From 0ae3da97cbd3c0eb4b6740625c8de1de6470e820 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 22 Jul 2026 04:01:50 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=A8=20infinite=20canvas,=20not?= =?UTF-8?q?ebook=20paper,=20and=20floating=20draw=20controls=20-=20pan=20a?= =?UTF-8?q?n=20unbounded=20pad=20(hand=20tool,=20middle-mouse=20drag,=20ri?= =?UTF-8?q?ght-click=20=20=20erases)=20with=20world-coord=20strokes;=20exp?= =?UTF-8?q?ort=20the=20drawn=20bounding=20box=20=20=20instead=20of=20the?= =?UTF-8?q?=20viewport=20so=20saved=20PNGs=20follow=20the=20content=20-=20?= =?UTF-8?q?view-only=20zoom=20(buttons=20+=20wheel,=200.25=C3=97=E2=80=934?= =?UTF-8?q?=C3=97);=20exports=20stay=20at=201=C3=97=20-=20notebook=20backg?= =?UTF-8?q?rounds=20plain=20/=20ruled=20/=20squared=20grid,=20baked=20into?= =?UTF-8?q?=20the=20=20=20PNG=20under=20a=20transparent=20stroke=20layer?= =?UTF-8?q?=20so=20the=20eraser=20can't=20cut=20the=20=20=20lines;=20the?= =?UTF-8?q?=20choice=20rides=20in=20the=20embedded=20scene=20JSON=20(no=20?= =?UTF-8?q?backend=20change)=20-=20strokesBounds=20ignores=20eraser=20stro?= =?UTF-8?q?kes=20so=20a=20far=20erase=20can't=20pad=20the=20=20=20export?= =?UTF-8?q?=20box;=20paintPaper=20draws=20the=20ruling=20(both=20unit-test?= =?UTF-8?q?ed)=20-=20floating=20glass=20control=20islands:=20tools+size=20?= =?UTF-8?q?top-left,=20colours=20=20=20top-middle,=20paper=20top-right,=20?= =?UTF-8?q?undo/clear=20+=20zoom=20in=20the=20corners=20-=20pen/eraser=20s?= =?UTF-8?q?ize=20and=20paper=20style=20open=20as=20hover/tap/keyboard=20me?= =?UTF-8?q?nus=20=20=20driven=20by=20an=20openMenu=20signal=20(closes=20on?= =?UTF-8?q?=20select,=20outside,=20Escape,=20leave)=20-=20transient=20tool?= =?UTF-8?q?=20highlight=20while=20middle/right=20button=20held;=20EN/TR=20?= =?UTF-8?q?i18n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/ui/draw-canvas.tsx | 508 ++++++++++++++++++++++++++---- src/components/ui/icons.tsx | 55 ++++ src/i18n/messages.ts | 24 ++ src/lib/draw-stroke.test.ts | 58 +++- src/lib/draw-stroke.ts | 59 +++- src/lib/drawing-file.ts | 10 +- 6 files changed, 640 insertions(+), 74 deletions(-) diff --git a/src/components/ui/draw-canvas.tsx b/src/components/ui/draw-canvas.tsx index 2dc94af..6d7530f 100644 --- a/src/components/ui/draw-canvas.tsx +++ b/src/components/ui/draw-canvas.tsx @@ -1,13 +1,22 @@ -import { For, Show, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js"; +import { For, Match, Show, Switch, createEffect, createSignal, onCleanup, onMount, untrack } from "solid-js"; import { Button } from "@/components/ui/button"; -import { IconDownload, IconEdit, IconEraser, IconSave, IconTrash, IconUndo } from "@/components/ui/icons"; +import { IconDownload, IconEdit, IconEraser, IconGrid, IconMove, IconRuled, IconSave, IconSquareOff, IconTrash, IconUndo, IconZoomIn, IconZoomOut } from "@/components/ui/icons"; import { cn } from "@/lib/cn"; -import { paintStroke, paintTip, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; +import { PAPER_CELL, PAPER_LINE, paintStroke, paintTip, strokesBounds, type BgKind, type DrawScene, type Point, type Stroke } from "@/lib/draw-stroke"; import { canvasToImageBlob, sceneToPngFile } from "@/lib/drawing-file"; import { useT } from "@/stores/preferences-context"; const COLORS = ["#1f2937", "#dc2626", "#2563eb", "#16a34a", "#ca8a04"]; const WIDTHS = [2, 6, 14]; +const ZOOM_MIN = 0.25; +const ZOOM_MAX = 4; +const ZOOM_STEP = 1.25; +// Whitespace kept around the drawn region when exporting the bounding box. +const EXPORT_MARGIN = 8; +// Floating glass overlays that live inside the canvas, matching the bottom-right +// zoom control. Position/size utilities are appended per overlay via cn(). +const OVERLAY_CARD = "absolute z-10 flex gap-1.5 rounded-lg border bg-card/90 p-1.5 shadow-sm backdrop-blur-sm"; +const OVERLAY_BTN = "flex h-9 w-9 items-center justify-center text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"; /** * Freehand drawing pad. `props.onSave` receives a PNG `File` that both displays @@ -27,21 +36,54 @@ export function DrawCanvas(props: { let canvas: HTMLCanvasElement | undefined; let wrap: HTMLDivElement | undefined; let current: Stroke | undefined; + // Live pan drag: pointer origin + pan value at grab, so the pad follows the finger. + let panStart: { x: number; y: number; px: number; py: number } | undefined; const [strokes, setStrokes] = createSignal([]); const [color, setColor] = createSignal(COLORS[0]); const [width, setWidth] = createSignal(WIDTHS[1]); const [erasing, setErasing] = createSignal(false); + const [hand, setHand] = createSignal(false); + // Transient tool while a non-left button is held (middle = pan, right = erase), + // so the toolbar highlights it as if clicked and reverts on release. + const [override, setOverride] = createSignal(null); + // The pad is unbounded — strokes live in world coords; pan is the world→screen + // offset in CSS px so you can move around a drawing larger than the viewport. + const [pan, setPan] = createSignal({ x: 0, y: 0 }); + // View-only magnification: screenCSS = world * zoom + pan. Strokes stay in world + // px, so stroke widths scale with the transform — never multiply them by hand. + const [zoom, setZoom] = createSignal(1); + // Notebook paper, drawn as CSS on the wrapper (never in redraw(), or the eraser + // would cut it). New pads default to squared grid — the look the pad is for. + const [bg, setBg] = createSignal("grid"); + // Which floating picker is open (pen/eraser line-thickness, or paper style). + // Driven by JS, not CSS :focus-within — a mouse click keeps focus on the trigger + // and the canvas isn't focusable to blur it, so focus-within stayed stuck open. + const [openMenu, setOpenMenu] = createSignal(null); const ratio = () => window.devicePixelRatio || 1; const context = () => canvas?.getContext("2d") ?? null; + // Transient override wins over the persistent tool so the toolbar reflects a held button. + const activeTool = (): "pen" | "erase" | "pan" => { + const o = override(); + if (o) return o; + if (hand()) return "pan"; + if (erasing()) return "erase"; + return "pen"; + }; + const redraw = () => { const c = context(); if (!c || !canvas) return; const scale = ratio(); + // Clear the whole backing store in device pixels, then shift into world space + // by the pan offset so off-origin strokes render where the pan puts them. c.setTransform(scale, 0, 0, scale, 0, 0); c.clearRect(0, 0, canvas.width / scale, canvas.height / scale); + const p = pan(); + const z = zoom(); + c.setTransform(z * scale, 0, 0, z * scale, p.x * scale, p.y * scale); for (const stroke of strokes()) paintStroke(c, stroke); if (current) paintStroke(c, current); }; @@ -61,40 +103,70 @@ export function DrawCanvas(props: { resize(); const observer = new ResizeObserver(() => resize()); if (wrap) observer.observe(wrap); - onCleanup(() => observer.disconnect()); + // Close any open flyout on a pointerdown outside every picker group, or Escape. + // The canvas isn't focusable, so nothing would otherwise dismiss it. + const onDocDown = (e: PointerEvent) => { + if (!(e.target as HTMLElement | null)?.closest("[data-draw-menu]")) setOpenMenu(null); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") setOpenMenu(null); + }; + document.addEventListener("pointerdown", onDocDown); + document.addEventListener("keydown", onKey); + onCleanup(() => { + observer.disconnect(); + document.removeEventListener("pointerdown", onDocDown); + document.removeEventListener("keydown", onKey); + }); }); - // Rescale a loaded scene to the current pad size, preserving aspect ratio, so a - // drawing made on one screen fits when reopened on a differently sized one - // instead of overflowing or clipping. - const fitStrokes = (scene: DrawScene): Stroke[] => { - const rect = canvas?.getBoundingClientRect(); - if (!rect?.width || !scene.w || !scene.h) return scene.strokes; - const factor = Math.min(rect.width / scene.w, rect.height / scene.h); - if (Math.abs(factor - 1) < 0.005) return scene.strokes; - return scene.strokes.map((s) => ({ - ...s, - width: s.width * factor, - points: s.points.map((p) => ({ x: p.x * factor, y: p.y * factor })), - })); - }; - // Load (or reload) an edited scene whenever the caller supplies one — including - // while the pad is already open. untrack keeps redraw's read of strokes() from - // turning this into a self-triggering loop. + // while the pad is already open. No rescale: the pad is unbounded, so rather than + // shrinking a big drawing to fit we keep it 1:1 and pan its content into the + // corner (you move around it from there). untrack keeps redraw's read of + // strokes() from turning this into a self-triggering loop. createEffect(() => { const scene = props.initialScene; untrack(() => { - setStrokes(scene ? fitStrokes(scene) : []); + const next = scene ? scene.strokes : []; + setStrokes(next); + setBg(scene?.bg ?? "none"); // old drawings lack bg → plain, preserving their original look + setZoom(1); // a reopened drawing starts at 100% + const b = strokesBounds(next); + setPan(b ? { x: EXPORT_MARGIN - b.x, y: EXPORT_MARGIN - b.y } : { x: 0, y: 0 }); redraw(); }); }); const pointAt = (e: PointerEvent): Point => { const rect = canvas!.getBoundingClientRect(); - return { x: e.clientX - rect.left, y: e.clientY - rect.top }; + const p = pan(); + const z = zoom(); + return { x: (e.clientX - rect.left - p.x) / z, y: (e.clientY - rect.top - p.y) / z }; }; + // Zoom around the pad center: keep the world point under the center fixed so + // content doesn't fly off. Clamped to [ZOOM_MIN, ZOOM_MAX]. + // ponytail: no pinch-zoom; buttons + wheel cover it, add 2-pointer tracking if touch users ask + const zoomBy = (factor: number) => { + if (!canvas) return; + const rect = canvas.getBoundingClientRect(); + const cx = rect.width / 2; + const cy = rect.height / 2; + const p = pan(); + const z0 = zoom(); + const z1 = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, z0 * factor)); + if (z1 === z0) return; + const wx = (cx - p.x) / z0; + const wy = (cy - p.y) / z0; + setZoom(z1); + setPan({ x: cx - wx * z1, y: cy - wy * z1 }); + redraw(); + }; + + // Snap back to 100% while keeping the centered content centered (no-op at 1). + const resetZoom = () => zoomBy(1 / zoom()); + const drawTip = (stroke: Stroke) => { const c = context(); if (c) paintTip(c, stroke); @@ -104,22 +176,44 @@ export function DrawCanvas(props: { if (props.pending) return; e.preventDefault(); canvas?.setPointerCapture(e.pointerId); + // Middle button (1) always pans; the hand tool pans on any button EXCEPT right, + // because right button always erases (see below). button is the real value only + // on pointerdown; -1 during move, which is why panStart/current carry the state. + if (e.button === 1 || (hand() && e.button !== 2)) { + if (e.button === 1) setOverride("pan"); // transient middle-button pan + const p = pan(); + panStart = { x: e.clientX, y: e.clientY, px: p.x, py: p.y }; + return; + } + // Right button (2) forces an erase stroke regardless of the selected tool. + const eraseNow = erasing() || e.button === 2; + if (e.button === 2) setOverride("erase"); // transient right-button erase current = { color: color(), - width: erasing() ? width() * 2.5 : width(), - erase: erasing(), + width: eraseNow ? width() * 2.5 : width(), + erase: eraseNow, points: [pointAt(e)], }; drawTip(current); }; const extendStroke = (e: PointerEvent) => { + if (panStart) { + setPan({ x: panStart.px + (e.clientX - panStart.x), y: panStart.py + (e.clientY - panStart.y) }); + redraw(); + return; + } if (!current) return; current.points.push(pointAt(e)); drawTip(current); }; const endStroke = () => { + setOverride(null); + if (panStart) { + panStart = undefined; + return; + } const done = current; current = undefined; if (!done) return; @@ -141,19 +235,52 @@ export function DrawCanvas(props: { // brand-new untouched pad has nothing to save. const canSave = () => strokes().length > 0 || props.initialScene != null; + // Render only the drawn region (not the viewport) onto an offscreen DPR-scaled + // canvas, and produce the matching scene with strokes shifted into that box. + // This is what makes the pad "infinite": export follows the content wherever it + // was drawn or panned to, instead of capturing what happens to be on screen. + const renderBounds = (): { canvas: HTMLCanvasElement; scene: DrawScene } | null => { + const list = strokes(); + const b = strokesBounds(list); + if (!b) return null; + const scale = ratio(); + const w = Math.ceil(b.w + EXPORT_MARGIN * 2); + const h = Math.ceil(b.h + EXPORT_MARGIN * 2); + const dx = EXPORT_MARGIN - b.x; + const dy = EXPORT_MARGIN - b.y; + const off = document.createElement("canvas"); + off.width = Math.round(w * scale); + off.height = Math.round(h * scale); + const oc = off.getContext("2d"); + if (!oc) return null; + oc.setTransform(scale, 0, 0, scale, dx * scale, dy * scale); + for (const s of list) paintStroke(oc, s); + const shifted = list.map((s) => ({ ...s, points: s.points.map((p) => ({ x: p.x + dx, y: p.y + dy })) })); + const scene: DrawScene = { v: 1, w, h, strokes: shifted, bg: bg() }; + return { canvas: off, scene }; + }; + const save = async () => { - if (!canvas || !canSave()) return; - // Points live in CSS px (see pointAt), so the scene box is the canvas's CSS size. - const rect = canvas.getBoundingClientRect(); - const scene: DrawScene = { v: 1, w: Math.round(rect.width), h: Math.round(rect.height), strokes: strokes() }; - props.onSave(await sceneToPngFile(canvas, scene, props.fileName ?? "drawing.png")); + if (!canSave()) return; + const name = props.fileName ?? "drawing.png"; + const rendered = renderBounds(); + if (rendered) { + props.onSave(await sceneToPngFile(rendered.canvas, rendered.scene, name)); + return; + } + // Cleared while editing an existing drawing: save a 1×1 blank to persist the erase. + const blank = document.createElement("canvas"); + blank.width = 1; + blank.height = 1; + props.onSave(await sceneToPngFile(blank, { v: 1, w: 1, h: 1, strokes: [], bg: bg() }, name)); }; const baseName = () => (props.fileName ?? "drawing").replace(/(\.hzdraw)?\.[a-z0-9]+$/i, ""); const download = async (mime: string, ext: string) => { - if (!canvas || strokes().length === 0) return; - const blob = await canvasToImageBlob(canvas, mime); + const rendered = renderBounds(); + if (!rendered) return; + const blob = await canvasToImageBlob(rendered.canvas, mime, bg()); if (!blob) return; const url = URL.createObjectURL(blob); const link = document.createElement("a"); @@ -163,6 +290,30 @@ export function DrawCanvas(props: { URL.revokeObjectURL(url); }; + // Live ruling via CSS gradients so lines pan and zoom WITH the content: world + // cell PAPER_CELL → PAPER_CELL*zoom on screen, a world-origin line sits at pan. + // (Export bakes its own ruling; the two aren't pixel-identical, and needn't be.) + const paperStyle = () => { + const kind = bg(); + if (kind === "none") return {}; + const cell = PAPER_CELL * zoom(); + const p = pan(); + if (kind === "grid") { + return { + "background-image": `linear-gradient(to right, ${PAPER_LINE} 1px, transparent 1px), linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, + "background-size": `${cell}px ${cell}px`, + "background-position": `${p.x}px ${p.y}px`, + }; + } + return { + "background-image": `linear-gradient(to bottom, ${PAPER_LINE} 1px, transparent 1px)`, + "background-size": `100% ${cell}px`, + "background-position": `0 ${p.y}px`, + }; + }; + + const bgLabel = () => (bg() === "none" ? t("draw.bgNone") : bg() === "lines" ? t("draw.bgLines") : t("draw.bgGrid")); + const toolClass = (active: boolean) => cn( "flex h-11 w-11 items-center justify-center rounded-lg border transition-colors", @@ -171,35 +322,149 @@ export function DrawCanvas(props: { : "border-border bg-background text-muted-foreground hover:bg-accent hover:text-foreground", ); + // Line-thickness flyout shared by the pen and eraser triggers (width is one + // shared signal, so both open the same picker). A JSX-returning local, not a + // second exported component — one file, one component. Visibility is driven by + // openMenu() (see the pointer/click handlers on each trigger); the pt-1.5 wrapper + // bridges the gap so the mouse can travel trigger→flyout without pointerleave + // firing. z-20 sits it above the sibling islands. + const widthPicker = (id: "pen" | "eraser") => ( +
+
+ + {(size) => ( + + )} + +
+
+ ); + return (
-
-
- - + {widthPicker("pen")} +
+
{ + if (e.pointerType !== "touch") setOpenMenu("eraser"); + }} + onPointerLeave={(e) => { + if (e.pointerType !== "touch") setOpenMenu(null); + }} + > + + {widthPicker("eraser")} +
+
-
+ {/* Top-middle island — colour swatches */} +
{(swatch) => (
-
- - {(size) => ( - + {/* Top-right island — paper selector. The trigger shows the current paper; + hover/tap toggles the none/lines/grid flyout via openMenu(). The card is + already `absolute` (its own containing block), so the flyout positions off + it without a `relative` wrapper. */} +
{ + if (e.pointerType !== "touch") setOpenMenu("paper"); + }} + onPointerLeave={(e) => { + if (e.pointerType !== "touch") setOpenMenu(null); + }} + > + + {/* Paper flyout — opens downward, right-aligned; pt-1.5 bridges the gap so + the mouse can travel trigger→flyout without pointerleave firing. */} +
+ > +
+ + + +
+
-
- -
-
-
- - -

{t("draw.hint")}

-
+
+ + + +
diff --git a/src/components/ui/icons.tsx b/src/components/ui/icons.tsx index d73911f..5aa590a 100644 --- a/src/components/ui/icons.tsx +++ b/src/components/ui/icons.tsx @@ -128,6 +128,51 @@ export function IconEraser(props: IconProps) { ); } +export function IconMove(props: IconProps) { + return ( + + + + + + + + + ); +} + +export function IconGrid(props: IconProps) { + return ( + + + + + + + + ); +} + +export function IconRuled(props: IconProps) { + return ( + + + + + + + ); +} + +export function IconSquareOff(props: IconProps) { + return ( + + + + + ); +} + export function IconUndo(props: IconProps) { return ( @@ -191,6 +236,16 @@ export function IconZoomIn(props: IconProps) { ); } +export function IconZoomOut(props: IconProps) { + return ( + + + + + + ); +} + export function IconHelpCircle(props: IconProps) { return ( diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index cc56125..3ab6c3c 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -230,14 +230,22 @@ export type MessageKey = | "notes.drawTitle" | "draw.pen" | "draw.eraser" + | "draw.pan" + | "draw.zoomIn" + | "draw.zoomOut" + | "draw.resetZoom" | "draw.color" | "draw.width" + | "draw.paper" | "draw.undo" | "draw.clear" | "draw.save" | "draw.hint" | "draw.downloadPng" | "draw.downloadJpeg" + | "draw.bgNone" + | "draw.bgLines" + | "draw.bgGrid" | "notes.downloadFile" | "notes.noFiles" | "notes.fileLimit" @@ -932,14 +940,22 @@ const en: Dict = { "notes.drawTitle": "Draw a picture", "draw.pen": "Pen", "draw.eraser": "Eraser", + "draw.pan": "Move around", + "draw.zoomIn": "Zoom in", + "draw.zoomOut": "Zoom out", + "draw.resetZoom": "Reset zoom", "draw.color": "Colour", "draw.width": "Line thickness", + "draw.paper": "Paper", "draw.undo": "Undo", "draw.clear": "Clear all", "draw.save": "Save drawing", "draw.hint": "Draw here with your finger, pen, or mouse.", "draw.downloadPng": "Download PNG", "draw.downloadJpeg": "Download JPEG", + "draw.bgNone": "Plain", + "draw.bgLines": "Lines", + "draw.bgGrid": "Grid", "notes.downloadFile": "Download", "notes.noFiles": "No files attached.", "notes.fileLimit": "This note already has 10 files.", @@ -1646,14 +1662,22 @@ const tr: Dict = { "notes.drawTitle": "Resim çiz", "draw.pen": "Kalem", "draw.eraser": "Silgi", + "draw.pan": "Gezin", + "draw.zoomIn": "Yakınlaştır", + "draw.zoomOut": "Uzaklaştır", + "draw.resetZoom": "Sıfırla", "draw.color": "Renk", "draw.width": "Çizgi kalınlığı", + "draw.paper": "Kağıt", "draw.undo": "Geri al", "draw.clear": "Hepsini sil", "draw.save": "Çizimi kaydet", "draw.hint": "Parmağınla, kalemle ya da fareyle buraya çiz.", "draw.downloadPng": "PNG indir", "draw.downloadJpeg": "JPEG indir", + "draw.bgNone": "Düz", + "draw.bgLines": "Çizgili", + "draw.bgGrid": "Kareli", "notes.downloadFile": "İndir", "notes.noFiles": "Henüz dosya eklenmemiş.", "notes.fileLimit": "Bu notta zaten 10 dosya var.", diff --git a/src/lib/draw-stroke.test.ts b/src/lib/draw-stroke.test.ts index 232ac0c..4b84be3 100644 --- a/src/lib/draw-stroke.test.ts +++ b/src/lib/draw-stroke.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { paintStroke, paintTip, parseScene, type DrawScene, type Stroke } from "./draw-stroke"; +import { paintPaper, paintStroke, paintTip, parseScene, strokesBounds, type DrawScene, type Stroke } from "./draw-stroke"; /** Records every 2d-context call so the three geometry branches can be asserted without a DOM. */ function stubContext() { @@ -129,3 +129,59 @@ describe("parseScene", () => { expect(parseScene(null)).toBeNull(); }); }); + +describe("strokesBounds", () => { + it("is null with nothing drawn", () => { + expect(strokesBounds([])).toBeNull(); + }); + + it("wraps every point and pads by half the stroke width", () => { + const b = strokesBounds([ + stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // half-width 2 + stroke([{ x: 50, y: 40 }], { width: 10 }), // half-width 5 + ]); + // minX 10-2=8, minY 10-2=8, maxX 50+5=55, maxY 40+5=45 + expect(b).toEqual({ x: 8, y: 8, w: 47, h: 37 }); + }); + + it("ignores eraser strokes so a far erase doesn't pad the export box", () => { + const b = strokesBounds([ + stroke([{ x: 10, y: 10 }, { x: 30, y: 20 }], { width: 4 }), // pen, half-width 2 + stroke([{ x: 500, y: 500 }], { width: 10, erase: true }), // far eraser — must not count + ]); + // same box as the pen stroke alone: minX 10-2=8, minY 10-2=8, maxX 30+2=32, maxY 20+2=22 + expect(b).toEqual({ x: 8, y: 8, w: 24, h: 14 }); + }); + + it("is null when the scene has only eraser strokes", () => { + expect(strokesBounds([stroke([{ x: 5, y: 5 }], { erase: true })])).toBeNull(); + }); +}); + +describe("paintPaper", () => { + it("draws nothing for none", () => { + const c = stubContext(); + paintPaper(c, "none", 100, 100, 24); + expect(c.calls).toEqual([]); + }); + + it("draws only horizontal rules for lines", () => { + const c = stubContext(); + paintPaper(c, "lines", 100, 100, 24); + const moves = c.calls.filter((s) => s.startsWith("moveTo")); + expect(moves.length).toBeGreaterThan(0); + // every rule starts at the left edge (x=0) — no vertical segments + expect(moves.every((s) => s.startsWith("moveTo(0,"))).toBe(true); + expect(c.calls).toContain("stroke()"); + }); + + it("draws both horizontal and vertical lines for grid", () => { + const c = stubContext(); + paintPaper(c, "grid", 100, 100, 24); + const moves = c.calls.filter((s) => s.startsWith("moveTo")); + const horizontal = moves.filter((s) => s.startsWith("moveTo(0,")); + const vertical = moves.filter((s) => !s.startsWith("moveTo(0,")); + expect(horizontal.length).toBeGreaterThan(0); + expect(vertical.length).toBeGreaterThan(0); + }); +}); diff --git a/src/lib/draw-stroke.ts b/src/lib/draw-stroke.ts index 3413899..1f7082e 100644 --- a/src/lib/draw-stroke.ts +++ b/src/lib/draw-stroke.ts @@ -1,6 +1,12 @@ export type Point = { x: number; y: number }; export type Stroke = { color: string; width: number; erase: boolean; points: Point[] }; -export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[] }; +export type BgKind = "none" | "lines" | "grid"; +export type DrawScene = { v: 1; w: number; h: number; strokes: Stroke[]; bg?: BgKind }; + +/** World px per notebook cell — shared by the live CSS paper and the baked export so both read as the same ruling. */ +export const PAPER_CELL = 24; +/** Faint blue-gray ruling colour for both the live CSS paper and the baked export. */ +export const PAPER_LINE = "rgba(37, 99, 235, 0.14)"; function isPoint(p: unknown): p is Point { 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 { return null; } if (!scene.strokes.every(isStroke)) return null; + // bg is optional (old drawings lack it); reject only a present-but-bogus value. + if (scene.bg !== undefined && scene.bg !== "none" && scene.bg !== "lines" && scene.bg !== "grid") return null; return scene; } +/** + * Tight bounding box over every ink (pen) stroke, padded by its half-width so a + * thick line isn't clipped at the edge. Null when there's nothing drawn. Used to + * export only the drawn region of an unbounded (pannable) pad instead of the + * viewport. + */ +export function strokesBounds(strokes: Stroke[]): { x: number; y: number; w: number; h: number } | null { + let minX = Infinity; + let minY = Infinity; + let maxX = -Infinity; + let maxY = -Infinity; + for (const s of strokes) { + if (s.erase) continue; // eraser cuts existing ink, adds none — must not expand the export box + const r = s.width / 2; + for (const p of s.points) { + minX = Math.min(minX, p.x - r); + minY = Math.min(minY, p.y - r); + maxX = Math.max(maxX, p.x + r); + maxY = Math.max(maxY, p.y + r); + } + } + if (!Number.isFinite(minX)) return null; + return { x: minX, y: minY, w: maxX - minX, h: maxY - minY }; +} + function applyBrush(c: CanvasRenderingContext2D, stroke: Stroke) { // The eraser cuts through the transparent drawing layer rather than painting // over it, so a saved drawing keeps whatever the caller flattens it onto. @@ -89,3 +122,27 @@ export function paintTip(c: CanvasRenderingContext2D, stroke: Stroke) { c.lineTo(pts[pts.length - 1].x, pts[pts.length - 1].y); c.stroke(); } + +/** + * Paint ruled/grid paper across a device-pixel box, meant to sit UNDER the + * strokes. `step` is line spacing in device px. No-op for "none". Kept out of the + * live redraw() on purpose: the eraser (destination-out) would cut these lines, so + * the live pad rules itself with CSS and this only bakes the exported image. + */ +export function paintPaper(c: CanvasRenderingContext2D, bg: BgKind, width: number, height: number, step: number) { + if (bg === "none" || step <= 0) return; + c.strokeStyle = PAPER_LINE; + c.lineWidth = 1; + c.beginPath(); + for (let y = step; y < height; y += step) { + c.moveTo(0, y); + c.lineTo(width, y); + } + if (bg === "grid") { + for (let x = step; x < width; x += step) { + c.moveTo(x, 0); + c.lineTo(x, height); + } + } + c.stroke(); +} diff --git a/src/lib/drawing-file.ts b/src/lib/drawing-file.ts index ea244ab..4f1238f 100644 --- a/src/lib/drawing-file.ts +++ b/src/lib/drawing-file.ts @@ -1,4 +1,4 @@ -import { parseScene, type DrawScene } from "./draw-stroke"; +import { PAPER_CELL, paintPaper, parseScene, type BgKind, type DrawScene } from "./draw-stroke"; import { embedPngText, extractPngText } from "./png-meta"; /** 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 { * strokes would vanish on dark backgrounds once exported. DOM glue — needs a * document. */ -export function canvasToImageBlob(source: HTMLCanvasElement, mime: string): Promise { +export function canvasToImageBlob(source: HTMLCanvasElement, mime: string, bg: BgKind = "none"): Promise { const out = document.createElement("canvas"); out.width = source.width; out.height = source.height; @@ -23,13 +23,17 @@ export function canvasToImageBlob(source: HTMLCanvasElement, mime: string): Prom if (!oc) return Promise.resolve(null); oc.fillStyle = "#ffffff"; oc.fillRect(0, 0, out.width, out.height); + // Paper goes between the white fill and the transparent stroke layer, so erased + // spots (transparent in `source`) reveal the ruling instead of the strokes. + const dpr = window.devicePixelRatio || 1; + paintPaper(oc, bg, out.width, out.height, PAPER_CELL * dpr); oc.drawImage(source, 0, 0); return new Promise((resolve) => out.toBlob(resolve, mime)); } /** Encode the pad as a PNG File that both displays as an image and carries its editable scene. */ export async function sceneToPngFile(source: HTMLCanvasElement, scene: DrawScene, name: string): Promise { - const blob = await canvasToImageBlob(source, "image/png"); + const blob = await canvasToImageBlob(source, "image/png", scene.bg ?? "none"); if (!blob) throw new Error("canvas PNG export failed"); const bytes = new Uint8Array(await blob.arrayBuffer()); const withScene = embedPngText(bytes, DRAWING_KEYWORD, JSON.stringify(scene));