forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

drawing-playback.tsx114 lines, 4.6 KiBHistoryRawDownload
1import { createSignal, onCleanup, onMount } from "solid-js";
2import { Button } from "@/components/ui/button";
3import { cn } from "@/lib/cn";
4import { PAPER_CELL, canvasPx, paintPaper, paintStroke, sliceStrokes, type DrawScene } from "@/lib/draw-stroke";
5import { useT } from "@/stores/preferences-context";
6
7// ponytail: synthetic order-only pace — the drawing carries no per-point timing, so
8// every answer replays at this constant point rate. Bump if playback feels too fast/slow.
9const POINTS_PER_SECOND = 220;
10
11/**
12 * Replays a recovered drawing scene stroke-by-stroke in drawn order. Mirrors the
13 * export pipeline (drawing-file `renderBounds`/`canvasToImageBlob`) so a fully
14 * revealed frame is pixel-identical to the static answer <img>: strokes go on a
15 * transparent layer (erasers cut only ink), then that layer is composited over
16 * white + paper ruling. No timestamps are read — order + a synthetic pace only.
17 */
18export function DrawingPlayback(props: { scene: DrawScene; class?: string; canvasClass?: string }) {
19 const t = useT();
20 let canvas: HTMLCanvasElement | undefined;
21 let layer: HTMLCanvasElement | undefined; // offscreen transparent stroke layer (the export's `source`)
22 let raf = 0;
23 let startedAt = 0; // performance.now() when the current run began
24 let baseCount = 0; // points already revealed when the run began (so pause/resume continues)
25 let revealed = 0;
26 // The scene's own export DPR when it has one (older scenes fall back to this display's),
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.
29 let scale = 1;
30
31 const total = () => props.scene.strokes.reduce((n, s) => n + s.points.length, 0);
32 const [playing, setPlaying] = createSignal(true);
33
34 const paint = (count: number) => {
35 const s = props.scene;
36 const lc = layer?.getContext("2d");
37 const mc = canvas?.getContext("2d");
38 if (!layer || !canvas || !lc || !mc) return;
39 // 1. stroke layer: clear + replay the revealed prefix in world coords. Strokes are
40 // already baked into the scene box, so a plain DPR scale places them like the export.
41 lc.setTransform(scale, 0, 0, scale, 0, 0);
42 lc.clearRect(0, 0, s.w, s.h);
43 const { full, partial } = sliceStrokes(s.strokes, count);
44 for (const st of full) paintStroke(lc, st);
45 if (partial) paintStroke(lc, partial);
46 // 2. main canvas: white → paper → composite the ink (matches canvasToImageBlob).
47 mc.setTransform(1, 0, 0, 1, 0, 0);
48 mc.fillStyle = "#ffffff";
49 mc.fillRect(0, 0, canvas.width, canvas.height);
50 paintPaper(mc, s.bg ?? "none", canvas.width, canvas.height, PAPER_CELL * scale);
51 mc.drawImage(layer, 0, 0);
52 };
53
54 const loop = () => {
55 const elapsed = (performance.now() - startedAt) / 1000;
56 revealed = Math.min(total(), baseCount + Math.floor(elapsed * POINTS_PER_SECOND));
57 paint(revealed);
58 if (revealed >= total()) {
59 setPlaying(false); // reached the end: freeze on the complete drawing
60 return;
61 }
62 raf = requestAnimationFrame(loop);
63 };
64
65 const play = () => {
66 if (revealed >= total()) revealed = 0; // finished → replay from the start
67 baseCount = revealed;
68 startedAt = performance.now();
69 setPlaying(true);
70 cancelAnimationFrame(raf);
71 raf = requestAnimationFrame(loop);
72 };
73
74 const pause = () => {
75 cancelAnimationFrame(raf);
76 setPlaying(false);
77 };
78
79 const restart = () => {
80 revealed = 0;
81 play();
82 };
83
84 onMount(() => {
85 scale = props.scene.dpr ?? (window.devicePixelRatio || 1);
86 const w = canvasPx(props.scene.w, scale);
87 const h = canvasPx(props.scene.h, scale);
88 if (canvas) {
89 canvas.width = w;
90 canvas.height = h;
91 }
92 layer = document.createElement("canvas");
93 layer.width = w;
94 layer.height = h;
95 play(); // auto-start from blank — the teacher clicked "play" to get here
96 });
97
98 onCleanup(() => cancelAnimationFrame(raf));
99
100 return (
101 <div class={cn("space-y-2", props.class)}>
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"} />
104 <div class="flex flex-wrap items-center gap-2">
105 <Button type="button" variant="outline" size="sm" onClick={() => (playing() ? pause() : play())}>
106 {playing() ? t("exams.pause") : t("exams.play")}
107 </Button>
108 <Button type="button" variant="outline" size="sm" onClick={restart}>
109 {t("exams.restart")}
110 </Button>
111 </div>
112 </div>
113 );
114}