forge
Explore
Log in

Don't you dare go Hollow

🎨 infinite canvas, notebook paper, and floating draw controls

Browse files at this commit

0ae3da97cbd3c0eb4b6740625c8de1de6470e820Ahmet Kaan GümüşParent: 3758bf0
  • feat
    • 🎨 infinite canvas, notebook paper, and floating draw controls
Show full message
feat: 🎨 infinite canvas, notebook paper, and floating draw controls
- pan an unbounded pad (hand tool, middle-mouse drag, right-click
  erases) with world-coord strokes; export the drawn bounding box
  instead of the viewport so saved PNGs follow the content
- view-only zoom (buttons + wheel, 0.25×–4×); exports stay at 1×
- notebook backgrounds plain / ruled / squared grid, baked into the
  PNG under a transparent stroke layer so the eraser can't cut the
  lines; the choice rides in the embedded scene JSON (no backend change)
- strokesBounds ignores eraser strokes so a far erase can't pad the
  export box; paintPaper draws the ruling (both unit-tested)
- floating glass control islands: tools+size top-left, colours
  top-middle, paper top-right, undo/clear + zoom in the corners
- pen/eraser size and paper style open as hover/tap/keyboard menus
  driven by an openMenu signal (closes on select, outside, Escape, leave)
- transient tool highlight while middle/right button held; EN/TR i18n
src/components/ui/draw-canvas.tsxmodified+439 -69
@@ -1,13 +1,22 @@
1-import { For, Show, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";1+import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js";
2 import { Button } from "@/components/ui/button";2 import { Button } from "@/components/ui/button";
3-import { IconDownload, IconEdit, IconEraser, IconSave, IconTrash, IconUndo } 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 { paintStroke, paintTip, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke";5+import { PAPER_CELL, PAPER_LINE, 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
9 const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"];9 const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"];
10 const WIDTHS = [2, 6, 14];10 const WIDTHS = [2, 6, 14];
11+const ZOOM_MIN = 0.25;
12+const ZOOM_MAX = 4;
13+const ZOOM_STEP = 1.25;
14+// Whitespace kept around the drawn region when exporting the bounding box.
15+const EXPORT_MARGIN = 8;
16+// Floating glass overlays that live inside the canvas, matching the bottom-right
17+// zoom control. Position/size utilities are appended per overlay via cn().
18+const OVERLAY_CARD = "absolute z-10 flex gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-sm backdrop-blur-sm";
19+const OVERLAY_BTN = "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground";
11 20
12 /**21 /**
13 * Freehand drawing pad. `props.onSave` receives a PNG `File` that both displays22 * Freehand drawing pad. `props.onSave` receives a PNG `File` that both displays
@@ -27,21 +36,54 @@ export function DrawCanvas(props: {
27 let canvas: HTMLCanvasElement | undefined;36 let canvas: HTMLCanvasElement | undefined;
28 let wrap: HTMLDivElement | undefined;37 let wrap: HTMLDivElement | undefined;
29 let current: Stroke | undefined;38 let current: Stroke | undefined;
39+ // Live pan drag: pointer origin + pan value at grab, so the pad follows the finger.
40+ let panStart: { x: number; y: number; px: number; py: number } | undefined;
30 41
31 const [strokes, setStrokes] = createSignal<Stroke[]>([]);42 const [strokes, setStrokes] = createSignal<Stroke[]>([]);
32 const [color, setColor] = createSignal(COLORS[0]);43 const [color, setColor] = createSignal(COLORS[0]);
33 const [width, setWidth] = createSignal(WIDTHS[1]);44 const [width, setWidth] = createSignal(WIDTHS[1]);
34 const [erasing, setErasing] = createSignal(false);45 const [erasing, setErasing] = createSignal(false);
46+ const [hand, setHand] = createSignal(false);
47+ // Transient tool while a non-left button is held (middle = pan, right = erase),
48+ // so the toolbar highlights it as if clicked and reverts on release.
49+ const [override, setOverride] = createSignal<null | "pan" | "erase">(null);
50+ // The pad is unbounded — strokes live in world coords; pan is the world→screen
51+ // offset in CSS px so you can move around a drawing larger than the viewport.
52+ const [pan, setPan] = createSignal({ x: 0, y: 0 });
53+ // View-only magnification: screenCSS = world * zoom + pan. Strokes stay in world
54+ // px, so stroke widths scale with the transform — never multiply them by hand.
55+ const [zoom, setZoom] = createSignal(1);
56+ // Notebook paper, drawn as CSS on the wrapper (never in redraw(), or the eraser
57+ // would cut it). New pads default to squared grid — the look the pad is for.
58+ const [bg, setBg] = createSignal<BgKind>("grid");
59+ // Which floating picker is open (pen/eraser line-thickness, or paper style).
60+ // Driven by JS, not CSS :focus-within — a mouse click keeps focus on the trigger
61+ // and the canvas isn't focusable to blur it, so focus-within stayed stuck open.
62+ const [openMenu, setOpenMenu] = createSignal<null | "pen" | "eraser" | "paper">(null);
35 63
36 const ratio = () => window.devicePixelRatio || 1;64 const ratio = () => window.devicePixelRatio || 1;
37 const context = () => canvas?.getContext("2d") ?? null;65 const context = () => canvas?.getContext("2d") ?? null;
38 66
67+ // Transient override wins over the persistent tool so the toolbar reflects a held button.
68+ const activeTool = (): "pen" | "erase" | "pan" => {
69+ const o = override();
70+ if (o) return o;
71+ if (hand()) return "pan";
72+ if (erasing()) return "erase";
73+ return "pen";
74+ };
75+
39 const redraw = () => {76 const redraw = () => {
40 const c = context();77 const c = context();
41 if (!c || !canvas) return;78 if (!c || !canvas) return;
42 const scale = ratio();79 const scale = ratio();
80+ // Clear the whole backing store in device pixels, then shift into world space
81+ // by the pan offset so off-origin strokes render where the pan puts them.
43 c.setTransform(scale, 0, 0, scale, 0, 0);82 c.setTransform(scale, 0, 0, scale, 0, 0);
44 c.clearRect(0, 0, canvas.width / scale, canvas.height / scale);83 c.clearRect(0, 0, canvas.width / scale, canvas.height / scale);
84+ const p = pan();
85+ const z = zoom();
86+ c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale);
45 for (const stroke of strokes()) paintStroke(c, stroke);87 for (const stroke of strokes()) paintStroke(c, stroke);
46 if (current) paintStroke(c, current);88 if (current) paintStroke(c, current);
47 };89 };
@@ -61,40 +103,70 @@ export function DrawCanvas(props: {
61 resize();103 resize();
62 const observer = new ResizeObserver(() => resize());104 const observer = new ResizeObserver(() => resize());
63 if (wrap) observer.observe(wrap);105 if (wrap) observer.observe(wrap);
64- onCleanup(() => observer.disconnect());106+ // Close any open flyout on a pointerdown outside every picker group, or Escape.
107+ // The canvas isn't focusable, so nothing would otherwise dismiss it.
108+ const onDocDown = (e: PointerEvent) => {
109+ if (!(e.target as HTMLElement | null)?.closest("[data-draw-menu]")) setOpenMenu(null);
110+ };
111+ const onKey = (e: KeyboardEvent) => {
112+ if (e.key === "Escape") setOpenMenu(null);
113+ };
114+ document.addEventListener("pointerdown", onDocDown);
115+ document.addEventListener("keydown", onKey);
116+ onCleanup(() => {
117+ observer.disconnect();
118+ document.removeEventListener("pointerdown", onDocDown);
119+ document.removeEventListener("keydown", onKey);
120+ });
65 });121 });
66 122
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 — including123 // 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() from124+ // while the pad is already open. No rescale: the pad is unbounded, so rather than
84- // turning this into a self-triggering loop.125+ // shrinking a big drawing to fit we keep it 1:1 and pan its content into the
126+ // corner (you move around it from there). untrack keeps redraw's read of
127+ // strokes() from turning this into a self-triggering loop.
85 createEffect(() => {128 createEffect(() => {
86 const scene = props.initialScene;129 const scene = props.initialScene;
87 untrack(() => {130 untrack(() => {
88- setStrokes(scene ? fitStrokes(scene) : []);131+ const next = scene ? scene.strokes : [];
132+ setStrokes(next);
133+ setBg(scene?.bg ?? "none"); // old drawings lack bg → plain, preserving their original look
134+ setZoom(1); // a reopened drawing starts at 100%
135+ const b = strokesBounds(next);
136+ setPan(b ? { x: EXPORT_MARGIN - b.x, y: EXPORT_MARGIN - b.y } : { x: 0, y: 0 });
89 redraw();137 redraw();
90 });138 });
91 });139 });
92 140
93 const pointAt = (e: PointerEvent): Point => {141 const pointAt = (e: PointerEvent): Point => {
94 const rect = canvas!.getBoundingClientRect();142 const rect = canvas!.getBoundingClientRect();
95- return { x: e.clientX - rect.left, y: e.clientY - rect.top };143+ const p = pan();
144+ const z = zoom();
145+ return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z };
96 };146 };
97 147
148+ // Zoom around the pad center: keep the world point under the center fixed so
149+ // content doesn't fly off. Clamped to [ZOOM_MIN, ZOOM_MAX].
150+ // ponytail: no pinch-zoom; buttons + wheel cover it, add 2-pointer tracking if touch users ask
151+ const zoomBy = (factor: number) => {
152+ if (!canvas) return;
153+ const rect = canvas.getBoundingClientRect();
154+ const cx = rect.width / 2;
155+ const cy = rect.height / 2;
156+ const p = pan();
157+ const z0 = zoom();
158+ const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor));
159+ if (z1 === z0) return;
160+ const wx = (cx - p.x) / z0;
161+ const wy = (cy - p.y) / z0;
162+ setZoom(z1);
163+ setPan({ x: cx - wx * z1, y: cy - wy * z1 });
164+ redraw();
165+ };
166+
167+ // Snap back to 100% while keeping the centered content centered (no-op at 1).
168+ const resetZoom = () => zoomBy(1 / zoom());
169+
98 const drawTip = (stroke: Stroke) => {170 const drawTip = (stroke: Stroke) => {
99 const c = context();171 const c = context();
100 if (c) paintTip(c, stroke);172 if (c) paintTip(c, stroke);
@@ -104,22 +176,44 @@ export function DrawCanvas(props: {
104 if (props.pending) return;176 if (props.pending) return;
105 e.preventDefault();177 e.preventDefault();
106 canvas?.setPointerCapture(e.pointerId);178 canvas?.setPointerCapture(e.pointerId);
179+ // Middle button (1) always pans; the hand tool pans on any button EXCEPT right,
180+ // because right button always erases (see below). button is the real value only
181+ // on pointerdown; -1 during move, which is why panStart/current carry the state.
182+ if (e.button === 1 || (hand() && e.button !== 2)) {
183+ if (e.button === 1) setOverride("pan"); // transient middle-button pan
184+ const p = pan();
185+ panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y };
186+ return;
187+ }
188+ // Right button (2) forces an erase stroke regardless of the selected tool.
189+ const eraseNow = erasing() || e.button === 2;
190+ if (e.button === 2) setOverride("erase"); // transient right-button erase
107 current = {191 current = {
108 color: color(),192 color: color(),
109- width: erasing() ? width() * 2.5 : width(),193+ width: eraseNow ? width() * 2.5 : width(),
110- erase: erasing(),194+ erase: eraseNow,
111 points: [pointAt(e)],195 points: [pointAt(e)],
112 };196 };
113 drawTip(current);197 drawTip(current);
114 };198 };
115 199
116 const extendStroke = (e: PointerEvent) => {200 const extendStroke = (e: PointerEvent) => {
201+ if (panStart) {
202+ setPan({ x: panStart.px + (e.clientX - panStart.x), y: panStart.py + (e.clientY - panStart.y) });
203+ redraw();
204+ return;
205+ }
117 if (!current) return;206 if (!current) return;
118 current.points.push(pointAt(e));207 current.points.push(pointAt(e));
119 drawTip(current);208 drawTip(current);
120 };209 };
121 210
122 const endStroke = () => {211 const endStroke = () => {
212+ setOverride(null);
213+ if (panStart) {
214+ panStart = undefined;
215+ return;
216+ }
123 const done = current;217 const done = current;
124 current = undefined;218 current = undefined;
125 if (!done) return;219 if (!done) return;
@@ -141,19 +235,52 @@ export function DrawCanvas(props: {
141 // brand-new untouched pad has nothing to save.235 // brand-new untouched pad has nothing to save.
142 const canSave = () => strokes().length > 0 || props.initialScene != null;236 const canSave = () => strokes().length > 0 || props.initialScene != null;
143 237
238+ // Render only the drawn region (not the viewport) onto an offscreen DPR-scaled
239+ // canvas, and produce the matching scene with strokes shifted into that box.
240+ // This is what makes the pad "infinite": export follows the content wherever it
241+ // was drawn or panned to, instead of capturing what happens to be on screen.
242+ const renderBounds = (): { canvas: HTMLCanvasElement; scene: DrawScene } | null => {
243+ const list = strokes();
244+ const b = strokesBounds(list);
245+ if (!b) return null;
246+ const scale = ratio();
247+ const w = Math.ceil(b.w + EXPORT_MARGIN * 2);
248+ const h = Math.ceil(b.h + EXPORT_MARGIN * 2);
249+ const dx = EXPORT_MARGIN - b.x;
250+ const dy = EXPORT_MARGIN - b.y;
251+ const off = document.createElement("canvas");
252+ off.width = Math.round(w * scale);
253+ off.height = Math.round(h * scale);
254+ const oc = off.getContext("2d");
255+ if (!oc) return null;
256+ oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale);
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 })) }));
259+ const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg() };
260+ return { canvas: off, scene };
261+ };
262+
144 const save = async () => {263 const save = async () => {
145- if (!canvas || !canSave()) return;264+ if (!canSave()) return;
146- // Points live in CSS px (see pointAt), so the scene box is the canvas's CSS size.265+ const name = props.fileName ?? "drawing.png";
147- const rect = canvas.getBoundingClientRect();266+ const rendered = renderBounds();
148- const scene: DrawScene = { v: 1, w: Math.round(rect.width), h: Math.round(rect.height), strokes: strokes() };267+ if (rendered) {
149- props.onSave(await sceneToPngFile(canvas, scene, props.fileName ?? "drawing.png"));268+ props.onSave(await sceneToPngFile(rendered.canvas, rendered.scene, name));
269+ return;
270+ }
271+ // Cleared while editing an existing drawing: save a 1×1 blank to persist the erase.
272+ const blank = document.createElement("canvas");
273+ blank.width = 1;
274+ blank.height = 1;
275+ props.onSave(await sceneToPngFile(blank, { v: 1, w: 1, h: 1, strokes: [], bg: bg() }, name));
150 };276 };
151 277
152 const baseName = () => (props.fileName ?? "drawing").replace(/(\.hzdraw)?\.[a-z0-9]+$/i, "");278 const baseName = () => (props.fileName ?? "drawing").replace(/(\.hzdraw)?\.[a-z0-9]+$/i, "");
153 279
154 const download = async (mime: string, ext: string) => {280 const download = async (mime: string, ext: string) => {
155- if (!canvas || strokes().length === 0) return;281+ const rendered = renderBounds();
156- const blob = await canvasToImageBlob(canvas, mime);282+ if (!rendered) return;
283+ const blob = await canvasToImageBlob(rendered.canvas, mime, bg());
157 if (!blob) return;284 if (!blob) return;
158 const url = URL.createObjectURL(blob);285 const url = URL.createObjectURL(blob);
159 const link = document.createElement("a");286 const link = document.createElement("a");
@@ -163,6 +290,30 @@ export function DrawCanvas(props: {
163 URL.revokeObjectURL(url);290 URL.revokeObjectURL(url);
164 };291 };
165 292
293+ // Live ruling via CSS gradients so lines pan and zoom WITH the content: world
294+ // cell PAPER_CELL → PAPER_CELL*zoom on screen, a world-origin line sits at pan.
295+ // (Export bakes its own ruling; the two aren't pixel-identical, and needn't be.)
296+ const paperStyle = () => {
297+ const kind = bg();
298+ if (kind === "none") return {};
299+ const cell = PAPER_CELL * zoom();
300+ const p = pan();
301+ if (kind === "grid") {
302+ return {
303+ "background-image": `linear-gradient(to right, ${PAPER_LINE} 1px, transparent 1px), linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`,
304+ "background-size": `${cell}px ${cell}px`,
305+ "background-position": `${p.x}px ${p.y}px`,
306+ };
307+ }
308+ return {
309+ "background-image": `linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`,
310+ "background-size": `100% ${cell}px`,
311+ "background-position": `0 ${p.y}px`,
312+ };
313+ };
314+
315+ const bgLabel = () => (bg() === "none" ? t("draw.bgNone") : bg() === "lines" ? t("draw.bgLines") : t("draw.bgGrid"));
316+
166 const toolClass = (active: boolean) =>317 const toolClass = (active: boolean) =>
167 cn(318 cn(
168 "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors",319 "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors",
@@ -171,35 +322,149 @@ export function DrawCanvas(props: {
171 : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground",322 : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground",
172 );323 );
173 324
325+ // Line-thickness flyout shared by the pen and eraser triggers (width is one
326+ // shared signal, so both open the same picker). A JSX-returning local, not a
327+ // second exported component — one file, one component. Visibility is driven by
328+ // openMenu() (see the pointer/click handlers on each trigger); the pt-1.5 wrapper
329+ // bridges the gap so the mouse can travel trigger→flyout without pointerleave
330+ // firing. z-20 sits it above the sibling islands.
331+ const widthPicker = (id: "pen" | "eraser") => (
332+ <div
333+ class={cn(
334+ "absolute left-0 top-full z-20 pt-1.5 transition",
335+ openMenu() === id ? "translate-y-0 opacity-100" : "pointer-events-none invisible translate-y-1 opacity-0",
336+ )}
337+ >
338+ <div class={cn(OVERLAY_CARD, "static")} role="group" aria-label={t("draw.width")}>
339+ <For each={WIDTHS}>
340+ {(size) => (
341+ <button
342+ type="button"
343+ aria-pressed={width() === size}
344+ title={t("draw.width")}
345+ class={toolClass(width() === size)}
346+ onClick={() => {
347+ setWidth(size);
348+ setOpenMenu(null);
349+ }}
350+ >
351+ <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} />
352+ <span class="sr-only">{size}</span>
353+ </button>
354+ )}
355+ </For>
356+ </div>
357+ </div>
358+ );
359+
174 return (360 return (
175 <div class={cn("space-y-3", props.class)}>361 <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">362+ <div ref={wrap} class="relative h-[26rem] overflow-hidden rounded-lg border bg-white shadow-inner sm:h-[30rem]" style={paperStyle()}>
177- <div class="flex gap-1.5">363+ <canvas
178- <button type="button" class={toolClass(!erasing())} aria-pressed={!erasing()} title={t("draw.pen")} onClick={() => setErasing(false)}>364+ ref={canvas}
179- <IconEdit class="h-5 w-5" />365+ class="h-full w-full touch-none"
180- <span class="sr-only">{t("draw.pen")}</span>366+ classList={{ "cursor-grab": activeTool() === "pan" }}
181- </button>367+ onMouseDown={(e) => {
182- <button type="button" class={toolClass(erasing())} aria-pressed={erasing()} title={t("draw.eraser")} onClick={() => setErasing(true)}>368+ // preventDefault in pointerdown does not stop the middle-click autoscroll widget.
183- <IconEraser class="h-5 w-5" />369+ if (e.button === 1) e.preventDefault();
184- <span class="sr-only">{t("draw.eraser")}</span>370+ }}
371+ onContextMenu={(e) => e.preventDefault()}
372+ onPointerDown={startStroke}
373+ onPointerMove={extendStroke}
374+ onPointerUp={endStroke}
375+ onPointerCancel={endStroke}
376+ onWheel={(e) => {
377+ e.preventDefault();
378+ zoomBy(e.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP);
379+ }}
380+ />
381+ <Show when={strokes().length === 0 && !current}>
382+ <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400">{t("draw.hint")}</p>
383+ </Show>
384+
385+ {/* Top-left island — tools only: pen, eraser, pan. Pen and eraser each
386+ reveal the shared line-thickness flyout (open on hover/tap, toggled via
387+ openMenu()); pan has no flyout. */}
388+ <div class={cn(OVERLAY_CARD, "left-2 top-2")}>
389+ <div
390+ data-draw-menu
391+ class="relative"
392+ onPointerEnter={(e) => {
393+ if (e.pointerType !== "touch") setOpenMenu("pen");
394+ }}
395+ onPointerLeave={(e) => {
396+ if (e.pointerType !== "touch") setOpenMenu(null);
397+ }}
398+ >
399+ <button
400+ type="button"
401+ class={toolClass(activeTool() === "pen")}
402+ aria-haspopup="true"
403+ aria-expanded={openMenu() === "pen"}
404+ aria-pressed={activeTool() === "pen"}
405+ title={t("draw.pen")}
406+ onClick={() => {
407+ setErasing(false);
408+ setHand(false);
409+ setOpenMenu((o) => (o === "pen" ? null : "pen"));
410+ }}
411+ >
412+ <IconEdit class="h-5 w-5" />
413+ <span class="sr-only">{t("draw.pen")}</span>
414+ </button>
415+ {widthPicker("pen")}
416+ </div>
417+ <div
418+ data-draw-menu
419+ class="relative"
420+ onPointerEnter={(e) => {
421+ if (e.pointerType !== "touch") setOpenMenu("eraser");
422+ }}
423+ onPointerLeave={(e) => {
424+ if (e.pointerType !== "touch") setOpenMenu(null);
425+ }}
426+ >
427+ <button
428+ type="button"
429+ class={toolClass(activeTool() === "erase")}
430+ aria-haspopup="true"
431+ aria-expanded={openMenu() === "eraser"}
432+ aria-pressed={activeTool() === "erase"}
433+ title={t("draw.eraser")}
434+ onClick={() => {
435+ setErasing(true);
436+ setHand(false);
437+ setOpenMenu((o) => (o === "eraser" ? null : "eraser"));
438+ }}
439+ >
440+ <IconEraser class="h-5 w-5" />
441+ <span class="sr-only">{t("draw.eraser")}</span>
442+ </button>
443+ {widthPicker("eraser")}
444+ </div>
445+ <button type="button" class={toolClass(activeTool() === "pan")} aria-pressed={activeTool() === "pan"} title={t("draw.pan")} onClick={() => setHand(true)}>
446+ <IconMove class="h-5 w-5" />
447+ <span class="sr-only">{t("draw.pan")}</span>
185 </button>448 </button>
186 </div>449 </div>
187 450
188- <div class="flex gap-1.5" role="group" aria-label={t("draw.color")}>451+ {/* Top-middle island — colour swatches */}
452+ <div class={cn(OVERLAY_CARD, "left-1/2 top-2 -translate-x-1/2 flex-wrap items-center")} role="group" aria-label={t("draw.color")}>
189 <For each={COLORS}>453 <For each={COLORS}>
190 {(swatch) => (454 {(swatch) => (
191 <button455 <button
192 type="button"456 type="button"
193- aria-pressed={color() === swatch && !erasing()}457+ aria-pressed={color() === swatch && activeTool() === "pen"}
194 title={t("draw.color")}458 title={t("draw.color")}
195 class={cn(459 class={cn(
196- "h-11 w-11 rounded-lg border-2 transition-transform",460+ "h-9 w-9 sm:h-11 sm:w-11 rounded-lg border-2 transition-transform",
197- color() === swatch && !erasing() ? "border-foreground scale-105" : "border-border/60 hover:scale-105",461+ color() === swatch && activeTool() === "pen" ? "border-foreground scale-105" : "border-border/60 hover:scale-105",
198 )}462 )}
199 style={{ "background-color": swatch }}463 style={{ "background-color": swatch }}
200 onClick={() => {464 onClick={() => {
201 setColor(swatch);465 setColor(swatch);
202 setErasing(false);466 setErasing(false);
467+ setHand(false);
203 }}468 }}
204 >469 >
205 <span class="sr-only">{swatch}</span>470 <span class="sr-only">{swatch}</span>
@@ -208,41 +473,146 @@ export function DrawCanvas(props: {
208 </For>473 </For>
209 </div>474 </div>
210 475
211- <div class="flex gap-1.5" role="group" aria-label={t("draw.width")}>476+ {/* Top-right island — paper selector. The trigger shows the current paper;
212- <For each={WIDTHS}>477+ hover/tap toggles the none/lines/grid flyout via openMenu(). The card is
213- {(size) => (478+ already `absolute` (its own containing block), so the flyout positions off
214- <button type="button" aria-pressed={width() === size} title={t("draw.width")} class={toolClass(width() === size)} onClick={() => setWidth(size)}>479+ it without a `relative` wrapper. */}
215- <span class="rounded-full bg-current" style={{ width: `${size + 2}px`, height: `${size + 2}px` }} />480+ <div
216- <span class="sr-only">{size}</span>481+ data-draw-menu
217- </button>482+ class={cn(OVERLAY_CARD, "right-2 top-2")}
483+ onPointerEnter={(e) => {
484+ if (e.pointerType !== "touch") setOpenMenu("paper");
485+ }}
486+ onPointerLeave={(e) => {
487+ if (e.pointerType !== "touch") setOpenMenu(null);
488+ }}
489+ >
490+ <button
491+ type="button"
492+ class={toolClass(bg() !== "none")}
493+ aria-haspopup="true"
494+ aria-expanded={openMenu() === "paper"}
495+ aria-pressed={bg() !== "none"}
496+ title={bgLabel()}
497+ onClick={() => setOpenMenu((o) => (o === "paper" ? null : "paper"))}
498+ >
499+ <Switch>
500+ <Match when={bg() === "none"}>
501+ <IconSquareOff class="h-5 w-5" />
502+ </Match>
503+ <Match when={bg() === "lines"}>
504+ <IconRuled class="h-5 w-5" />
505+ </Match>
506+ <Match when={bg() === "grid"}>
507+ <IconGrid class="h-5 w-5" />
508+ </Match>
509+ </Switch>
510+ <span class="sr-only">{bgLabel()}</span>
511+ </button>
512+ {/* Paper flyout — opens downward, right-aligned; pt-1.5 bridges the gap so
513+ the mouse can travel trigger→flyout without pointerleave firing. */}
514+ <div
515+ class={cn(
516+ "absolute right-0 top-full z-20 pt-1.5 transition",
517+ openMenu() === "paper" ? "translate-y-0 opacity-100" : "pointer-events-none invisible translate-y-1 opacity-0",
218 )}518 )}
219- </For>519+ >
520+ <div class={cn(OVERLAY_CARD, "static")} role="group" aria-label={t("draw.paper")}>
521+ <button
522+ type="button"
523+ class={toolClass(bg() === "none")}
524+ aria-pressed={bg() === "none"}
525+ title={t("draw.bgNone")}
526+ onClick={() => {
527+ setBg("none");
528+ setOpenMenu(null);
529+ }}
530+ >
531+ <IconSquareOff class="h-5 w-5" />
532+ <span class="sr-only">{t("draw.bgNone")}</span>
533+ </button>
534+ <button
535+ type="button"
536+ class={toolClass(bg() === "lines")}
537+ aria-pressed={bg() === "lines"}
538+ title={t("draw.bgLines")}
539+ onClick={() => {
540+ setBg("lines");
541+ setOpenMenu(null);
542+ }}
543+ >
544+ <IconRuled class="h-5 w-5" />
545+ <span class="sr-only">{t("draw.bgLines")}</span>
546+ </button>
547+ <button
548+ type="button"
549+ class={toolClass(bg() === "grid")}
550+ aria-pressed={bg() === "grid"}
551+ title={t("draw.bgGrid")}
552+ onClick={() => {
553+ setBg("grid");
554+ setOpenMenu(null);
555+ }}
556+ >
557+ <IconGrid class="h-5 w-5" />
558+ <span class="sr-only">{t("draw.bgGrid")}</span>
559+ </button>
560+ </div>
561+ </div>
220 </div>562 </div>
221 563
222- <div class="ml-auto flex gap-1.5">564+ {/* Bottom-left history */}
223- <button type="button" class={toolClass(false)} disabled={strokes().length === 0} title={t("draw.undo")} onClick={undo}>565+ <div class={cn(OVERLAY_CARD, "bottom-2 left-2")}>
566+ <button
567+ type="button"
568+ class={cn(OVERLAY_BTN, "rounded-md disabled:pointer-events-none disabled:opacity-40")}
569+ disabled={strokes().length === 0}
570+ title={t("draw.undo")}
571+ onClick={undo}
572+ >
224 <IconUndo class="h-5 w-5" />573 <IconUndo class="h-5 w-5" />
225 <span class="sr-only">{t("draw.undo")}</span>574 <span class="sr-only">{t("draw.undo")}</span>
226 </button>575 </button>
227- <button type="button" class={toolClass(false)} disabled={strokes().length === 0} title={t("draw.clear")} onClick={clear}>576+ <button
577+ type="button"
578+ class={cn(OVERLAY_BTN, "rounded-md disabled:pointer-events-none disabled:opacity-40")}
579+ disabled={strokes().length === 0}
580+ title={t("draw.clear")}
581+ onClick={clear}
582+ >
228 <IconTrash class="h-5 w-5" />583 <IconTrash class="h-5 w-5" />
229 <span class="sr-only">{t("draw.clear")}</span>584 <span class="sr-only">{t("draw.clear")}</span>
230 </button>585 </button>
231 </div>586 </div>
232- </div>
233 587
234- <div ref={wrap} class="relative h-[22rem] overflow-hidden rounded-lg border bg-white shadow-inner">588+ <div class="absolute bottom-2 right-2 z-10 flex flex-col divide-y divide-border overflow-hidden rounded-lg border bg-card/90 shadow-sm backdrop-blur-sm">
235- <canvas589+ <button
236- ref={canvas}590+ type="button"
237- class="h-full w-full touch-none"591+ class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
238- onPointerDown={startStroke}592+ title={t("draw.zoomIn")}
239- onPointerMove={extendStroke}593+ onClick={() => zoomBy(ZOOM_STEP)}
240- onPointerUp={endStroke}594+ >
241- onPointerCancel={endStroke}595+ <IconZoomIn class="h-5 w-5" />
242- />596+ <span class="sr-only">{t("draw.zoomIn")}</span>
243- <Show when={strokes().length === 0 && !current}>597+ </button>
244- <p class="pointer-events-none absolute inset-0 flex items-center justify-center text-sm text-slate-400">{t("draw.hint")}</p>598+ <button
245- </Show>599+ type="button"
600+ class="flex h-9 w-9 items-center justify-center font-mono text-xs tabular-nums text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
601+ title={t("draw.resetZoom")}
602+ onClick={resetZoom}
603+ >
604+ {Math.round(zoom() * 100)}%
605+ </button>
606+ <button
607+ type="button"
608+ class="flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
609+ title={t("draw.zoomOut")}
610+ onClick={() => zoomBy(1 / ZOOM_STEP)}
611+ >
612+ <IconZoomOut class="h-5 w-5" />
613+ <span class="sr-only">{t("draw.zoomOut")}</span>
614+ </button>
615+ </div>
246 </div>616 </div>
247 617
248 <div class="flex flex-wrap items-center gap-2">618 <div class="flex flex-wrap items-center gap-2">
src/components/ui/icons.tsxmodified+55 -0
@@ -128,6 +128,51 @@ export function IconEraser(props: IconProps) {
128 );128 );
129 }129 }
130 130
131+export function IconMove(props: IconProps) {
132+ return (
133+ <Svg {...props}>
134+ <path d="M5 9l-3 3 3 3" />
135+ <path d="M9 5l3-3 3 3" />
136+ <path d="M15 19l-3 3-3-3" />
137+ <path d="M19 9l3 3-3 3" />
138+ <path d="M2 12h20" />
139+ <path d="M12 2v20" />
140+ </Svg>
141+ );
142+}
143+
144+export function IconGrid(props: IconProps) {
145+ return (
146+ <Svg {...props}>
147+ <rect width="18" height="18" x="3" y="3" rx="2" />
148+ <path d="M3 9h18" />
149+ <path d="M3 15h18" />
150+ <path d="M9 3v18" />
151+ <path d="M15 3v18" />
152+ </Svg>
153+ );
154+}
155+
156+export function IconRuled(props: IconProps) {
157+ return (
158+ <Svg {...props}>
159+ <line x1="4" y1="5" x2="20" y2="5" />
160+ <line x1="4" y1="10" x2="20" y2="10" />
161+ <line x1="4" y1="15" x2="20" y2="15" />
162+ <line x1="4" y1="19" x2="20" y2="19" />
163+ </Svg>
164+ );
165+}
166+
167+export function IconSquareOff(props: IconProps) {
168+ return (
169+ <Svg {...props}>
170+ <rect width="18" height="18" x="3" y="3" rx="2" />
171+ <path d="m3 21 18-18" />
172+ </Svg>
173+ );
174+}
175+
131 export function IconUndo(props: IconProps) {176 export function IconUndo(props: IconProps) {
132 return (177 return (
133 <Svg {...props}>178 <Svg {...props}>
@@ -191,6 +236,16 @@ export function IconZoomIn(props: IconProps) {
191 );236 );
192 }237 }
193 238
239+export function IconZoomOut(props: IconProps) {
240+ return (
241+ <Svg {...props}>
242+ <circle cx="11" cy="11" r="8" />
243+ <line x1="21" x2="16.65" y1="21" y2="16.65" />
244+ <line x1="8" x2="14" y1="11" y2="11" />
245+ </Svg>
246+ );
247+}
248+
194 export function IconHelpCircle(props: IconProps) {249 export function IconHelpCircle(props: IconProps) {
195 return (250 return (
196 <Svg {...props}>251 <Svg {...props}>
src/i18n/messages.tsmodified+24 -0
@@ -230,14 +230,22 @@ export type MessageKey =
230 | "notes.drawTitle"230 | "notes.drawTitle"
231 | "draw.pen"231 | "draw.pen"
232 | "draw.eraser"232 | "draw.eraser"
233+ | "draw.pan"
234+ | "draw.zoomIn"
235+ | "draw.zoomOut"
236+ | "draw.resetZoom"
233 | "draw.color"237 | "draw.color"
234 | "draw.width"238 | "draw.width"
239+ | "draw.paper"
235 | "draw.undo"240 | "draw.undo"
236 | "draw.clear"241 | "draw.clear"
237 | "draw.save"242 | "draw.save"
238 | "draw.hint"243 | "draw.hint"
239 | "draw.downloadPng"244 | "draw.downloadPng"
240 | "draw.downloadJpeg"245 | "draw.downloadJpeg"
246+ | "draw.bgNone"
247+ | "draw.bgLines"
248+ | "draw.bgGrid"
241 | "notes.downloadFile"249 | "notes.downloadFile"
242 | "notes.noFiles"250 | "notes.noFiles"
243 | "notes.fileLimit"251 | "notes.fileLimit"
@@ -932,14 +940,22 @@ const en: Dict = {
932 "notes.drawTitle": "Draw a picture",940 "notes.drawTitle": "Draw a picture",
933 "draw.pen": "Pen",941 "draw.pen": "Pen",
934 "draw.eraser": "Eraser",942 "draw.eraser": "Eraser",
943+ "draw.pan": "Move around",
944+ "draw.zoomIn": "Zoom in",
945+ "draw.zoomOut": "Zoom out",
946+ "draw.resetZoom": "Reset zoom",
935 "draw.color": "Colour",947 "draw.color": "Colour",
936 "draw.width": "Line thickness",948 "draw.width": "Line thickness",
949+ "draw.paper": "Paper",
937 "draw.undo": "Undo",950 "draw.undo": "Undo",
938 "draw.clear": "Clear all",951 "draw.clear": "Clear all",
939 "draw.save": "Save drawing",952 "draw.save": "Save drawing",
940 "draw.hint": "Draw here with your finger, pen, or mouse.",953 "draw.hint": "Draw here with your finger, pen, or mouse.",
941 "draw.downloadPng": "Download PNG",954 "draw.downloadPng": "Download PNG",
942 "draw.downloadJpeg": "Download JPEG",955 "draw.downloadJpeg": "Download JPEG",
956+ "draw.bgNone": "Plain",
957+ "draw.bgLines": "Lines",
958+ "draw.bgGrid": "Grid",
943 "notes.downloadFile": "Download",959 "notes.downloadFile": "Download",
944 "notes.noFiles": "No files attached.",960 "notes.noFiles": "No files attached.",
945 "notes.fileLimit": "This note already has 10 files.",961 "notes.fileLimit": "This note already has 10 files.",
@@ -1646,14 +1662,22 @@ const tr: Dict = {
1646 "notes.drawTitle": "Resim çiz",1662 "notes.drawTitle": "Resim çiz",
1647 "draw.pen": "Kalem",1663 "draw.pen": "Kalem",
1648 "draw.eraser": "Silgi",1664 "draw.eraser": "Silgi",
1665+ "draw.pan": "Gezin",
1666+ "draw.zoomIn": "Yakınlaştır",
1667+ "draw.zoomOut": "Uzaklaştır",
1668+ "draw.resetZoom": "Sıfırla",
1649 "draw.color": "Renk",1669 "draw.color": "Renk",
1650 "draw.width": "Çizgi kalınlığı",1670 "draw.width": "Çizgi kalınlığı",
1671+ "draw.paper": "Kağıt",
1651 "draw.undo": "Geri al",1672 "draw.undo": "Geri al",
1652 "draw.clear": "Hepsini sil",1673 "draw.clear": "Hepsini sil",
1653 "draw.save": "Çizimi kaydet",1674 "draw.save": "Çizimi kaydet",
1654 "draw.hint": "Parmağınla, kalemle ya da fareyle buraya çiz.",1675 "draw.hint": "Parmağınla, kalemle ya da fareyle buraya çiz.",
1655 "draw.downloadPng": "PNG indir",1676 "draw.downloadPng": "PNG indir",
1656 "draw.downloadJpeg": "JPEG indir",1677 "draw.downloadJpeg": "JPEG indir",
1678+ "draw.bgNone": "Düz",
1679+ "draw.bgLines": "Çizgili",
1680+ "draw.bgGrid": "Kareli",
1657 "notes.downloadFile": "İndir",1681 "notes.downloadFile": "İndir",
1658 "notes.noFiles": "Henüz dosya eklenmemiş.",1682 "notes.noFiles": "Henüz dosya eklenmemiş.",
1659 "notes.fileLimit": "Bu notta zaten 10 dosya var.",1683 "notes.fileLimit": "Bu notta zaten 10 dosya var.",
src/lib/draw-stroke.test.tsmodified+57 -1
@@ -1,5 +1,5 @@
1 import { describe, expect, it } from "vitest";1 import { describe, expect, it } from "vitest";
2-import { paintStroke, paintTip, parseScene, type DrawScene, type Stroke } from "./draw-stroke";2+import { paintPaper, paintStroke, paintTip, parseScene, 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() {
@@ -129,3 +129,59 @@ describe("parseScene", () => {
129 expect(parseScene(null)).toBeNull();129 expect(parseScene(null)).toBeNull();
130 });130 });
131 });131 });
132+
133+describe("strokesBounds", () => {
134+ it("is null with nothing drawn", () => {
135+ expect(strokesBounds([])).toBeNull();
136+ });
137+
138+ it("wraps every point and pads by half the stroke width", () => {
139+ const b = strokesBounds([
140+ stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // half-width 2
141+ stroke([{ x: 50, y: 40 }], { width: 10 }), // half-width 5
142+ ]);
143+ // minX 10-2=8, minY 10-2=8, maxX 50+5=55, maxY 40+5=45
144+ expect(b).toEqual({ x: 8, y: 8, w: 47, h: 37 });
145+ });
146+
147+ it("ignores eraser strokes so a far erase doesn't pad the export box", () => {
148+ const b = strokesBounds([
149+ stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // pen, half-width 2
150+ stroke([{ x: 500, y: 500 }], { width: 10, erase: true }), // far eraser — must not count
151+ ]);
152+ // same box as the pen stroke alone: minX 10-2=8, minY 10-2=8, maxX 30+2=32, maxY 20+2=22
153+ expect(b).toEqual({ x: 8, y: 8, w: 24, h: 14 });
154+ });
155+
156+ it("is null when the scene has only eraser strokes", () => {
157+ expect(strokesBounds([stroke([{ x: 5, y: 5 }], { erase: true })])).toBeNull();
158+ });
159+});
160+
161+describe("paintPaper", () => {
162+ it("draws nothing for none", () => {
163+ const c = stubContext();
164+ paintPaper(c, "none", 100, 100, 24);
165+ expect(c.calls).toEqual([]);
166+ });
167+
168+ it("draws only horizontal rules for lines", () => {
169+ const c = stubContext();
170+ paintPaper(c, "lines", 100, 100, 24);
171+ const moves = c.calls.filter((s) => s.startsWith("moveTo"));
172+ expect(moves.length).toBeGreaterThan(0);
173+ // every rule starts at the left edge (x=0) — no vertical segments
174+ expect(moves.every((s) => s.startsWith("moveTo(0,"))).toBe(true);
175+ expect(c.calls).toContain("stroke()");
176+ });
177+
178+ it("draws both horizontal and vertical lines for grid", () => {
179+ const c = stubContext();
180+ paintPaper(c, "grid", 100, 100, 24);
181+ const moves = c.calls.filter((s) => s.startsWith("moveTo"));
182+ const horizontal = moves.filter((s) => s.startsWith("moveTo(0,"));
183+ const vertical = moves.filter((s) => !s.startsWith("moveTo(0,"));
184+ expect(horizontal.length).toBeGreaterThan(0);
185+ expect(vertical.length).toBeGreaterThan(0);
186+ });
187+});
src/lib/draw-stroke.tsmodified+58 -1
@@ -1,6 +1,12 @@
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 DrawScene = { v: 1; w: number; h: number; strokes: Stroke[] };3+export type BgKind = "none" | "lines" | "grid";
4+export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind };
5+
6+/** 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+/** Faint blue-gray ruling colour for both the live CSS paper and the baked export. */
9+export const PAPER_LINE = "rgba(37, 99, 235, 0.14)";
4 10
5 function isPoint(p: unknown): p is Point {11 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";12 return !!p && typeof p === "object" && typeof (p as Point).x === "number" && typeof (p as Point).y === "number";
@@ -37,9 +43,36 @@ export function parseScene(text: string | null): DrawScene | null {
37 return null;43 return null;
38 }44 }
39 if (!scene.strokes.every(isStroke)) return null;45 if (!scene.strokes.every(isStroke)) return null;
46+ // 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;
40 return scene;48 return scene;
41 }49 }
42 50
51+/**
52+ * 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
54+ * export only the drawn region of an unbounded (pannable) pad instead of the
55+ * viewport.
56+ */
57+export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: number; h: number } | null {
58+ let minX = Infinity;
59+ let minY = Infinity;
60+ let maxX = -Infinity;
61+ let maxY = -Infinity;
62+ for (const s of strokes) {
63+ if (s.erase) continue; // eraser cuts existing ink, adds none — must not expand the export box
64+ const r = s.width / 2;
65+ for (const p of s.points) {
66+ minX = Math.min(minX, p.x - r);
67+ minY = Math.min(minY, p.y - r);
68+ maxX = Math.max(maxX, p.x + r);
69+ maxY = Math.max(maxY, p.y + r);
70+ }
71+ }
72+ if (!Number.isFinite(minX)) return null;
73+ return { x: minX, y: minY, w: maxX - minX, h: maxY - minY };
74+}
75+
43 function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) {76 function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) {
44 // The eraser cuts through the transparent drawing layer rather than painting77 // 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.78 // over it, so a saved drawing keeps whatever the caller flattens it onto.
@@ -89,3 +122,27 @@ export function paintTip(c: CanvasRenderingContext2D, stroke: Stroke) {
89 c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y);122 c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y);
90 c.stroke();123 c.stroke();
91 }124 }
125+
126+/**
127+ * Paint ruled/grid paper across a device-pixel box, meant to sit UNDER the
128+ * strokes. `step` is line spacing in device px. No-op for "none". Kept out of the
129+ * live redraw() on purpose: the eraser (destination-out) would cut these lines, so
130+ * the live pad rules itself with CSS and this only bakes the exported image.
131+ */
132+export function paintPaper(c: CanvasRenderingContext2D, bg: BgKind, width: number, height: number, step: number) {
133+ if (bg === "none" || step <= 0) return;
134+ c.strokeStyle = PAPER_LINE;
135+ c.lineWidth = 1;
136+ c.beginPath();
137+ for (let y = step; y < height; y += step) {
138+ c.moveTo(0, y);
139+ c.lineTo(width, y);
140+ }
141+ if (bg === "grid") {
142+ for (let x = step; x < width; x += step) {
143+ c.moveTo(x, 0);
144+ c.lineTo(x, height);
145+ }
146+ }
147+ c.stroke();
148+}
src/lib/drawing-file.tsmodified+7 -3
@@ -1,4 +1,4 @@
1-import { parseScene, type DrawScene } from "./draw-stroke";1+import { PAPER_CELL, paintPaper, parseScene, type BgKind, type DrawScene } from "./draw-stroke";
2 import { embedPngText, extractPngText } from "./png-meta";2 import { embedPngText, extractPngText } from "./png-meta";
3 3
4 /** tEXt keyword under which a drawing's editable stroke JSON is stored inside its PNG. */4 /** tEXt keyword under which a drawing's editable stroke JSON is stored inside its PNG. */
@@ -15,7 +15,7 @@ export function pngBytesToScene(bytes: Uint8Array): DrawScene | null {
15 * strokes would vanish on dark backgrounds once exported. DOM glue — needs a15 * strokes would vanish on dark backgrounds once exported. DOM glue — needs a
16 * document.16 * document.
17 */17 */
18-export function canvasToImageBlob(source: HTMLCanvasElement, mime: string): Promise<Blob | null> {18+export function canvasToImageBlob(source: HTMLCanvasElement, mime: string, bg: BgKind = "none"): Promise<Blob | null> {
19 const out = document.createElement("canvas");19 const out = document.createElement("canvas");
20 out.width = source.width;20 out.width = source.width;
21 out.height = source.height;21 out.height = source.height;
@@ -23,13 +23,17 @@ export function canvasToImageBlob(source: HTMLCanvasElement, mime: string): Prom
23 if (!oc) return Promise.resolve(null);23 if (!oc) return Promise.resolve(null);
24 oc.fillStyle = "#ffffff";24 oc.fillStyle = "#ffffff";
25 oc.fillRect(0, 0, out.width, out.height);25 oc.fillRect(0, 0, out.width, out.height);
26+ // Paper goes between the white fill and the transparent stroke layer, so erased
27+ // spots (transparent in `source`) reveal the ruling instead of the strokes.
28+ const dpr = window.devicePixelRatio || 1;
29+ paintPaper(oc, bg, out.width, out.height, PAPER_CELL * dpr);
26 oc.drawImage(source, 0, 0);30 oc.drawImage(source, 0, 0);
27 return new Promise((resolve) => out.toBlob(resolve, mime));31 return new Promise((resolve) => out.toBlob(resolve, mime));
28 }32 }
29 33
30 /** Encode the pad as a PNG File that both displays as an image and carries its editable scene. */34 /** 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> {35 export async function sceneToPngFile(source: HTMLCanvasElement, scene: DrawScene, name: string): Promise<File> {
32- const blob = await canvasToImageBlob(source, "image/png");36+ const blob = await canvasToImageBlob(source, "image/png", scene.bg ?? "none");
33 if (!blob) throw new Error("canvas PNG export failed");37 if (!blob) throw new Error("canvas PNG export failed");
34 const bytes = new Uint8Array(await blob.arrayBuffer());38 const bytes = new Uint8Array(await blob.arrayBuffer());
35 const withScene = embedPngText(bytes, DRAWING_KEYWORD, JSON.stringify(scene));39 const withScene = embedPngText(bytes, DRAWING_KEYWORD, JSON.stringify(scene));