🎨 editable freehand drawings for notes and text exams
Browse files at this commit3758bf0148b8615e523def58dbe39a06744cec77Parent: 93a44b7- feat
- 🎨 editable freehand drawings for notes and text exams
21 changed files +1183 -25
- AGENTS.md +6 -1
- src/api/__tests__/exams/exams.test.ts +56 -1
- src/api/client/types.ts +2 -0
- src/api/exams/deleteExamAttemptAnswerImage.ts +5 -0
- src/api/exams/getExamAnswerImageBlob.ts +5 -0
- src/api/exams/getExamQuestionImageBlob.ts +5 -0
- src/api/exams/index.ts +4 -0
- src/api/exams/postExamAttemptAnswerImage.ts +8 -0
- src/components/exams/answer-sheet-view.tsx +7 -0
- src/components/exams/exam-room-ws.tsx +137 -13
- src/components/exams/question-form.tsx +66 -2
- src/components/notes/note-files-panel.tsx +102 -8
- src/components/ui/draw-canvas.tsx +264 -0
- src/components/ui/icons.tsx +19 -0
- src/i18n/messages.ts +54 -0
- src/lib/draw-stroke.test.ts +131 -0
- src/lib/draw-stroke.ts +91 -0
- src/lib/drawing-file.test.ts +33 -0
- src/lib/drawing-file.ts +37 -0
- src/lib/png-meta.test.ts +63 -0
- src/lib/png-meta.ts +88 -0
AGENTS.mdmodified+6 -1
| @@ -36,7 +36,12 @@ instructions. Always written and read in English. | |||
| 36 | `note-card.test.tsx`. | 36 | `note-card.test.tsx`. |
| 37 | - Components in the same domain live in the same folder: `components/notes/`, | 37 | - Components in the same domain live in the same folder: `components/notes/`, |
| 38 | `components/events/`, `components/exams/`, `components/users/`, | 38 | `components/events/`, `components/exams/`, `components/users/`, |
| 39 | - `components/layout/`, `components/ui/`. | 39 | + `components/attendance/`, `components/courses/`, `components/marks/`, |
| 40 | + `components/sessions/`, `components/layout/`, `components/ui/`. | ||
| 41 | +- Cross-cutting app state lives in `src/stores/` (`auth-context.tsx`, | ||
| 42 | + `preferences-context.tsx`) — context providers only, never domain components. | ||
| 43 | + School-policy lists (exam kinds, attendance statuses, grade bands) come from | ||
| 44 | + `getSettings()` in a `createResource`, never hardcoded in components. | ||
| 40 | - **API layer:** Domain-based folders under `src/api/` (e.g., `src/api/notes/`, | 45 | - **API layer:** Domain-based folders under `src/api/` (e.g., `src/api/notes/`, |
| 41 | `src/api/exams/`). One file per request under its domain folder, camelCase and verb-first, | 46 | `src/api/exams/`). One file per request under its domain folder, camelCase and verb-first, |
| 42 | mirroring the endpoint exactly (`src/api/notes/getNoteById.ts`, | 47 | mirroring the endpoint exactly (`src/api/notes/getNoteById.ts`, |
src/api/__tests__/exams/exams.test.tsmodified+56 -1
| @@ -3,7 +3,11 @@ import { getExams } from "../../exams"; | |||
| 3 | import { getExamById } from "../../exams"; | 3 | import { getExamById } from "../../exams"; |
| 4 | import { patchExamById } from "../../exams"; | 4 | import { patchExamById } from "../../exams"; |
| 5 | import { deleteExamById } from "../../exams"; | 5 | import { deleteExamById } from "../../exams"; |
| 6 | -import { lastFetchCall, mockFetch204, mockFetchSuccess } from "../helpers/mock-fetch"; | 6 | +import { getExamQuestionImageBlob } from "../../exams"; |
| 7 | +import { postExamAttemptAnswerImage } from "../../exams"; | ||
| 8 | +import { deleteExamAttemptAnswerImage } from "../../exams"; | ||
| 9 | +import { getExamAnswerImageBlob } from "../../exams"; | ||
| 10 | +import { lastFetchCall, mockFetch204, mockFetchBlob, mockFetchSuccess } from "../helpers/mock-fetch"; | ||
| 7 | 11 | ||
| 8 | describe("exams API - core", () => { | 12 | describe("exams API - core", () => { |
| 9 | afterEach(() => { | 13 | afterEach(() => { |
| @@ -57,4 +61,55 @@ describe("exams API - core", () => { | |||
| 57 | expect(url).toBe("/api/exams/ex1"); | 61 | expect(url).toBe("/api/exams/ex1"); |
| 58 | expect(init?.method).toBe("DELETE"); | 62 | expect(init?.method).toBe("DELETE"); |
| 59 | }); | 63 | }); |
| 64 | + | ||
| 65 | + it("getExamQuestionImageBlob fetches the question image blob", async () => { | ||
| 66 | + const blob = new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }); | ||
| 67 | + mockFetchBlob(blob); | ||
| 68 | + | ||
| 69 | + const result = await getExamQuestionImageBlob("ex1", "q1"); | ||
| 70 | + expect(result).toBeInstanceOf(Blob); | ||
| 71 | + | ||
| 72 | + const [url, init] = lastFetchCall(); | ||
| 73 | + expect(url).toBe("/api/exams/ex1/questions/q1/image"); | ||
| 74 | + expect(init?.method ?? "GET").toBe("GET"); | ||
| 75 | + expect(init?.credentials).toBe("same-origin"); | ||
| 76 | + }); | ||
| 77 | + | ||
| 78 | + it("postExamAttemptAnswerImage calls /exams/:id/attempt/answers/:qid/image with FormData", async () => { | ||
| 79 | + const mockMeta = { content_type: "image/png", size: 100 }; | ||
| 80 | + mockFetchSuccess(mockMeta); | ||
| 81 | + | ||
| 82 | + const file = new File(["test"], "answer.png", { type: "image/png" }); | ||
| 83 | + const result = await postExamAttemptAnswerImage("ex1", "q1", file); | ||
| 84 | + expect(result).toEqual(mockMeta); | ||
| 85 | + | ||
| 86 | + const [url, init] = lastFetchCall(); | ||
| 87 | + expect(url).toBe("/api/exams/ex1/attempt/answers/q1/image"); | ||
| 88 | + expect(init?.method).toBe("POST"); | ||
| 89 | + expect(init?.body).toBeInstanceOf(FormData); | ||
| 90 | + expect((init?.body as FormData).get("file")).toBe(file); | ||
| 91 | + }); | ||
| 92 | + | ||
| 93 | + it("deleteExamAttemptAnswerImage calls /exams/:id/attempt/answers/:qid/image", async () => { | ||
| 94 | + mockFetch204(); | ||
| 95 | + | ||
| 96 | + await deleteExamAttemptAnswerImage("ex1", "q1"); | ||
| 97 | + | ||
| 98 | + const [url, init] = lastFetchCall(); | ||
| 99 | + expect(url).toBe("/api/exams/ex1/attempt/answers/q1/image"); | ||
| 100 | + expect(init?.method).toBe("DELETE"); | ||
| 101 | + }); | ||
| 102 | + | ||
| 103 | + it("getExamAnswerImageBlob fetches the student's own answer image blob", async () => { | ||
| 104 | + const blob = new Blob([new Uint8Array([0x89, 0x50, 0x4e, 0x47])], { type: "image/png" }); | ||
| 105 | + mockFetchBlob(blob); | ||
| 106 | + | ||
| 107 | + const result = await getExamAnswerImageBlob("ex1", "q1"); | ||
| 108 | + expect(result).toBeInstanceOf(Blob); | ||
| 109 | + | ||
| 110 | + const [url, init] = lastFetchCall(); | ||
| 111 | + expect(url).toBe("/api/exams/ex1/attempt/answers/q1/image"); | ||
| 112 | + expect(init?.method ?? "GET").toBe("GET"); | ||
| 113 | + expect(init?.credentials).toBe("same-origin"); | ||
| 114 | + }); | ||
| 60 | }); | 115 | }); |
src/api/client/types.tsmodified+2 -0
| @@ -196,6 +196,7 @@ export type AttemptAnswer = { | |||
| 196 | selected?: number | null; | 196 | selected?: number | null; |
| 197 | text?: string | null; | 197 | text?: string | null; |
| 198 | updated_at?: number; | 198 | updated_at?: number; |
| 199 | + answer_image?: ImageMeta | null; | ||
| 199 | }; | 200 | }; |
| 200 | 201 | ||
| 201 | export type AttemptQuestionResponse = { | 202 | export type AttemptQuestionResponse = { |
| @@ -303,6 +304,7 @@ export type StudentAnswer = { | |||
| 303 | text: string | null; | 304 | text: string | null; |
| 304 | updated_at: number; | 305 | updated_at: number; |
| 305 | is_correct: boolean | null; | 306 | is_correct: boolean | null; |
| 307 | + answer_image?: ImageMeta | null; | ||
| 306 | }; | 308 | }; |
| 307 | 309 | ||
| 308 | export type StudentAnswerSheet = { | 310 | export type StudentAnswerSheet = { |
src/api/exams/deleteExamAttemptAnswerImage.tsadded+5 -0
| @@ -0,0 +1,5 @@ | |||
| 1 | +import { client } from "../client"; | ||
| 2 | + | ||
| 3 | +export function deleteExamAttemptAnswerImage(examId: string, questionId: string): Promise<void> { | ||
| 4 | + return client<void>(`/exams/${examId}/attempt/answers/${questionId}/image`, { method: "DELETE" }); | ||
| 5 | +} | ||
src/api/exams/getExamAnswerImageBlob.tsadded+5 -0
| @@ -0,0 +1,5 @@ | |||
| 1 | +import { blobClient } from "../client"; | ||
| 2 | + | ||
| 3 | +export async function getExamAnswerImageBlob(examId: string, questionId: string, signal?: AbortSignal): Promise<Blob> { | ||
| 4 | + return blobClient(`/exams/${examId}/attempt/answers/${questionId}/image`, signal); | ||
| 5 | +} | ||
src/api/exams/getExamQuestionImageBlob.tsadded+5 -0
| @@ -0,0 +1,5 @@ | |||
| 1 | +import { blobClient } from "../client"; | ||
| 2 | + | ||
| 3 | +export function getExamQuestionImageBlob(examId: string, questionId: string, signal?: AbortSignal): Promise<Blob> { | ||
| 4 | + return blobClient(`/exams/${examId}/questions/${questionId}/image`, signal); | ||
| 5 | +} | ||
src/api/exams/index.tsmodified+4 -0
| @@ -7,6 +7,7 @@ export * from "./postExamQuestion"; | |||
| 7 | export * from "./patchExamQuestionById"; | 7 | export * from "./patchExamQuestionById"; |
| 8 | export * from "./deleteExamQuestionById"; | 8 | export * from "./deleteExamQuestionById"; |
| 9 | export * from "./postExamQuestionImage"; | 9 | export * from "./postExamQuestionImage"; |
| 10 | +export * from "./getExamQuestionImageBlob"; | ||
| 10 | export * from "./deleteExamQuestionImage"; | 11 | export * from "./deleteExamQuestionImage"; |
| 11 | export * from "./postExamChoiceImage"; | 12 | export * from "./postExamChoiceImage"; |
| 12 | export * from "./deleteExamChoiceImage"; | 13 | export * from "./deleteExamChoiceImage"; |
| @@ -23,3 +24,6 @@ export * from "./postExamAttempt"; | |||
| 23 | export * from "./postExamAttemptFinish"; | 24 | export * from "./postExamAttemptFinish"; |
| 24 | export * from "./getExamAttemptQuestions"; | 25 | export * from "./getExamAttemptQuestions"; |
| 25 | export * from "./postExamAttemptAnswer"; | 26 | export * from "./postExamAttemptAnswer"; |
| 27 | +export * from "./postExamAttemptAnswerImage"; | ||
| 28 | +export * from "./deleteExamAttemptAnswerImage"; | ||
| 29 | +export * from "./getExamAnswerImageBlob"; | ||
src/api/exams/postExamAttemptAnswerImage.tsadded+8 -0
| @@ -0,0 +1,8 @@ | |||
| 1 | +import { formClient } from "../client"; | ||
| 2 | +import type { ImageMeta } from "../client"; | ||
| 3 | + | ||
| 4 | +export function postExamAttemptAnswerImage(examId: string, questionId: string, file: File, signal?: AbortSignal): Promise<ImageMeta> { | ||
| 5 | + const body = new FormData(); | ||
| 6 | + body.append("file", file); | ||
| 7 | + return formClient<ImageMeta>(`/exams/${examId}/attempt/answers/${questionId}/image`, body, signal); | ||
| 8 | +} | ||
src/components/exams/answer-sheet-view.tsxmodified+7 -0
| @@ -81,6 +81,13 @@ export function AnswerSheetView(props: { examId: string; userId: string }) { | |||
| 81 | <div class="rounded-sm bg-muted/40 p-3"> | 81 | <div class="rounded-sm bg-muted/40 p-3"> |
| 82 | <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p> | 82 | <p class="text-xs text-muted-foreground">{t("exams.textAnswer")}</p> |
| 83 | <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p> | 83 | <p class="mt-1 whitespace-pre-wrap text-sm">{row.answer?.text || "—"}</p> |
| 84 | + <Show when={row.answer?.answer_image}> | ||
| 85 | + <img | ||
| 86 | + src={`/api/exams/${d().sheet.exam}/attempts/${d().sheet.user.id}/answers/${row.question.id}/image`} | ||
| 87 | + alt={t("exams.drawAnswer")} | ||
| 88 | + class="mt-3 h-64 w-full max-w-2xl rounded-md border bg-background object-contain" | ||
| 89 | + /> | ||
| 90 | + </Show> | ||
| 84 | </div> | 91 | </div> |
| 85 | } | 92 | } |
| 86 | > | 93 | > |
src/components/exams/exam-room-ws.tsxmodified+137 -13
| @@ -1,15 +1,20 @@ | |||
| 1 | -import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createSignal, onCleanup } from "solid-js"; | 1 | +import { For, Match, Show, Suspense, Switch, createEffect, createMemo, createSignal, lazy, onCleanup } from "solid-js"; |
| 2 | import { getExamAttempt } from "@/api/exams"; | 2 | import { getExamAttempt } from "@/api/exams"; |
| 3 | import { getExamAttemptQuestions } from "@/api/exams"; | 3 | import { getExamAttemptQuestions } from "@/api/exams"; |
| 4 | import { postExamAttempt } from "@/api/exams"; | 4 | import { postExamAttempt } from "@/api/exams"; |
| 5 | import { postExamAttemptAnswer } from "@/api/exams"; | 5 | import { postExamAttemptAnswer } from "@/api/exams"; |
| 6 | import { postExamAttemptFinish } from "@/api/exams"; | 6 | import { postExamAttemptFinish } from "@/api/exams"; |
| 7 | +import { postExamAttemptAnswerImage } from "@/api/exams"; | ||
| 8 | +import { deleteExamAttemptAnswerImage } from "@/api/exams"; | ||
| 9 | +import { getExamAnswerImageBlob } from "@/api/exams"; | ||
| 7 | import { formatApiError, formatApiErrorMessage } from "@/api/client"; | 10 | import { formatApiError, formatApiErrorMessage } from "@/api/client"; |
| 8 | import type { AttemptQuestion, Exam, ExamAttempt } from "@/api/client"; | 11 | import type { AttemptQuestion, Exam, ExamAttempt } from "@/api/client"; |
| 12 | +import type { DrawScene } from "@/lib/draw-stroke"; | ||
| 9 | import { Badge } from "@/components/ui/badge"; | 13 | import { Badge } from "@/components/ui/badge"; |
| 10 | import { Button } from "@/components/ui/button"; | 14 | import { Button } from "@/components/ui/button"; |
| 11 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 15 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 12 | -import { IconAlert, IconChevronLeft, IconChevronRight } from "@/components/ui/icons"; | 16 | +import { FormDialog } from "@/components/ui/form-dialog"; |
| 17 | +import { IconAlert, IconChevronLeft, IconChevronRight, IconEdit, IconTrash } from "@/components/ui/icons"; | ||
| 13 | import { PageSpinner } from "@/components/ui/page-spinner"; | 18 | import { PageSpinner } from "@/components/ui/page-spinner"; |
| 14 | import { Textarea } from "@/components/ui/textarea"; | 19 | import { Textarea } from "@/components/ui/textarea"; |
| 15 | import { cn } from "@/lib/cn"; | 20 | import { cn } from "@/lib/cn"; |
| @@ -17,6 +22,9 @@ import { createNow } from "@/lib/create-now"; | |||
| 17 | import { formatDateTime } from "@/lib/format"; | 22 | import { formatDateTime } from "@/lib/format"; |
| 18 | import { usePreferences, useT } from "@/stores/preferences-context"; | 23 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 19 | 24 | ||
| 25 | +// Lazy so the drawing pad rides its own chunk, off the exam room's initial load. | ||
| 26 | +const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); | ||
| 27 | + | ||
| 20 | type WsState = "connecting" | "connected" | "disconnected"; | 28 | type WsState = "connecting" | "connected" | "disconnected"; |
| 21 | type WsMessage = | 29 | type WsMessage = |
| 22 | | { type: "state"; status: string; deadline: number | null; remaining_ms: number | null; now: number; answered: number; question_count: number } | 30 | | { type: "state"; status: string; deadline: number | null; remaining_ms: number | null; now: number; answered: number; question_count: number } |
| @@ -207,6 +215,41 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 207 | } | 215 | } |
| 208 | }; | 216 | }; |
| 209 | 217 | ||
| 218 | + // A drawing is binary, so it skips the JSON WS/REST autosave: upload out-of-band, | ||
| 219 | + // then refetch so the answer's answer_image and updated_at badge catch up. | ||
| 220 | + const refreshAnswers = async () => { | ||
| 221 | + const next = await getExamAttempt(props.exam.id); | ||
| 222 | + setAttempt(next); | ||
| 223 | + const qs = await getExamAttemptQuestions(props.exam.id); | ||
| 224 | + setQuestions(qs); | ||
| 225 | + }; | ||
| 226 | + | ||
| 227 | + const saveAnswerImage = async (question: AttemptQuestion, file: File) => { | ||
| 228 | + setError(""); | ||
| 229 | + setPending(true); | ||
| 230 | + try { | ||
| 231 | + await postExamAttemptAnswerImage(props.exam.id, question.id, file); | ||
| 232 | + await refreshAnswers(); | ||
| 233 | + } catch (err) { | ||
| 234 | + setError(formatApiError(err, locale())); | ||
| 235 | + } finally { | ||
| 236 | + setPending(false); | ||
| 237 | + } | ||
| 238 | + }; | ||
| 239 | + | ||
| 240 | + const removeAnswerImage = async (question: AttemptQuestion) => { | ||
| 241 | + setError(""); | ||
| 242 | + setPending(true); | ||
| 243 | + try { | ||
| 244 | + await deleteExamAttemptAnswerImage(props.exam.id, question.id); | ||
| 245 | + await refreshAnswers(); | ||
| 246 | + } catch (err) { | ||
| 247 | + setError(formatApiError(err, locale())); | ||
| 248 | + } finally { | ||
| 249 | + setPending(false); | ||
| 250 | + } | ||
| 251 | + }; | ||
| 252 | + | ||
| 210 | const finish = async () => { | 253 | const finish = async () => { |
| 211 | setPending(true); | 254 | setPending(true); |
| 212 | setError(""); | 255 | setError(""); |
| @@ -359,6 +402,8 @@ export function ExamRoomWS(props: { exam: Exam }) { | |||
| 359 | disabled={!canWrite() || pending()} | 402 | disabled={!canWrite() || pending()} |
| 360 | onSave={(value) => saveAnswer(question(), value)} | 403 | onSave={(value) => saveAnswer(question(), value)} |
| 361 | onSaved={goNext} | 404 | onSaved={goNext} |
| 405 | + onSaveImage={(file) => saveAnswerImage(question(), file)} | ||
| 406 | + onRemoveImage={() => removeAnswerImage(question())} | ||
| 362 | /> | 407 | /> |
| 363 | <div class="flex items-center justify-between gap-2"> | 408 | <div class="flex items-center justify-between gap-2"> |
| 364 | <Button type="button" variant="outline" class="rounded-lg" disabled={activeQuestionIndex() === 0} onClick={goPrevious}> | 409 | <Button type="button" variant="outline" class="rounded-lg" disabled={activeQuestionIndex() === 0} onClick={goPrevious}> |
| @@ -539,6 +584,8 @@ function QuestionAnswerCardWS(props: { | |||
| 539 | disabled: boolean; | 584 | disabled: boolean; |
| 540 | onSave: (value: string) => Promise<void>; | 585 | onSave: (value: string) => Promise<void>; |
| 541 | onSaved?: () => void; | 586 | onSaved?: () => void; |
| 587 | + onSaveImage: (file: File) => Promise<void>; | ||
| 588 | + onRemoveImage: () => Promise<void>; | ||
| 542 | }) { | 589 | }) { |
| 543 | const t = useT(); | 590 | const t = useT(); |
| 544 | const { locale } = usePreferences(); | 591 | const { locale } = usePreferences(); |
| @@ -550,6 +597,8 @@ function QuestionAnswerCardWS(props: { | |||
| 550 | : props.question.answer?.text ?? "", | 597 | : props.question.answer?.text ?? "", |
| 551 | ); | 598 | ); |
| 552 | const [saved, setSaved] = createSignal(false); | 599 | const [saved, setSaved] = createSignal(false); |
| 600 | + const [drawOpen, setDrawOpen] = createSignal(false); | ||
| 601 | + const [editScene, setEditScene] = createSignal<DrawScene | null>(null); | ||
| 553 | let questionId = props.question.id; | 602 | let questionId = props.question.id; |
| 554 | 603 | ||
| 555 | createEffect(() => { | 604 | createEffect(() => { |
| @@ -563,6 +612,8 @@ function QuestionAnswerCardWS(props: { | |||
| 563 | : props.question.answer?.text ?? "", | 612 | : props.question.answer?.text ?? "", |
| 564 | ); | 613 | ); |
| 565 | setSaved(false); | 614 | setSaved(false); |
| 615 | + setDrawOpen(false); | ||
| 616 | + setEditScene(null); | ||
| 566 | }); | 617 | }); |
| 567 | 618 | ||
| 568 | const save = async () => { | 619 | const save = async () => { |
| @@ -571,6 +622,30 @@ function QuestionAnswerCardWS(props: { | |||
| 571 | props.onSaved?.(); | 622 | props.onSaved?.(); |
| 572 | }; | 623 | }; |
| 573 | 624 | ||
| 625 | + const openNewDrawing = () => { | ||
| 626 | + setEditScene(null); | ||
| 627 | + setDrawOpen(true); | ||
| 628 | + }; | ||
| 629 | + | ||
| 630 | + // Reload the stored PNG's embedded scene so the pad reopens on the saved drawing. | ||
| 631 | + const openEditDrawing = async () => { | ||
| 632 | + try { | ||
| 633 | + const blob = await getExamAnswerImageBlob(props.question.exam, props.question.id); | ||
| 634 | + const { pngBytesToScene } = await import("@/lib/drawing-file"); | ||
| 635 | + setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); | ||
| 636 | + } catch { | ||
| 637 | + setEditScene(null); // plain image or fetch failed → start blank, never crash | ||
| 638 | + } finally { | ||
| 639 | + setDrawOpen(true); | ||
| 640 | + } | ||
| 641 | + }; | ||
| 642 | + | ||
| 643 | + const saveDrawing = async (file: File) => { | ||
| 644 | + await props.onSaveImage(file); | ||
| 645 | + setEditScene(null); | ||
| 646 | + setDrawOpen(false); | ||
| 647 | + }; | ||
| 648 | + | ||
| 574 | return ( | 649 | return ( |
| 575 | <article id={`question-${props.question.id}`} class="surface-card min-h-[calc(100vh-16rem)] p-5 sm:p-6 lg:p-8"> | 650 | <article id={`question-${props.question.id}`} class="surface-card min-h-[calc(100vh-16rem)] p-5 sm:p-6 lg:p-8"> |
| 576 | <div class="mb-3 flex flex-wrap items-center gap-2"> | 651 | <div class="mb-3 flex flex-wrap items-center gap-2"> |
| @@ -594,17 +669,48 @@ function QuestionAnswerCardWS(props: { | |||
| 594 | <Show | 669 | <Show |
| 595 | when={props.question.kind === "choice"} | 670 | when={props.question.kind === "choice"} |
| 596 | fallback={ | 671 | fallback={ |
| 597 | - <Textarea | 672 | + <div class="space-y-3"> |
| 598 | - class="min-h-32" | 673 | + <Textarea |
| 599 | - value={value()} | 674 | + class="min-h-32" |
| 600 | - rows={4} | 675 | + value={value()} |
| 601 | - disabled={props.disabled} | 676 | + rows={4} |
| 602 | - maxlength={10000} | 677 | + disabled={props.disabled} |
| 603 | - onInput={(e) => { | 678 | + maxlength={10000} |
| 604 | - setSaved(false); | 679 | + onInput={(e) => { |
| 605 | - setValue(e.currentTarget.value); | 680 | + setSaved(false); |
| 606 | - }} | 681 | + setValue(e.currentTarget.value); |
| 607 | - /> | 682 | + }} |
| 683 | + /> | ||
| 684 | + <Show when={props.question.answer?.answer_image}> | ||
| 685 | + <img | ||
| 686 | + src={`/api/exams/${props.question.exam}/attempt/answers/${props.question.id}/image`} | ||
| 687 | + alt={t("exams.drawAnswer")} | ||
| 688 | + class="h-64 w-full max-w-2xl rounded-md border bg-muted/20 object-contain" | ||
| 689 | + /> | ||
| 690 | + </Show> | ||
| 691 | + <Show when={!props.disabled}> | ||
| 692 | + <div class="flex flex-wrap items-center gap-2"> | ||
| 693 | + <Show | ||
| 694 | + when={props.question.answer?.answer_image} | ||
| 695 | + fallback={ | ||
| 696 | + <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={openNewDrawing}> | ||
| 697 | + <IconEdit class="h-4 w-4" /> | ||
| 698 | + {t("exams.drawAnswer")} | ||
| 699 | + </Button> | ||
| 700 | + } | ||
| 701 | + > | ||
| 702 | + <Button type="button" variant="outline" size="sm" class="rounded-lg" onClick={() => void openEditDrawing()}> | ||
| 703 | + <IconEdit class="h-4 w-4" /> | ||
| 704 | + {t("exams.editDrawing")} | ||
| 705 | + </Button> | ||
| 706 | + <Button type="button" variant="outline" size="sm" class="rounded-lg text-destructive hover:text-destructive" onClick={() => void props.onRemoveImage()}> | ||
| 707 | + <IconTrash class="h-4 w-4" /> | ||
| 708 | + {t("exams.removeDrawing")} | ||
| 709 | + </Button> | ||
| 710 | + </Show> | ||
| 711 | + </div> | ||
| 712 | + </Show> | ||
| 713 | + </div> | ||
| 608 | } | 714 | } |
| 609 | > | 715 | > |
| 610 | <div class="space-y-2"> | 716 | <div class="space-y-2"> |
| @@ -646,6 +752,24 @@ function QuestionAnswerCardWS(props: { | |||
| 646 | > | 752 | > |
| 647 | {t("attempt.saveAnswer")} | 753 | {t("attempt.saveAnswer")} |
| 648 | </Button> | 754 | </Button> |
| 755 | + <FormDialog | ||
| 756 | + open={drawOpen()} | ||
| 757 | + onOpenChange={(open) => { | ||
| 758 | + setDrawOpen(open); | ||
| 759 | + if (!open) setEditScene(null); | ||
| 760 | + }} | ||
| 761 | + title={t("exams.drawAnswer")} | ||
| 762 | + class="sm:max-w-3xl" | ||
| 763 | + > | ||
| 764 | + <Suspense fallback={<PageSpinner />}> | ||
| 765 | + <DrawCanvas | ||
| 766 | + pending={props.disabled} | ||
| 767 | + initialScene={editScene()} | ||
| 768 | + fileName="answer.png" | ||
| 769 | + onSave={(file) => void saveDrawing(file)} | ||
| 770 | + /> | ||
| 771 | + </Suspense> | ||
| 772 | + </FormDialog> | ||
| 649 | </article> | 773 | </article> |
| 650 | ); | 774 | ); |
| 651 | } | 775 | } |
src/components/exams/question-form.tsxmodified+66 -2
| @@ -1,9 +1,11 @@ | |||
| 1 | -import { For, Index, Show, createEffect, createSignal } from "solid-js"; | 1 | +import { For, Index, Show, Suspense, createEffect, createSignal, lazy } from "solid-js"; |
| 2 | import { formatApiError } from "@/api/client"; | 2 | import { formatApiError } from "@/api/client"; |
| 3 | import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; | 3 | import type { ExamQuestion, QuestionKind, Subject } from "@/api/client"; |
| 4 | import { QUESTION_KINDS } from "@/api/client"; | 4 | import { QUESTION_KINDS } from "@/api/client"; |
| 5 | +import { getExamQuestionImageBlob } from "@/api/exams"; | ||
| 6 | +import type { DrawScene } from "@/lib/draw-stroke"; | ||
| 5 | import { Button } from "@/components/ui/button"; | 7 | import { Button } from "@/components/ui/button"; |
| 6 | -import { IconCheck, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons"; | 8 | +import { IconCheck, IconEdit, IconFileImage, IconPlus, IconTrash } from "@/components/ui/icons"; |
| 7 | import { Input } from "@/components/ui/input"; | 9 | import { Input } from "@/components/ui/input"; |
| 8 | import { Label } from "@/components/ui/label"; | 10 | import { Label } from "@/components/ui/label"; |
| 9 | import { Select } from "@/components/ui/select"; | 11 | import { Select } from "@/components/ui/select"; |
| @@ -11,6 +13,9 @@ import { Textarea } from "@/components/ui/textarea"; | |||
| 11 | import { cn } from "@/lib/cn"; | 13 | import { cn } from "@/lib/cn"; |
| 12 | import { useT } from "@/stores/preferences-context"; | 14 | import { useT } from "@/stores/preferences-context"; |
| 13 | 15 | ||
| 16 | +// Lazy so the drawing pad rides its own chunk, off the exam editor's initial load. | ||
| 17 | +const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); | ||
| 18 | + | ||
| 14 | export type QuestionValues = { | 19 | export type QuestionValues = { |
| 15 | subject_id: string; | 20 | subject_id: string; |
| 16 | text: string; | 21 | text: string; |
| @@ -37,6 +42,8 @@ export function QuestionForm(props: { | |||
| 37 | const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]); | 42 | const [choices, setChoices] = createSignal<string[]>(props.initial?.choices ?? ["", "", "", ""]); |
| 38 | const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0); | 43 | const [correct, setCorrect] = createSignal(props.initial?.correct ?? 0); |
| 39 | const [image, setImage] = createSignal<File | null>(null); | 44 | const [image, setImage] = createSignal<File | null>(null); |
| 45 | + const [drawing, setDrawing] = createSignal(false); | ||
| 46 | + const [editScene, setEditScene] = createSignal<DrawScene | null>(null); | ||
| 40 | const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); | 47 | const [choiceImages, setChoiceImages] = createSignal<(File | null)[]>(choices().map(() => null)); |
| 41 | const [error, setError] = createSignal(""); | 48 | const [error, setError] = createSignal(""); |
| 42 | const [pending, setPending] = createSignal(false); | 49 | const [pending, setPending] = createSignal(false); |
| @@ -50,10 +57,33 @@ export function QuestionForm(props: { | |||
| 50 | setChoices(initial?.choices ?? ["", "", "", ""]); | 57 | setChoices(initial?.choices ?? ["", "", "", ""]); |
| 51 | setCorrect(initial?.correct ?? 0); | 58 | setCorrect(initial?.correct ?? 0); |
| 52 | setImage(null); | 59 | setImage(null); |
| 60 | + setDrawing(false); | ||
| 61 | + setEditScene(null); | ||
| 53 | setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); | 62 | setChoiceImages((initial?.choices ?? ["", "", "", ""]).map(() => null)); |
| 54 | setError(""); | 63 | setError(""); |
| 55 | }); | 64 | }); |
| 56 | 65 | ||
| 66 | + // Blank pad for a fresh drawing; reload the stored scene to edit an existing one. | ||
| 67 | + const startDrawing = () => { | ||
| 68 | + setEditScene(null); | ||
| 69 | + setDrawing((open) => !open); | ||
| 70 | + }; | ||
| 71 | + | ||
| 72 | + const editDrawing = async () => { | ||
| 73 | + const q = props.initial; | ||
| 74 | + if (!q?.image) return; | ||
| 75 | + setError(""); | ||
| 76 | + try { | ||
| 77 | + const blob = await getExamQuestionImageBlob(q.exam, q.id); | ||
| 78 | + const { pngBytesToScene } = await import("@/lib/drawing-file"); | ||
| 79 | + setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); | ||
| 80 | + } catch { | ||
| 81 | + setEditScene(null); // plain image or fetch failed → start blank, never crash | ||
| 82 | + } finally { | ||
| 83 | + setDrawing(true); | ||
| 84 | + } | ||
| 85 | + }; | ||
| 86 | + | ||
| 57 | const resizeTextArea = () => { | 87 | const resizeTextArea = () => { |
| 58 | if (!textAreaRef) return; | 88 | if (!textAreaRef) return; |
| 59 | textAreaRef.style.height = "auto"; | 89 | textAreaRef.style.height = "auto"; |
| @@ -166,8 +196,42 @@ export function QuestionForm(props: { | |||
| 166 | <IconFileImage class="h-3.5 w-3.5" /> | 196 | <IconFileImage class="h-3.5 w-3.5" /> |
| 167 | <span class="truncate">{image()?.name ?? t("questions.image")}</span> | 197 | <span class="truncate">{image()?.name ?? t("questions.image")}</span> |
| 168 | </label> | 198 | </label> |
| 199 | + <button | ||
| 200 | + type="button" | ||
| 201 | + aria-expanded={drawing()} | ||
| 202 | + class="flex items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" | ||
| 203 | + onClick={startDrawing} | ||
| 204 | + > | ||
| 205 | + <IconEdit class="h-3.5 w-3.5" /> | ||
| 206 | + {t("questions.draw")} | ||
| 207 | + </button> | ||
| 208 | + <Show when={props.initial?.image}> | ||
| 209 | + <button | ||
| 210 | + type="button" | ||
| 211 | + class="flex items-center gap-1.5 rounded-md border border-dashed bg-muted/30 px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground" | ||
| 212 | + onClick={() => void editDrawing()} | ||
| 213 | + > | ||
| 214 | + <IconEdit class="h-3.5 w-3.5" /> | ||
| 215 | + {t("questions.editDrawing")} | ||
| 216 | + </button> | ||
| 217 | + </Show> | ||
| 169 | </div> | 218 | </div> |
| 170 | </div> | 219 | </div> |
| 220 | + <Show when={drawing()}> | ||
| 221 | + <div class="mt-3 border-t border-border/50 pt-3"> | ||
| 222 | + <Label class="mb-2 block text-xs font-semibold text-muted-foreground">{t("questions.drawTitle")}</Label> | ||
| 223 | + <Suspense fallback={<div class="h-[22rem] animate-pulse rounded-lg border bg-muted/20" />}> | ||
| 224 | + <DrawCanvas | ||
| 225 | + fileName="question.png" | ||
| 226 | + initialScene={editScene()} | ||
| 227 | + onSave={(file) => { | ||
| 228 | + setImage(file); | ||
| 229 | + setDrawing(false); | ||
| 230 | + }} | ||
| 231 | + /> | ||
| 232 | + </Suspense> | ||
| 233 | + </div> | ||
| 234 | + </Show> | ||
| 171 | </div> | 235 | </div> |
| 172 | </div> | 236 | </div> |
| 173 | 237 | ||
src/components/notes/note-files-panel.tsxmodified+102 -8
| @@ -1,18 +1,22 @@ | |||
| 1 | -import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, type JSX } from "solid-js"; | 1 | +import { For, Show, Suspense, createEffect, createMemo, createResource, createSignal, lazy, type JSX } from "solid-js"; |
| 2 | import { deleteNoteFileById } from "@/api/notes"; | 2 | import { deleteNoteFileById } from "@/api/notes"; |
| 3 | +import { getNoteFileBlob } from "@/api/notes"; | ||
| 3 | import { getNoteFileUrl } from "@/api/notes"; | 4 | import { getNoteFileUrl } from "@/api/notes"; |
| 4 | import { getNoteFiles } from "@/api/notes"; | 5 | import { getNoteFiles } from "@/api/notes"; |
| 5 | import { getSettings } from "@/api/settings"; | 6 | import { getSettings } from "@/api/settings"; |
| 6 | import { postNoteFile } from "@/api/notes"; | 7 | import { postNoteFile } from "@/api/notes"; |
| 7 | import { formatApiError } from "@/api/client"; | 8 | import { formatApiError } from "@/api/client"; |
| 8 | import type { NoteFile } from "@/api/client"; | 9 | import type { NoteFile } from "@/api/client"; |
| 10 | +import type { DrawScene } from "@/lib/draw-stroke"; | ||
| 9 | import { NoteFilePreview } from "@/components/notes/note-file-preview"; | 11 | import { NoteFilePreview } from "@/components/notes/note-file-preview"; |
| 10 | import { Alert } from "@/components/ui/alert"; | 12 | import { Alert } from "@/components/ui/alert"; |
| 11 | import { Button } from "@/components/ui/button"; | 13 | import { Button } from "@/components/ui/button"; |
| 12 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; | 14 | import { ConfirmDialog } from "@/components/ui/confirm-dialog"; |
| 15 | +import { FormDialog } from "@/components/ui/form-dialog"; | ||
| 13 | import { createFlash } from "@/lib/flash"; | 16 | import { createFlash } from "@/lib/flash"; |
| 14 | import { | 17 | import { |
| 15 | IconDownload, | 18 | IconDownload, |
| 19 | + IconEdit, | ||
| 16 | IconEye, | 20 | IconEye, |
| 17 | IconFileAudio, | 21 | IconFileAudio, |
| 18 | IconFileImage, | 22 | IconFileImage, |
| @@ -29,9 +33,16 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; | |||
| 29 | import { cn } from "@/lib/cn"; | 33 | import { cn } from "@/lib/cn"; |
| 30 | import { useT } from "@/stores/preferences-context"; | 34 | import { useT } from "@/stores/preferences-context"; |
| 31 | 35 | ||
| 36 | +// Lazy so the drawing pad rides its own chunk, off the notes page's initial load. | ||
| 37 | +const DrawCanvas = lazy(() => import("@/components/ui/draw-canvas").then((m) => ({ default: m.DrawCanvas }))); | ||
| 38 | + | ||
| 32 | const MAX_NOTE_FILES = 10; | 39 | const MAX_NOTE_FILES = 10; |
| 33 | const FILE_PAGE_SIZE = 4; | 40 | const FILE_PAGE_SIZE = 4; |
| 34 | 41 | ||
| 42 | +/** Drawings are saved with this suffix so the grid can offer "Edit" without fetching every blob. */ | ||
| 43 | +const DRAWING_SUFFIX = ".hzdraw.png"; | ||
| 44 | +const isDrawing = (file: NoteFile) => file.name.toLowerCase().endsWith(DRAWING_SUFFIX); | ||
| 45 | + | ||
| 35 | function formatBytes(bytes: number): string { | 46 | function formatBytes(bytes: number): string { |
| 36 | if (bytes < 1024) return `${bytes} B`; | 47 | if (bytes < 1024) return `${bytes} B`; |
| 37 | if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; | 48 | if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`; |
| @@ -62,6 +73,9 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 62 | const [flash, setFlash] = createFlash(); | 73 | const [flash, setFlash] = createFlash(); |
| 63 | const [pending, setPending] = createSignal(false); | 74 | const [pending, setPending] = createSignal(false); |
| 64 | const [filePage, setFilePage] = createSignal(0); | 75 | const [filePage, setFilePage] = createSignal(0); |
| 76 | + const [drawOpen, setDrawOpen] = createSignal(false); | ||
| 77 | + const [editScene, setEditScene] = createSignal<DrawScene | null>(null); | ||
| 78 | + const [editTarget, setEditTarget] = createSignal<NoteFile | null>(null); | ||
| 65 | const [previewFile, setPreviewFile] = createSignal<NoteFile | null>(null); | 79 | const [previewFile, setPreviewFile] = createSignal<NoteFile | null>(null); |
| 66 | const [deleteTarget, setDeleteTarget] = createSignal<NoteFile | null>(null); | 80 | const [deleteTarget, setDeleteTarget] = createSignal<NoteFile | null>(null); |
| 67 | const [files, { refetch }] = createResource( | 81 | const [files, { refetch }] = createResource( |
| @@ -90,12 +104,12 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 90 | if (filePage() >= totalPages()) setFilePage(totalPages() - 1); | 104 | if (filePage() >= totalPages()) setFilePage(totalPages() - 1); |
| 91 | }); | 105 | }); |
| 92 | 106 | ||
| 93 | - const upload = async (file: File | undefined) => { | 107 | + const upload = async (file: File | undefined): Promise<boolean> => { |
| 94 | - if (!file) return; | 108 | + if (!file) return false; |
| 95 | setError(""); | 109 | setError(""); |
| 96 | if (file.size > maxFileBytes()) { | 110 | if (file.size > maxFileBytes()) { |
| 97 | setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); | 111 | setError(t("notes.fileTooLarge", { size: formatBytes(maxFileBytes()) })); |
| 98 | - return; | 112 | + return false; |
| 99 | } | 113 | } |
| 100 | setPending(true); | 114 | setPending(true); |
| 101 | try { | 115 | try { |
| @@ -103,8 +117,10 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 103 | await refetch(); | 117 | await refetch(); |
| 104 | if (input) input.value = ""; | 118 | if (input) input.value = ""; |
| 105 | setFlash(t("common.created")); | 119 | setFlash(t("common.created")); |
| 120 | + return true; | ||
| 106 | } catch (err) { | 121 | } catch (err) { |
| 107 | setError(formatApiError(err)); | 122 | setError(formatApiError(err)); |
| 123 | + return false; | ||
| 108 | } finally { | 124 | } finally { |
| 109 | setPending(false); | 125 | setPending(false); |
| 110 | } | 126 | } |
| @@ -117,6 +133,44 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 117 | link.click(); | 133 | link.click(); |
| 118 | }; | 134 | }; |
| 119 | 135 | ||
| 136 | + const openNewDrawing = () => { | ||
| 137 | + setEditScene(null); | ||
| 138 | + setEditTarget(null); | ||
| 139 | + setDrawOpen(true); | ||
| 140 | + }; | ||
| 141 | + | ||
| 142 | + const openEditDrawing = async (file: NoteFile) => { | ||
| 143 | + setError(""); | ||
| 144 | + try { | ||
| 145 | + const blob = await getNoteFileBlob(props.noteId, file.id); | ||
| 146 | + const { pngBytesToScene } = await import("@/lib/drawing-file"); | ||
| 147 | + setEditScene(pngBytesToScene(new Uint8Array(await blob.arrayBuffer()))); | ||
| 148 | + setEditTarget(file); | ||
| 149 | + setDrawOpen(true); | ||
| 150 | + } catch (err) { | ||
| 151 | + setError(formatApiError(err)); | ||
| 152 | + } | ||
| 153 | + }; | ||
| 154 | + | ||
| 155 | + // Create-new-then-delete-old: the replacement must be safely stored before the | ||
| 156 | + // original is removed, so a failed upload never loses the existing drawing. | ||
| 157 | + const saveDrawing = async (file: File) => { | ||
| 158 | + const target = editTarget(); | ||
| 159 | + if (!(await upload(file))) return; | ||
| 160 | + if (target) { | ||
| 161 | + try { | ||
| 162 | + await deleteNoteFileById(props.noteId, target.id); | ||
| 163 | + await refetch(); | ||
| 164 | + } catch { | ||
| 165 | + // New drawing is saved; deleting the old copy failed — a stale duplicate | ||
| 166 | + // remains, but nothing is lost. Leave it rather than risk the new one. | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + setEditScene(null); | ||
| 170 | + setEditTarget(null); | ||
| 171 | + setDrawOpen(false); | ||
| 172 | + }; | ||
| 173 | + | ||
| 120 | return ( | 174 | return ( |
| 121 | <section class="space-y-3 rounded-2xl border border-border/70 bg-card/80 p-4 shadow-sm"> | 175 | <section class="space-y-3 rounded-2xl border border-border/70 bg-card/80 p-4 shadow-sm"> |
| 122 | <Show when={flash()}> | 176 | <Show when={flash()}> |
| @@ -136,10 +190,16 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 136 | disabled={pending() || atLimit()} | 190 | disabled={pending() || atLimit()} |
| 137 | onChange={(event) => void upload(event.currentTarget.files?.[0])} | 191 | onChange={(event) => void upload(event.currentTarget.files?.[0])} |
| 138 | /> | 192 | /> |
| 139 | - <Button type="button" size="sm" class="rounded-md" disabled={pending() || atLimit()} onClick={() => input?.click()}> | 193 | + <div class="flex flex-wrap items-center gap-2"> |
| 140 | - <IconPlus class="h-4 w-4" /> | 194 | + <Button type="button" variant="outline" size="sm" class="rounded-md" disabled={pending() || atLimit()} onClick={openNewDrawing}> |
| 141 | - {t("notes.addFile")} | 195 | + <IconEdit class="h-4 w-4" /> |
| 142 | - </Button> | 196 | + {t("notes.draw")} |
| 197 | + </Button> | ||
| 198 | + <Button type="button" size="sm" class="rounded-md" disabled={pending() || atLimit()} onClick={() => input?.click()}> | ||
| 199 | + <IconPlus class="h-4 w-4" /> | ||
| 200 | + {t("notes.addFile")} | ||
| 201 | + </Button> | ||
| 202 | + </div> | ||
| 143 | </div> | 203 | </div> |
| 144 | 204 | ||
| 145 | {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>} | 205 | {error() && <p class="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p>} |
| @@ -175,6 +235,15 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 175 | <TableRowActions | 235 | <TableRowActions |
| 176 | label={t("common.actions")} | 236 | label={t("common.actions")} |
| 177 | actions={[ | 237 | actions={[ |
| 238 | + ...(isDrawing(file) | ||
| 239 | + ? [ | ||
| 240 | + { | ||
| 241 | + label: t("common.edit"), | ||
| 242 | + icon: <IconEdit class="h-4 w-4" />, | ||
| 243 | + onSelect: () => void openEditDrawing(file), | ||
| 244 | + }, | ||
| 245 | + ] | ||
| 246 | + : []), | ||
| 178 | { | 247 | { |
| 179 | label: t("common.view"), | 248 | label: t("common.view"), |
| 180 | icon: <IconEye class="h-4 w-4" />, | 249 | icon: <IconEye class="h-4 w-4" />, |
| @@ -211,6 +280,31 @@ export function NoteFilesPanel(props: { noteId: string; active: boolean }) { | |||
| 211 | </Show> | 280 | </Show> |
| 212 | </Suspense> | 281 | </Suspense> |
| 213 | 282 | ||
| 283 | + <FormDialog | ||
| 284 | + open={drawOpen()} | ||
| 285 | + onOpenChange={(open) => { | ||
| 286 | + setDrawOpen(open); | ||
| 287 | + if (!open) { | ||
| 288 | + setEditScene(null); | ||
| 289 | + setEditTarget(null); | ||
| 290 | + } | ||
| 291 | + }} | ||
| 292 | + title={t("notes.drawTitle")} | ||
| 293 | + class="sm:max-w-3xl" | ||
| 294 | + > | ||
| 295 | + <Show when={error()}> | ||
| 296 | + <p class="mb-3 rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">{error()}</p> | ||
| 297 | + </Show> | ||
| 298 | + <Suspense fallback={<PageSpinner />}> | ||
| 299 | + <DrawCanvas | ||
| 300 | + pending={pending()} | ||
| 301 | + initialScene={editScene()} | ||
| 302 | + fileName={editTarget()?.name ?? `drawing-${(files() ?? []).length + 1}${DRAWING_SUFFIX}`} | ||
| 303 | + onSave={(file) => void saveDrawing(file)} | ||
| 304 | + /> | ||
| 305 | + </Suspense> | ||
| 306 | + </FormDialog> | ||
| 307 | + | ||
| 214 | <ConfirmDialog | 308 | <ConfirmDialog |
| 215 | open={deleteTarget() != null} | 309 | open={deleteTarget() != null} |
| 216 | onOpenChange={(open) => !open && setDeleteTarget(null)} | 310 | onOpenChange={(open) => !open && setDeleteTarget(null)} |
src/components/ui/draw-canvas.tsxadded+264 -0
| @@ -0,0 +1,264 @@ | |||
| 1 | +import { For, Show, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js"; | ||
| 2 | +import { Button } from "@/components/ui/button"; | ||
| 3 | +import { IconDownload, IconEdit, IconEraser, IconSave, IconTrash, IconUndo } from "@/components/ui/icons"; | ||
| 4 | +import { cn } from "@/lib/cn"; | ||
| 5 | +import { paintStroke, paintTip, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; | ||
| 6 | +import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; | ||
| 7 | +import { useT } from "@/stores/preferences-context"; | ||
| 8 | + | ||
| 9 | +const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; | ||
| 10 | +const WIDTHS = [2, 6, 14]; | ||
| 11 | + | ||
| 12 | +/** | ||
| 13 | + * Freehand drawing pad. `props.onSave` receives a PNG `File` that both displays | ||
| 14 | + * as a normal image and carries its editable stroke JSON in a tEXt chunk, so the | ||
| 15 | + * same File feeds every existing upload seam (`postNoteFile`, | ||
| 16 | + * `postExamQuestionImage`) and a saved drawing can be reopened via `initialScene`. | ||
| 17 | + * PNG/JPEG buttons additionally download a flat image straight to the device. | ||
| 18 | + */ | ||
| 19 | +export function DrawCanvas(props: { | ||
| 20 | + onSave: (file: File) => void; | ||
| 21 | + initialScene?: DrawScene | null; | ||
| 22 | + fileName?: string; | ||
| 23 | + pending?: boolean; | ||
| 24 | + class?: string; | ||
| 25 | +}) { | ||
| 26 | + const t = useT(); | ||
| 27 | + let canvas: HTMLCanvasElement | undefined; | ||
| 28 | + let wrap: HTMLDivElement | undefined; | ||
| 29 | + let current: Stroke | undefined; | ||
| 30 | + | ||
| 31 | + const [strokes, setStrokes] = createSignal<Stroke[]>([]); | ||
| 32 | + const [color, setColor] = createSignal(COLORS[0]); | ||
| 33 | + const [width, setWidth] = createSignal(WIDTHS[1]); | ||
| 34 | + const [erasing, setErasing] = createSignal(false); | ||
| 35 | + | ||
| 36 | + const ratio = () => window.devicePixelRatio || 1; | ||
| 37 | + const context = () => canvas?.getContext("2d") ?? null; | ||
| 38 | + | ||
| 39 | + const redraw = () => { | ||
| 40 | + const c = context(); | ||
| 41 | + if (!c || !canvas) return; | ||
| 42 | + const scale = ratio(); | ||
| 43 | + c.setTransform(scale, 0, 0, scale, 0, 0); | ||
| 44 | + c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); | ||
| 45 | + for (const stroke of strokes()) paintStroke(c, stroke); | ||
| 46 | + if (current) paintStroke(c, current); | ||
| 47 | + }; | ||
| 48 | + | ||
| 49 | + // The backing store is DPR-scaled; without this strokes land blurry and offset. | ||
| 50 | + const resize = () => { | ||
| 51 | + if (!canvas) return; | ||
| 52 | + const rect = canvas.getBoundingClientRect(); | ||
| 53 | + if (rect.width === 0 || rect.height === 0) return; | ||
| 54 | + const scale = ratio(); | ||
| 55 | + canvas.width = Math.round(rect.width * scale); | ||
| 56 | + canvas.height = Math.round(rect.height * scale); | ||
| 57 | + redraw(); | ||
| 58 | + }; | ||
| 59 | + | ||
| 60 | + onMount(() => { | ||
| 61 | + resize(); | ||
| 62 | + const observer = new ResizeObserver(() => resize()); | ||
| 63 | + if (wrap) observer.observe(wrap); | ||
| 64 | + onCleanup(() => observer.disconnect()); | ||
| 65 | + }); | ||
| 66 | + | ||
| 67 | + // Rescale a loaded scene to the current pad size, preserving aspect ratio, so a | ||
| 68 | + // drawing made on one screen fits when reopened on a differently sized one | ||
| 69 | + // instead of overflowing or clipping. | ||
| 70 | + const fitStrokes = (scene: DrawScene): Stroke[] => { | ||
| 71 | + const rect = canvas?.getBoundingClientRect(); | ||
| 72 | + if (!rect?.width || !scene.w || !scene.h) return scene.strokes; | ||
| 73 | + const factor = Math.min(rect.width / scene.w, rect.height / scene.h); | ||
| 74 | + if (Math.abs(factor - 1) < 0.005) return scene.strokes; | ||
| 75 | + return scene.strokes.map((s) => ({ | ||
| 76 | + ...s, | ||
| 77 | + width: s.width * factor, | ||
| 78 | + points: s.points.map((p) => ({ x: p.x * factor, y: p.y * factor })), | ||
| 79 | + })); | ||
| 80 | + }; | ||
| 81 | + | ||
| 82 | + // Load (or reload) an edited scene whenever the caller supplies one — including | ||
| 83 | + // while the pad is already open. untrack keeps redraw's read of strokes() from | ||
| 84 | + // turning this into a self-triggering loop. | ||
| 85 | + createEffect(() => { | ||
| 86 | + const scene = props.initialScene; | ||
| 87 | + untrack(() => { | ||
| 88 | + setStrokes(scene ? fitStrokes(scene) : []); | ||
| 89 | + redraw(); | ||
| 90 | + }); | ||
| 91 | + }); | ||
| 92 | + | ||
| 93 | + const pointAt = (e: PointerEvent): Point => { | ||
| 94 | + const rect = canvas!.getBoundingClientRect(); | ||
| 95 | + return { x: e.clientX - rect.left, y: e.clientY - rect.top }; | ||
| 96 | + }; | ||
| 97 | + | ||
| 98 | + const drawTip = (stroke: Stroke) => { | ||
| 99 | + const c = context(); | ||
| 100 | + if (c) paintTip(c, stroke); | ||
| 101 | + }; | ||
| 102 | + | ||
| 103 | + const startStroke = (e: PointerEvent) => { | ||
| 104 | + if (props.pending) return; | ||
| 105 | + e.preventDefault(); | ||
| 106 | + canvas?.setPointerCapture(e.pointerId); | ||
| 107 | + current = { | ||
| 108 | + color: color(), | ||
| 109 | + width: erasing() ? width() * 2.5 : width(), | ||
| 110 | + erase: erasing(), | ||
| 111 | + points: [pointAt(e)], | ||
| 112 | + }; | ||
| 113 | + drawTip(current); | ||
| 114 | + }; | ||
| 115 | + | ||
| 116 | + const extendStroke = (e: PointerEvent) => { | ||
| 117 | + if (!current) return; | ||
| 118 | + current.points.push(pointAt(e)); | ||
| 119 | + drawTip(current); | ||
| 120 | + }; | ||
| 121 | + | ||
| 122 | + const endStroke = () => { | ||
| 123 | + const done = current; | ||
| 124 | + current = undefined; | ||
| 125 | + if (!done) return; | ||
| 126 | + setStrokes((all) => [...all, done]); | ||
| 127 | + redraw(); // swap the live polyline for its smoothed replay | ||
| 128 | + }; | ||
| 129 | + | ||
| 130 | + const undo = () => { | ||
| 131 | + setStrokes((all) => all.slice(0, -1)); | ||
| 132 | + redraw(); | ||
| 133 | + }; | ||
| 134 | + | ||
| 135 | + const clear = () => { | ||
| 136 | + setStrokes([]); | ||
| 137 | + redraw(); | ||
| 138 | + }; | ||
| 139 | + | ||
| 140 | + // Editing lets you clear a drawing and save the blank (persist the erase); a | ||
| 141 | + // brand-new untouched pad has nothing to save. | ||
| 142 | + const canSave = () => strokes().length > 0 || props.initialScene != null; | ||
| 143 | + | ||
| 144 | + const save = async () => { | ||
| 145 | + if (!canvas || !canSave()) return; | ||
| 146 | + // Points live in CSS px (see pointAt), so the scene box is the canvas's CSS size. | ||
| 147 | + const rect = canvas.getBoundingClientRect(); | ||
| 148 | + const scene: DrawScene = { v: 1, w: Math.round(rect.width), h: Math.round(rect.height), strokes: strokes() }; | ||
| 149 | + props.onSave(await sceneToPngFile(canvas, scene, props.fileName ?? "drawing.png")); | ||
| 150 | + }; | ||
| 151 | + | ||
| 152 | + const baseName = () => (props.fileName ?? "drawing").replace(/(\.hzdraw)?\.[a-z0-9]+$/i, ""); | ||
| 153 | + | ||
| 154 | + const download = async (mime: string, ext: string) => { | ||
| 155 | + if (!canvas || strokes().length === 0) return; | ||
| 156 | + const blob = await canvasToImageBlob(canvas, mime); | ||
| 157 | + if (!blob) return; | ||
| 158 | + const url = URL.createObjectURL(blob); | ||
| 159 | + const link = document.createElement("a"); | ||
| 160 | + link.href = url; | ||
| 161 | + link.download = `${baseName()}.${ext}`; | ||
| 162 | + link.click(); | ||
| 163 | + URL.revokeObjectURL(url); | ||
| 164 | + }; | ||
| 165 | + | ||
| 166 | + const toolClass = (active: boolean) => | ||
| 167 | + cn( | ||
| 168 | + "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", | ||
| 169 | + active | ||
| 170 | + ? "border-primary bg-primary text-primary-foreground shadow-sm" | ||
| 171 | + : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", | ||
| 172 | + ); | ||
| 173 | + | ||
| 174 | + return ( | ||
| 175 | + <div class={cn("space-y-3", props.class)}> | ||
| 176 | + <div class="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg border bg-card p-2 shadow-sm"> | ||
| 177 | + <div class="flex gap-1.5"> | ||
| 178 | + <button type="button" class={toolClass(!erasing())} aria-pressed={!erasing()} title={t("draw.pen")} onClick={() => setErasing(false)}> | ||
| 179 | + <IconEdit class="h-5 w-5" /> | ||
| 180 | + <span class="sr-only">{t("draw.pen")}</span> | ||
| 181 | + </button> | ||
| 182 | + <button type="button" class={toolClass(erasing())} aria-pressed={erasing()} title={t("draw.eraser")} onClick={() => setErasing(true)}> | ||
| 183 | + <IconEraser class="h-5 w-5" /> | ||
| 184 | + <span class="sr-only">{t("draw.eraser")}</span> | ||
| 185 | + </button> | ||
| 186 | + </div> | ||
| 187 | + | ||
| 188 | + <div class="flex gap-1.5" role="group" aria-label={t("draw.color")}> | ||
| 189 | + <For each={COLORS}> | ||
| 190 | + {(swatch) => ( | ||
| 191 | + <button | ||
| 192 | + type="button" | ||
| 193 | + aria-pressed={color() === swatch && !erasing()} | ||
| 194 | + title={t("draw.color")} | ||
| 195 | + class={cn( | ||
| 196 | + "h-11 w-11 rounded-lg border-2 transition-transform", | ||
| 197 | + color() === swatch && !erasing() ? "border-foreground scale-105" : "border-border/60 hover:scale-105", | ||
| 198 | + )} | ||
| 199 | + style={{ "background-color": swatch }} | ||
| 200 | + onClick={() => { | ||
| 201 | + setColor(swatch); | ||
| 202 | + setErasing(false); | ||
| 203 | + }} | ||
| 204 | + > | ||
| 205 | + <span class="sr-only">{swatch}</span> | ||
| 206 | + </button> | ||
| 207 | + )} | ||
| 208 | + </For> | ||
| 209 | + </div> | ||
| 210 | + | ||
| 211 | + <div class="flex gap-1.5" role="group" aria-label={t("draw.width")}> | ||
| 212 | + <For each={WIDTHS}> | ||
| 213 | + {(size) => ( | ||
| 214 | + <button type="button" aria-pressed={width() === size} title={t("draw.width")} class={toolClass(width() === size)} onClick={() => setWidth(size)}> | ||
| 215 | + <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} /> | ||
| 216 | + <span class="sr-only">{size}</span> | ||
| 217 | + </button> | ||
| 218 | + )} | ||
| 219 | + </For> | ||
| 220 | + </div> | ||
| 221 | + | ||
| 222 | + <div class="ml-auto flex gap-1.5"> | ||
| 223 | + <button type="button" class={toolClass(false)} disabled={strokes().length === 0} title={t("draw.undo")} onClick={undo}> | ||
| 224 | + <IconUndo class="h-5 w-5" /> | ||
| 225 | + <span class="sr-only">{t("draw.undo")}</span> | ||
| 226 | + </button> | ||
| 227 | + <button type="button" class={toolClass(false)} disabled={strokes().length === 0} title={t("draw.clear")} onClick={clear}> | ||
| 228 | + <IconTrash class="h-5 w-5" /> | ||
| 229 | + <span class="sr-only">{t("draw.clear")}</span> | ||
| 230 | + </button> | ||
| 231 | + </div> | ||
| 232 | + </div> | ||
| 233 | + | ||
| 234 | + <div ref={wrap} class="relative h-[22rem] overflow-hidden rounded-lg border bg-white shadow-inner"> | ||
| 235 | + <canvas | ||
| 236 | + ref={canvas} | ||
| 237 | + class="h-full w-full touch-none" | ||
| 238 | + onPointerDown={startStroke} | ||
| 239 | + onPointerMove={extendStroke} | ||
| 240 | + onPointerUp={endStroke} | ||
| 241 | + onPointerCancel={endStroke} | ||
| 242 | + /> | ||
| 243 | + <Show when={strokes().length === 0 && !current}> | ||
| 244 | + <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400">{t("draw.hint")}</p> | ||
| 245 | + </Show> | ||
| 246 | + </div> | ||
| 247 | + | ||
| 248 | + <div class="flex flex-wrap items-center gap-2"> | ||
| 249 | + <Button type="button" class="h-10 gap-2" disabled={props.pending || !canSave()} onClick={() => void save()}> | ||
| 250 | + <IconSave class="h-4 w-4" /> | ||
| 251 | + {t("draw.save")} | ||
| 252 | + </Button> | ||
| 253 | + <Button type="button" variant="outline" class="h-10 gap-2" disabled={strokes().length === 0} onClick={() => void download("image/png", "png")}> | ||
| 254 | + <IconDownload class="h-4 w-4" /> | ||
| 255 | + {t("draw.downloadPng")} | ||
| 256 | + </Button> | ||
| 257 | + <Button type="button" variant="outline" class="h-10 gap-2" disabled={strokes().length === 0} onClick={() => void download("image/jpeg", "jpg")}> | ||
| 258 | + <IconDownload class="h-4 w-4" /> | ||
| 259 | + {t("draw.downloadJpeg")} | ||
| 260 | + </Button> | ||
| 261 | + </div> | ||
| 262 | + </div> | ||
| 263 | + ); | ||
| 264 | +} | ||
src/components/ui/icons.tsxmodified+19 -0
| @@ -118,6 +118,25 @@ export function IconEdit(props: IconProps) { | |||
| 118 | ); | 118 | ); |
| 119 | } | 119 | } |
| 120 | 120 | ||
| 121 | +export function IconEraser(props: IconProps) { | ||
| 122 | + return ( | ||
| 123 | + <Svg {...props}> | ||
| 124 | + <path d="m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21" /> | ||
| 125 | + <path d="M22 21H7" /> | ||
| 126 | + <path d="m5 11 9 9" /> | ||
| 127 | + </Svg> | ||
| 128 | + ); | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +export function IconUndo(props: IconProps) { | ||
| 132 | + return ( | ||
| 133 | + <Svg {...props}> | ||
| 134 | + <path d="M9 14 4 9l5-5" /> | ||
| 135 | + <path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11" /> | ||
| 136 | + </Svg> | ||
| 137 | + ); | ||
| 138 | +} | ||
| 139 | + | ||
| 121 | export function IconPlus(props: IconProps) { | 140 | export function IconPlus(props: IconProps) { |
| 122 | return ( | 141 | return ( |
| 123 | <Svg {...props}> | 142 | <Svg {...props}> |
src/i18n/messages.tsmodified+54 -0
| @@ -226,6 +226,18 @@ export type MessageKey = | |||
| 226 | | "notes.files" | 226 | | "notes.files" |
| 227 | | "notes.filesHelp" | 227 | | "notes.filesHelp" |
| 228 | | "notes.addFile" | 228 | | "notes.addFile" |
| 229 | + | "notes.draw" | ||
| 230 | + | "notes.drawTitle" | ||
| 231 | + | "draw.pen" | ||
| 232 | + | "draw.eraser" | ||
| 233 | + | "draw.color" | ||
| 234 | + | "draw.width" | ||
| 235 | + | "draw.undo" | ||
| 236 | + | "draw.clear" | ||
| 237 | + | "draw.save" | ||
| 238 | + | "draw.hint" | ||
| 239 | + | "draw.downloadPng" | ||
| 240 | + | "draw.downloadJpeg" | ||
| 229 | | "notes.downloadFile" | 241 | | "notes.downloadFile" |
| 230 | | "notes.noFiles" | 242 | | "notes.noFiles" |
| 231 | | "notes.fileLimit" | 243 | | "notes.fileLimit" |
| @@ -357,6 +369,9 @@ export type MessageKey = | |||
| 357 | | "questions.kind.choice" | 369 | | "questions.kind.choice" |
| 358 | | "questions.kind.text" | 370 | | "questions.kind.text" |
| 359 | | "questions.image" | 371 | | "questions.image" |
| 372 | + | "questions.draw" | ||
| 373 | + | "questions.drawTitle" | ||
| 374 | + | "questions.editDrawing" | ||
| 360 | | "questions.choiceImage" | 375 | | "questions.choiceImage" |
| 361 | | "questions.subjectRequired" | 376 | | "questions.subjectRequired" |
| 362 | | "questions.textRequired" | 377 | | "questions.textRequired" |
| @@ -554,6 +569,9 @@ export type MessageKey = | |||
| 554 | | "exams.possible" | 569 | | "exams.possible" |
| 555 | | "exams.isCorrect" | 570 | | "exams.isCorrect" |
| 556 | | "exams.textAnswer" | 571 | | "exams.textAnswer" |
| 572 | + | "exams.drawAnswer" | ||
| 573 | + | "exams.editDrawing" | ||
| 574 | + | "exams.removeDrawing" | ||
| 557 | | "exams.nameless" | 575 | | "exams.nameless" |
| 558 | | "exams.emptyRoster" | 576 | | "exams.emptyRoster" |
| 559 | | "exams.selectStudent" | 577 | | "exams.selectStudent" |
| @@ -910,6 +928,18 @@ const en: Dict = { | |||
| 910 | "notes.files": "Attachments", | 928 | "notes.files": "Attachments", |
| 911 | "notes.filesHelp": "Up to 10 files. Max {size} each.", | 929 | "notes.filesHelp": "Up to 10 files. Max {size} each.", |
| 912 | "notes.addFile": "Add file", | 930 | "notes.addFile": "Add file", |
| 931 | + "notes.draw": "Draw", | ||
| 932 | + "notes.drawTitle": "Draw a picture", | ||
| 933 | + "draw.pen": "Pen", | ||
| 934 | + "draw.eraser": "Eraser", | ||
| 935 | + "draw.color": "Colour", | ||
| 936 | + "draw.width": "Line thickness", | ||
| 937 | + "draw.undo": "Undo", | ||
| 938 | + "draw.clear": "Clear all", | ||
| 939 | + "draw.save": "Save drawing", | ||
| 940 | + "draw.hint": "Draw here with your finger, pen, or mouse.", | ||
| 941 | + "draw.downloadPng": "Download PNG", | ||
| 942 | + "draw.downloadJpeg": "Download JPEG", | ||
| 913 | "notes.downloadFile": "Download", | 943 | "notes.downloadFile": "Download", |
| 914 | "notes.noFiles": "No files attached.", | 944 | "notes.noFiles": "No files attached.", |
| 915 | "notes.fileLimit": "This note already has 10 files.", | 945 | "notes.fileLimit": "This note already has 10 files.", |
| @@ -1048,6 +1078,9 @@ const en: Dict = { | |||
| 1048 | "questions.kind.choice": "Choice", | 1078 | "questions.kind.choice": "Choice", |
| 1049 | "questions.kind.text": "Text", | 1079 | "questions.kind.text": "Text", |
| 1050 | "questions.image": "Question image", | 1080 | "questions.image": "Question image", |
| 1081 | + "questions.draw": "Draw the image", | ||
| 1082 | + "questions.drawTitle": "Draw the question image", | ||
| 1083 | + "questions.editDrawing": "Edit drawing", | ||
| 1051 | "questions.choiceImage": "Choice image", | 1084 | "questions.choiceImage": "Choice image", |
| 1052 | "questions.subjectRequired": "Select a subject for this question", | 1085 | "questions.subjectRequired": "Select a subject for this question", |
| 1053 | "questions.textRequired": "Question text is required", | 1086 | "questions.textRequired": "Question text is required", |
| @@ -1256,6 +1289,9 @@ const en: Dict = { | |||
| 1256 | "exams.possible": "Possible", | 1289 | "exams.possible": "Possible", |
| 1257 | "exams.isCorrect": "Correct", | 1290 | "exams.isCorrect": "Correct", |
| 1258 | "exams.textAnswer": "Text answer", | 1291 | "exams.textAnswer": "Text answer", |
| 1292 | + "exams.drawAnswer": "Draw answer", | ||
| 1293 | + "exams.editDrawing": "Edit drawing", | ||
| 1294 | + "exams.removeDrawing": "Remove drawing", | ||
| 1259 | "exams.nameless": "Unnamed", | 1295 | "exams.nameless": "Unnamed", |
| 1260 | "exams.emptyRoster": "No enrolled students yet.", | 1296 | "exams.emptyRoster": "No enrolled students yet.", |
| 1261 | "exams.selectStudent": "Select a student from the roster", | 1297 | "exams.selectStudent": "Select a student from the roster", |
| @@ -1606,6 +1642,18 @@ const tr: Dict = { | |||
| 1606 | "notes.files": "Ekler", | 1642 | "notes.files": "Ekler", |
| 1607 | "notes.filesHelp": "En fazla 10 dosya. Dosya başına {size} sınırı.", | 1643 | "notes.filesHelp": "En fazla 10 dosya. Dosya başına {size} sınırı.", |
| 1608 | "notes.addFile": "Dosya ekle", | 1644 | "notes.addFile": "Dosya ekle", |
| 1645 | + "notes.draw": "Çiz", | ||
| 1646 | + "notes.drawTitle": "Resim çiz", | ||
| 1647 | + "draw.pen": "Kalem", | ||
| 1648 | + "draw.eraser": "Silgi", | ||
| 1649 | + "draw.color": "Renk", | ||
| 1650 | + "draw.width": "Çizgi kalınlığı", | ||
| 1651 | + "draw.undo": "Geri al", | ||
| 1652 | + "draw.clear": "Hepsini sil", | ||
| 1653 | + "draw.save": "Çizimi kaydet", | ||
| 1654 | + "draw.hint": "Parmağınla, kalemle ya da fareyle buraya çiz.", | ||
| 1655 | + "draw.downloadPng": "PNG indir", | ||
| 1656 | + "draw.downloadJpeg": "JPEG indir", | ||
| 1609 | "notes.downloadFile": "İndir", | 1657 | "notes.downloadFile": "İndir", |
| 1610 | "notes.noFiles": "Henüz dosya eklenmemiş.", | 1658 | "notes.noFiles": "Henüz dosya eklenmemiş.", |
| 1611 | "notes.fileLimit": "Bu notta zaten 10 dosya var.", | 1659 | "notes.fileLimit": "Bu notta zaten 10 dosya var.", |
| @@ -1744,6 +1792,9 @@ const tr: Dict = { | |||
| 1744 | "questions.kind.choice": "Seçmeli", | 1792 | "questions.kind.choice": "Seçmeli", |
| 1745 | "questions.kind.text": "Metin", | 1793 | "questions.kind.text": "Metin", |
| 1746 | "questions.image": "Soru görseli", | 1794 | "questions.image": "Soru görseli", |
| 1795 | + "questions.draw": "Görseli çiz", | ||
| 1796 | + "questions.drawTitle": "Soru görselini çiz", | ||
| 1797 | + "questions.editDrawing": "Çizimi düzenle", | ||
| 1747 | "questions.choiceImage": "Seçenek görseli", | 1798 | "questions.choiceImage": "Seçenek görseli", |
| 1748 | "questions.subjectRequired": "Bu soru için konu seç", | 1799 | "questions.subjectRequired": "Bu soru için konu seç", |
| 1749 | "questions.textRequired": "Soru metni gerekli", | 1800 | "questions.textRequired": "Soru metni gerekli", |
| @@ -1952,6 +2003,9 @@ const tr: Dict = { | |||
| 1952 | "exams.possible": "Mümkün", | 2003 | "exams.possible": "Mümkün", |
| 1953 | "exams.isCorrect": "Doğru", | 2004 | "exams.isCorrect": "Doğru", |
| 1954 | "exams.textAnswer": "Metin cevap", | 2005 | "exams.textAnswer": "Metin cevap", |
| 2006 | + "exams.drawAnswer": "Cevabı çiz", | ||
| 2007 | + "exams.editDrawing": "Çizimi düzenle", | ||
| 2008 | + "exams.removeDrawing": "Çizimi kaldır", | ||
| 1955 | "exams.nameless": "İsimsiz", | 2009 | "exams.nameless": "İsimsiz", |
| 1956 | "exams.emptyRoster": "Henüz kayıtlı öğrenci yok.", | 2010 | "exams.emptyRoster": "Henüz kayıtlı öğrenci yok.", |
| 1957 | "exams.selectStudent": "Listeden bir öğrenci seç", | 2011 | "exams.selectStudent": "Listeden bir öğrenci seç", |
src/lib/draw-stroke.test.tsadded+131 -0
| @@ -0,0 +1,131 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import { paintStroke, paintTip, parseScene, type DrawScene, type Stroke } from "./draw-stroke"; | ||
| 3 | + | ||
| 4 | +/** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */ | ||
| 5 | +function stubContext() { | ||
| 6 | + const calls: string[] = []; | ||
| 7 | + const props: Record<string, unknown> = {}; | ||
| 8 | + const record = | ||
| 9 | + (name: string) => | ||
| 10 | + (...args: unknown[]) => { | ||
| 11 | + calls.push(`${name}(${args.join(",")})`); | ||
| 12 | + }; | ||
| 13 | + const c = { | ||
| 14 | + calls, | ||
| 15 | + props, | ||
| 16 | + beginPath: record("beginPath"), | ||
| 17 | + moveTo: record("moveTo"), | ||
| 18 | + lineTo: record("lineTo"), | ||
| 19 | + quadraticCurveTo: record("quadraticCurveTo"), | ||
| 20 | + arc: record("arc"), | ||
| 21 | + fill: record("fill"), | ||
| 22 | + stroke: record("stroke"), | ||
| 23 | + }; | ||
| 24 | + // trap the style assignments so composite mode / width can be asserted too | ||
| 25 | + return new Proxy(c, { | ||
| 26 | + set(target, key, value) { | ||
| 27 | + props[String(key)] = value; | ||
| 28 | + return Reflect.set(target, key, value); | ||
| 29 | + }, | ||
| 30 | + }) as unknown as CanvasRenderingContext2D & { calls: string[]; props: Record<string, unknown> }; | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +const stroke = (points: Stroke["points"], over: Partial<Stroke> = {}): Stroke => ({ | ||
| 34 | + color: "#000", | ||
| 35 | + width: 4, | ||
| 36 | + erase: false, | ||
| 37 | + points, | ||
| 38 | + ...over, | ||
| 39 | +}); | ||
| 40 | + | ||
| 41 | +describe("paintStroke", () => { | ||
| 42 | + it("draws nothing for an empty stroke", () => { | ||
| 43 | + const c = stubContext(); | ||
| 44 | + paintStroke(c, stroke([])); | ||
| 45 | + expect(c.calls).toEqual([]); | ||
| 46 | + }); | ||
| 47 | + | ||
| 48 | + it("fills a dot for a tap with no drag", () => { | ||
| 49 | + const c = stubContext(); | ||
| 50 | + paintStroke(c, stroke([{ x: 10, y: 20 }])); | ||
| 51 | + // radius is half the line width, so a tap matches the pen it was drawn with | ||
| 52 | + expect(c.calls).toContain(`arc(10,20,2,0,${Math.PI * 2})`); | ||
| 53 | + expect(c.calls).toContain("fill()"); | ||
| 54 | + expect(c.calls).not.toContain("stroke()"); | ||
| 55 | + }); | ||
| 56 | + | ||
| 57 | + it("smooths interior points into quadratics and lands on the last point", () => { | ||
| 58 | + const c = stubContext(); | ||
| 59 | + paintStroke( | ||
| 60 | + c, | ||
| 61 | + stroke([ | ||
| 62 | + { x: 0, y: 0 }, | ||
| 63 | + { x: 10, y: 0 }, | ||
| 64 | + { x: 20, y: 10 }, | ||
| 65 | + { x: 30, y: 10 }, | ||
| 66 | + ]), | ||
| 67 | + ); | ||
| 68 | + expect(c.calls).toEqual([ | ||
| 69 | + "beginPath()", | ||
| 70 | + "moveTo(0,0)", | ||
| 71 | + "quadraticCurveTo(10,0,15,5)", | ||
| 72 | + "quadraticCurveTo(20,10,25,10)", | ||
| 73 | + "lineTo(30,10)", | ||
| 74 | + "stroke()", | ||
| 75 | + ]); | ||
| 76 | + }); | ||
| 77 | + | ||
| 78 | + it("cuts through the layer when erasing instead of painting over it", () => { | ||
| 79 | + const c = stubContext(); | ||
| 80 | + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }], { erase: true })); | ||
| 81 | + expect(c.props.globalCompositeOperation).toBe("destination-out"); | ||
| 82 | + }); | ||
| 83 | + | ||
| 84 | + it("paints over the layer when not erasing", () => { | ||
| 85 | + const c = stubContext(); | ||
| 86 | + paintStroke(c, stroke([{ x: 1, y: 1 }, { x: 2, y: 2 }])); | ||
| 87 | + expect(c.props.globalCompositeOperation).toBe("source-over"); | ||
| 88 | + }); | ||
| 89 | +}); | ||
| 90 | + | ||
| 91 | +describe("paintTip", () => { | ||
| 92 | + it("draws only the newest segment, not the whole stroke", () => { | ||
| 93 | + const c = stubContext(); | ||
| 94 | + paintTip( | ||
| 95 | + c, | ||
| 96 | + stroke([ | ||
| 97 | + { x: 0, y: 0 }, | ||
| 98 | + { x: 5, y: 5 }, | ||
| 99 | + { x: 9, y: 9 }, | ||
| 100 | + ]), | ||
| 101 | + ); | ||
| 102 | + expect(c.calls).toEqual(["beginPath()", "moveTo(5,5)", "lineTo(9,9)", "stroke()"]); | ||
| 103 | + }); | ||
| 104 | + | ||
| 105 | + it("falls back to a dot on the first point of a stroke", () => { | ||
| 106 | + const c = stubContext(); | ||
| 107 | + paintTip(c, stroke([{ x: 3, y: 4 }])); | ||
| 108 | + expect(c.calls).toContain("fill()"); | ||
| 109 | + }); | ||
| 110 | +}); | ||
| 111 | + | ||
| 112 | +describe("parseScene", () => { | ||
| 113 | + const scene: DrawScene = { v: 1, w: 100, h: 80, strokes: [stroke([{ x: 1, y: 2 }, { x: 3, y: 4 }])] }; | ||
| 114 | + | ||
| 115 | + it("parses a valid scene", () => { | ||
| 116 | + expect(parseScene(JSON.stringify(scene))).toEqual(scene); | ||
| 117 | + }); | ||
| 118 | + | ||
| 119 | + it("rejects a wrong version", () => { | ||
| 120 | + expect(parseScene(JSON.stringify({ ...scene, v: 2 }))).toBeNull(); | ||
| 121 | + }); | ||
| 122 | + | ||
| 123 | + it("rejects a malformed stroke shape", () => { | ||
| 124 | + expect(parseScene(JSON.stringify({ v: 1, w: 1, h: 1, strokes: [{ color: "#000" }] }))).toBeNull(); | ||
| 125 | + }); | ||
| 126 | + | ||
| 127 | + it("rejects garbage and null", () => { | ||
| 128 | + expect(parseScene("not json")).toBeNull(); | ||
| 129 | + expect(parseScene(null)).toBeNull(); | ||
| 130 | + }); | ||
| 131 | +}); | ||
src/lib/draw-stroke.tsadded+91 -0
| @@ -0,0 +1,91 @@ | |||
| 1 | +export type Point = { x: number; y: number }; | ||
| 2 | +export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; | ||
| 3 | +export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[] }; | ||
| 4 | + | ||
| 5 | +function isPoint(p: unknown): p is Point { | ||
| 6 | + return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number"; | ||
| 7 | +} | ||
| 8 | + | ||
| 9 | +function isStroke(s: unknown): s is Stroke { | ||
| 10 | + if (!s || typeof s !== "object") return false; | ||
| 11 | + const st = s as Stroke; | ||
| 12 | + return ( | ||
| 13 | + typeof st.color === "string" && | ||
| 14 | + typeof st.width === "number" && | ||
| 15 | + typeof st.erase === "boolean" && | ||
| 16 | + Array.isArray(st.points) && | ||
| 17 | + st.points.every(isPoint) | ||
| 18 | + ); | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/** | ||
| 22 | + * Parse the JSON embedded in a drawing PNG into a scene, or null on anything | ||
| 23 | + * malformed. The input is effectively untrusted (any uploaded `.hzdraw.png`), | ||
| 24 | + * so the whole shape is validated before it reaches the renderer. | ||
| 25 | + */ | ||
| 26 | +export function parseScene(text: string | null): DrawScene | null { | ||
| 27 | + if (!text) return null; | ||
| 28 | + let data: unknown; | ||
| 29 | + try { | ||
| 30 | + data = JSON.parse(text); | ||
| 31 | + } catch { | ||
| 32 | + return null; | ||
| 33 | + } | ||
| 34 | + if (!data || typeof data !== "object") return null; | ||
| 35 | + const scene = data as DrawScene; | ||
| 36 | + if (scene.v !== 1 || typeof scene.w !== "number" || typeof scene.h !== "number" || !Array.isArray(scene.strokes)) { | ||
| 37 | + return null; | ||
| 38 | + } | ||
| 39 | + if (!scene.strokes.every(isStroke)) return null; | ||
| 40 | + return scene; | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) { | ||
| 44 | + // The eraser cuts through the transparent drawing layer rather than painting | ||
| 45 | + // over it, so a saved drawing keeps whatever the caller flattens it onto. | ||
| 46 | + c.globalCompositeOperation = stroke.erase ? "destination-out" : "source-over"; | ||
| 47 | + c.strokeStyle = stroke.color; | ||
| 48 | + c.fillStyle = stroke.color; | ||
| 49 | + c.lineWidth = stroke.width; | ||
| 50 | + c.lineCap = "round"; | ||
| 51 | + c.lineJoin = "round"; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/** Replay a finished stroke. Midpoint quadratics so a fast drag reads as a curve, not a polygon. */ | ||
| 55 | +export function paintStroke(c: CanvasRenderingContext2D, stroke: Stroke) { | ||
| 56 | + const pts = stroke.points; | ||
| 57 | + if (pts.length === 0) return; | ||
| 58 | + applyBrush(c, stroke); | ||
| 59 | + if (pts.length === 1) { | ||
| 60 | + // a tap with no drag still leaves a dot | ||
| 61 | + c.beginPath(); | ||
| 62 | + c.arc(pts[0].x, pts[0].y, stroke.width / 2, 0, Math.PI * 2); | ||
| 63 | + c.fill(); | ||
| 64 | + return; | ||
| 65 | + } | ||
| 66 | + c.beginPath(); | ||
| 67 | + c.moveTo(pts[0].x, pts[0].y); | ||
| 68 | + for (let i = 1; i < pts.length - 1; i += 1) { | ||
| 69 | + c.quadraticCurveTo(pts[i].x, pts[i].y, (pts[i].x + pts[i + 1].x) / 2, (pts[i].y + pts[i + 1].y) / 2); | ||
| 70 | + } | ||
| 71 | + c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y); | ||
| 72 | + c.stroke(); | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +/** | ||
| 76 | + * Paint only the newest segment of a stroke still being drawn. Replaying the | ||
| 77 | + * whole drawing on every pointermove gets expensive past a few thousand points; | ||
| 78 | + * the caller replays once on pointerup to swap in the smoothed version. | ||
| 79 | + */ | ||
| 80 | +export function paintTip(c: CanvasRenderingContext2D, stroke: Stroke) { | ||
| 81 | + const pts = stroke.points; | ||
| 82 | + if (pts.length < 2) { | ||
| 83 | + paintStroke(c, stroke); | ||
| 84 | + return; | ||
| 85 | + } | ||
| 86 | + applyBrush(c, stroke); | ||
| 87 | + c.beginPath(); | ||
| 88 | + c.moveTo(pts[pts.length - 2].x, pts[pts.length - 2].y); | ||
| 89 | + c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y); | ||
| 90 | + c.stroke(); | ||
| 91 | +} | ||
src/lib/drawing-file.test.tsadded+33 -0
| @@ -0,0 +1,33 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import type { DrawScene } from "./draw-stroke"; | ||
| 3 | +import { pngBytesToScene } from "./drawing-file"; | ||
| 4 | +import { embedPngText } from "./png-meta"; | ||
| 5 | + | ||
| 6 | +const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; | ||
| 7 | + | ||
| 8 | +/** Chunk-walkable 1x1 PNG (signature + IHDR + IEND); enough carrier for embed/extract. */ | ||
| 9 | +function minimalPng(): Uint8Array { | ||
| 10 | + const ihdr = [0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]; | ||
| 11 | + return new Uint8Array([ | ||
| 12 | + ...SIGNATURE, | ||
| 13 | + 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, ...ihdr, 0, 0, 0, 0, | ||
| 14 | + 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0, 0, 0, 0, | ||
| 15 | + ]); | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +describe("pngBytesToScene", () => { | ||
| 19 | + it("round-trips a scene carried in the PNG's tEXt chunk", () => { | ||
| 20 | + const scene: DrawScene = { | ||
| 21 | + v: 1, | ||
| 22 | + w: 120, | ||
| 23 | + h: 90, | ||
| 24 | + strokes: [{ color: "#1f2937", width: 6, erase: false, points: [{ x: 1, y: 2 }, { x: 3, y: 4 }] }], | ||
| 25 | + }; | ||
| 26 | + const png = embedPngText(minimalPng(), "hezarfen-drawing", JSON.stringify(scene)); | ||
| 27 | + expect(pngBytesToScene(png)).toEqual(scene); | ||
| 28 | + }); | ||
| 29 | + | ||
| 30 | + it("returns null for a plain PNG with no embedded scene", () => { | ||
| 31 | + expect(pngBytesToScene(minimalPng())).toBeNull(); | ||
| 32 | + }); | ||
| 33 | +}); | ||
src/lib/drawing-file.tsadded+37 -0
| @@ -0,0 +1,37 @@ | |||
| 1 | +import { parseScene, type DrawScene } from "./draw-stroke"; | ||
| 2 | +import { embedPngText, extractPngText } from "./png-meta"; | ||
| 3 | + | ||
| 4 | +/** tEXt keyword under which a drawing's editable stroke JSON is stored inside its PNG. */ | ||
| 5 | +const DRAWING_KEYWORD = "hezarfen-drawing"; | ||
| 6 | + | ||
| 7 | +/** Read the editable scene back out of a drawing PNG's bytes, or null for a plain image. */ | ||
| 8 | +export function pngBytesToScene(bytes: Uint8Array): DrawScene | null { | ||
| 9 | + return parseScene(extractPngText(bytes, DRAWING_KEYWORD)); | ||
| 10 | +} | ||
| 11 | + | ||
| 12 | +/** | ||
| 13 | + * Flatten a transparent pad canvas onto white and encode it. The pad layer is | ||
| 14 | + * transparent so the eraser can cut through it; without the white fill dark | ||
| 15 | + * strokes would vanish on dark backgrounds once exported. DOM glue — needs a | ||
| 16 | + * document. | ||
| 17 | + */ | ||
| 18 | +export function canvasToImageBlob(source: HTMLCanvasElement, mime: string): Promise<Blob | null> { | ||
| 19 | + const out = document.createElement("canvas"); | ||
| 20 | + out.width = source.width; | ||
| 21 | + out.height = source.height; | ||
| 22 | + const oc = out.getContext("2d"); | ||
| 23 | + if (!oc) return Promise.resolve(null); | ||
| 24 | + oc.fillStyle = "#ffffff"; | ||
| 25 | + oc.fillRect(0, 0, out.width, out.height); | ||
| 26 | + oc.drawImage(source, 0, 0); | ||
| 27 | + return new Promise((resolve) => out.toBlob(resolve, mime)); | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +/** Encode the pad as a PNG File that both displays as an image and carries its editable scene. */ | ||
| 31 | +export async function sceneToPngFile(source: HTMLCanvasElement, scene: DrawScene, name: string): Promise<File> { | ||
| 32 | + const blob = await canvasToImageBlob(source, "image/png"); | ||
| 33 | + if (!blob) throw new Error("canvas PNG export failed"); | ||
| 34 | + const bytes = new Uint8Array(await blob.arrayBuffer()); | ||
| 35 | + const withScene = embedPngText(bytes, DRAWING_KEYWORD, JSON.stringify(scene)); | ||
| 36 | + return new File([withScene], name, { type: "image/png" }); | ||
| 37 | +} | ||
src/lib/png-meta.test.tsadded+63 -0
| @@ -0,0 +1,63 @@ | |||
| 1 | +import { describe, expect, it } from "vitest"; | ||
| 2 | +import { embedPngText, extractPngText } from "./png-meta"; | ||
| 3 | + | ||
| 4 | +const SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; | ||
| 5 | + | ||
| 6 | +/** Structurally valid (chunk-walkable) 1x1 PNG: signature + IHDR + IEND. CRCs are zeroed — embed/extract never validate them. */ | ||
| 7 | +function minimalPng(): Uint8Array { | ||
| 8 | + const ihdrData = [0, 0, 0, 1, 0, 0, 0, 1, 8, 6, 0, 0, 0]; // 1x1, 8-bit, RGBA | ||
| 9 | + return new Uint8Array([ | ||
| 10 | + ...SIGNATURE, | ||
| 11 | + 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, ...ihdrData, 0, 0, 0, 0, // IHDR | ||
| 12 | + 0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0, 0, 0, 0, // IEND | ||
| 13 | + ]); | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/** Reference CRC-32, pinned below to the spec's known IEND constant so it can vouch for embed's CRC. */ | ||
| 17 | +function refCrc32(bytes: Uint8Array): number { | ||
| 18 | + let crc = 0xffffffff; | ||
| 19 | + for (let i = 0; i < bytes.length; i += 1) { | ||
| 20 | + crc ^= bytes[i]; | ||
| 21 | + for (let bit = 0; bit < 8; bit += 1) crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); | ||
| 22 | + } | ||
| 23 | + return (crc ^ 0xffffffff) >>> 0; | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +const ascii = (s: string) => new Uint8Array([...s].map((c) => c.charCodeAt(0))); | ||
| 27 | + | ||
| 28 | +describe("png-meta", () => { | ||
| 29 | + it("round-trips embed -> extract", () => { | ||
| 30 | + const png = embedPngText(minimalPng(), "hezarfen-drawing", '{"v":1}'); | ||
| 31 | + expect(extractPngText(png, "hezarfen-drawing")).toBe('{"v":1}'); | ||
| 32 | + }); | ||
| 33 | + | ||
| 34 | + it("returns null for a wrong keyword", () => { | ||
| 35 | + const png = embedPngText(minimalPng(), "hezarfen-drawing", "payload"); | ||
| 36 | + expect(extractPngText(png, "other")).toBeNull(); | ||
| 37 | + }); | ||
| 38 | + | ||
| 39 | + it("returns null when no tEXt chunk is present", () => { | ||
| 40 | + expect(extractPngText(minimalPng(), "hezarfen-drawing")).toBeNull(); | ||
| 41 | + }); | ||
| 42 | + | ||
| 43 | + it("inserts the tEXt chunk right after IHDR", () => { | ||
| 44 | + const png = embedPngText(minimalPng(), "k", "v"); | ||
| 45 | + // signature(8) + IHDR chunk(4+4+13+4 = 25) => next chunk type starts at 33+4. | ||
| 46 | + const type = String.fromCharCode(png[37], png[38], png[39], png[40]); | ||
| 47 | + expect(type).toBe("tEXt"); | ||
| 48 | + }); | ||
| 49 | + | ||
| 50 | + it("writes a spec-correct CRC over chunk type + data", () => { | ||
| 51 | + // Anchor the reference implementation to the spec's fixed IEND CRC. | ||
| 52 | + expect(refCrc32(ascii("IEND"))).toBe(0xae426082); | ||
| 53 | + | ||
| 54 | + const png = embedPngText(minimalPng(), "kw", "hi"); | ||
| 55 | + // tEXt data = "kw" + NUL + "hi" (5 bytes); length field sits at offset 33. | ||
| 56 | + const dataLen = ((png[33] << 24) | (png[34] << 16) | (png[35] << 8) | png[36]) >>> 0; | ||
| 57 | + expect(dataLen).toBe(5); | ||
| 58 | + const typeAndData = png.subarray(37, 37 + 4 + dataLen); // "tEXt" + data | ||
| 59 | + const crcAt = 37 + 4 + dataLen; | ||
| 60 | + const embedded = ((png[crcAt] << 24) | (png[crcAt + 1] << 16) | (png[crcAt + 2] << 8) | png[crcAt + 3]) >>> 0; | ||
| 61 | + expect(embedded).toBe(refCrc32(typeAndData)); | ||
| 62 | + }); | ||
| 63 | +}); | ||
src/lib/png-meta.tsadded+88 -0
| @@ -0,0 +1,88 @@ | |||
| 1 | +/** | ||
| 2 | + * PNG `tEXt`-chunk metadata: embed/read a keyword→text pair inside a valid PNG. | ||
| 3 | + * Pure `Uint8Array` in/out, no DOM — this is the ".excalidraw.png" trick that lets | ||
| 4 | + * the editable stroke JSON ride inside the same bytes that display as a normal image. | ||
| 5 | + */ | ||
| 6 | + | ||
| 7 | +const SIGNATURE_LENGTH = 8; | ||
| 8 | +const TEXT_TYPE = new Uint8Array([0x74, 0x45, 0x58, 0x74]); // "tEXt" | ||
| 9 | + | ||
| 10 | +/** Standard PNG/zlib CRC-32 (polynomial 0xEDB88320), computed on the fly. */ | ||
| 11 | +function crc32(bytes: Uint8Array): number { | ||
| 12 | + let crc = 0xffffffff; | ||
| 13 | + for (let i = 0; i < bytes.length; i += 1) { | ||
| 14 | + crc ^= bytes[i]; | ||
| 15 | + for (let bit = 0; bit < 8; bit += 1) { | ||
| 16 | + crc = (crc >>> 1) ^ (0xedb88320 & -(crc & 1)); | ||
| 17 | + } | ||
| 18 | + } | ||
| 19 | + return (crc ^ 0xffffffff) >>> 0; | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +function readUint32(bytes: Uint8Array, offset: number): number { | ||
| 23 | + return ((bytes[offset] << 24) | (bytes[offset + 1] << 16) | (bytes[offset + 2] << 8) | bytes[offset + 3]) >>> 0; | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +function writeUint32(bytes: Uint8Array, offset: number, value: number): void { | ||
| 27 | + bytes[offset] = (value >>> 24) & 0xff; | ||
| 28 | + bytes[offset + 1] = (value >>> 16) & 0xff; | ||
| 29 | + bytes[offset + 2] = (value >>> 8) & 0xff; | ||
| 30 | + bytes[offset + 3] = value & 0xff; | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +/** Byte offset just past the IHDR chunk — the spec-legal spot to insert new chunks. */ | ||
| 34 | +function afterIhdr(png: Uint8Array): number { | ||
| 35 | + // signature(8) + length(4) + type(4) + IHDR data(length) + crc(4) | ||
| 36 | + return SIGNATURE_LENGTH + 4 + 4 + readUint32(png, SIGNATURE_LENGTH) + 4; | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/** Return a new PNG with a `tEXt` chunk carrying `keyword`→`text` inserted after IHDR. */ | ||
| 40 | +export function embedPngText(png: Uint8Array, keyword: string, text: string): Uint8Array<ArrayBuffer> { | ||
| 41 | + const enc = new TextEncoder(); | ||
| 42 | + const keyBytes = enc.encode(keyword); | ||
| 43 | + const textBytes = enc.encode(text); | ||
| 44 | + | ||
| 45 | + const data = new Uint8Array(keyBytes.length + 1 + textBytes.length); | ||
| 46 | + data.set(keyBytes, 0); | ||
| 47 | + data[keyBytes.length] = 0; // null separator between keyword and text | ||
| 48 | + data.set(textBytes, keyBytes.length + 1); | ||
| 49 | + | ||
| 50 | + // CRC covers the chunk type followed by its data. | ||
| 51 | + const typeAndData = new Uint8Array(TEXT_TYPE.length + data.length); | ||
| 52 | + typeAndData.set(TEXT_TYPE, 0); | ||
| 53 | + typeAndData.set(data, TEXT_TYPE.length); | ||
| 54 | + | ||
| 55 | + const chunk = new Uint8Array(4 + 4 + data.length + 4); | ||
| 56 | + writeUint32(chunk, 0, data.length); | ||
| 57 | + chunk.set(TEXT_TYPE, 4); | ||
| 58 | + chunk.set(data, 8); | ||
| 59 | + writeUint32(chunk, 8 + data.length, crc32(typeAndData)); | ||
| 60 | + | ||
| 61 | + const at = afterIhdr(png); | ||
| 62 | + const out = new Uint8Array(png.length + chunk.length); | ||
| 63 | + out.set(png.subarray(0, at), 0); | ||
| 64 | + out.set(chunk, at); | ||
| 65 | + out.set(png.subarray(at), at + chunk.length); | ||
| 66 | + return out; | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/** Read the text of the first `tEXt` chunk with `keyword`, or null if absent. */ | ||
| 70 | +export function extractPngText(png: Uint8Array, keyword: string): string | null { | ||
| 71 | + const dec = new TextDecoder(); | ||
| 72 | + let offset = SIGNATURE_LENGTH; | ||
| 73 | + while (offset + 8 <= png.length) { | ||
| 74 | + const length = readUint32(png, offset); | ||
| 75 | + const type = String.fromCharCode(png[offset + 4], png[offset + 5], png[offset + 6], png[offset + 7]); | ||
| 76 | + const dataStart = offset + 8; | ||
| 77 | + if (type === "tEXt") { | ||
| 78 | + const data = png.subarray(dataStart, dataStart + length); | ||
| 79 | + const nul = data.indexOf(0); | ||
| 80 | + if (nul !== -1 && dec.decode(data.subarray(0, nul)) === keyword) { | ||
| 81 | + return dec.decode(data.subarray(nul + 1)); | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + if (type === "IEND") break; | ||
| 85 | + offset = dataStart + length + 4; // skip data + crc | ||
| 86 | + } | ||
| 87 | + return null; | ||
| 88 | +} | ||