SPB Git

Repository Public

DrawingView.tsx 18.2 KB 235 lines tsx

1"use client";2/**3 * file: src/components/editor/nodes/DrawingView.tsx4 * description: node view of the `drawing` block (SPEC §2). In the page it shows the PNG preview; "Edit" opens a vector ink editor in a5 *   sheet: one canvas driven by pointer events (mouse, finger, stylus with real pressure), pen / marker / highlighter / stroke eraser,6 *   colours, widths, undo / redo. Saving uploads the `spn-ink-1` JSON and a 2× PNG render, then writes `ink`, `preview`, `width`,7 *   `height` and `pk: null` (the native PencilKit data no longer matches). Nothing is drawn or measured until the sheet is opened.8 * author: Simon-Pierre Boucher — contact@spboucher.ai9 */10import * as React from "react";11import { Brush, Eraser, Highlighter, PenLine, Pencil, Redo2, Trash2, Undo2 } from "lucide-react";12import { Dialog, SheetContent, Spinner } from "@/components/ui/primitives";13import { Button } from "@/components/ui/button";14import { toast } from "@/components/ui/toast";15import { fileUrl, uploadBlob } from "@/lib/client/upload";16import type { DrawingAttrs } from "@/lib/editor/next-node-defs";17import { backgroundFill, drawInk, drawStroke, emptyInk, eraseAt, parseInk, serializeInk, simplifyStroke, type InkDoc, type InkPoint, type InkStroke, type InkTool } from "@/lib/editor/ink";18import { NodeButton, NodeFrame, NodeState, type LeafViewProps } from "./frame";1920const DEFAULT_W = 1200, DEFAULT_H = 800;21type Tool = InkTool | "eraser";22/** Stroke colours (content, not chrome). "Ink" is a mid slate that stays readable on the light and on the dark page. */23const COLORS: { name: string; hex: string }[] = [24  { name: "Ink", hex: "#64748b" }, { name: "Black", hex: "#111827" }, { name: "Red", hex: "#dc2626" }, { name: "Orange", hex: "#ea580c" },25  { name: "Yellow", hex: "#eab308" }, { name: "Green", hex: "#16a34a" }, { name: "Blue", hex: "#2563eb" }, { name: "Purple", hex: "#9333ea" },26];27/** Widths in canvas units per tool (for the eraser: its radius). */28const WIDTHS: Record<Tool, [number, number, number]> = { pen: [3, 5, 9], marker: [7, 11, 17], highlighter: [16, 26, 40], eraser: [8, 16, 30] };29const WIDTH_NAMES = ["Thin", "Medium", "Thick"] as const;30const TOOLS: { tool: Tool; label: string; icon: React.ReactNode }[] = [31  { tool: "pen", label: "Pen", icon: <PenLine /> }, { tool: "marker", label: "Marker", icon: <Brush /> }, { tool: "highlighter", label: "Highlighter", icon: <Highlighter /> }, { tool: "eraser", label: "Eraser", icon: <Eraser /> },32];33const HISTORY_LIMIT = 200;3435export function DrawingView({ attrs, update, editable, selected, pageId }: LeafViewProps<DrawingAttrs>) {36  const [open, setOpen] = React.useState(false);37  const [broken, setBroken] = React.useState<string | null>(null);38  const has = !!(attrs.ink || attrs.preview), w = attrs.width > 0 ? attrs.width : DEFAULT_W, h = attrs.height > 0 ? attrs.height : DEFAULT_H;39  return (40    <NodeFrame kind="drawing" icon={<PenLine />} label="Drawing" selected={selected} actions={editable && has ? <NodeButton label="Edit" text onClick={() => setOpen(true)}><Pencil /></NodeButton> : undefined}>41      {attrs.preview && broken !== attrs.preview ? (42        // eslint-disable-next-line @next/next/no-img-element -- authenticated attachment, intrinsic size known, no optimiser43        <img className="dr-preview" src={fileUrl(attrs.preview)} width={w} height={h} alt="Drawing" loading="lazy" decoding="async" draggable={false} onError={() => setBroken(attrs.preview)} />44      ) : has ? (45        <NodeState icon={<PenLine />} title="Preview unavailable" hint={attrs.preview ? "The image of this drawing could not be loaded." : "This drawing has no image yet."} tone={attrs.preview ? "danger" : "neutral"} />46      ) : (47        <NodeState icon={<PenLine />} title="Empty drawing" hint={editable ? "Sketch with a mouse, a finger or a stylus." : undefined}>48          {editable && <NodeButton label="Draw" text tone="accent" onClick={() => setOpen(true)}><PenLine /></NodeButton>}49        </NodeState>50      )}51      {open && editable && <InkDialog attrs={attrs} pageId={pageId} onClose={() => setOpen(false)} onSaved={(patch) => { update(patch); setOpen(false); }} />}52    </NodeFrame>53  );54}5556type Phase = { state: "loading" } | { state: "ready" } | { state: "error"; message: string };57interface Gesture { id: number; left: number; top: number; live: InkStroke | null; /** eraser: the document when the gesture began */ before: InkDoc | null; last: [number, number] }5859function InkDialog({ attrs, pageId, onClose, onSaved }: { attrs: DrawingAttrs; pageId: string | null; onClose: () => void; onSaved: (patch: Partial<DrawingAttrs>) => void }) {60  const [phase, setPhase] = React.useState<Phase>({ state: "loading" });61  const [tool, setTool] = React.useState<Tool>("pen");62  const [color, setColor] = React.useState(COLORS[0].hex);63  const [size, setSize] = React.useState(1);64  const [saving, setSaving] = React.useState(false);65  const [confirm, setConfirm] = React.useState(false);66  const [, setRev] = React.useState(0);67  const doc = React.useRef<InkDoc>(emptyInk(DEFAULT_W, DEFAULT_H)), initial = React.useRef<InkDoc>(doc.current);68  const past = React.useRef<InkDoc[]>([]), future = React.useRef<InkDoc[]>([]);69  const canvas = React.useRef<HTMLCanvasElement | null>(null), stage = React.useRef<HTMLDivElement | null>(null), cache = React.useRef<HTMLCanvasElement | null>(null);70  const geom = React.useRef({ css: 1, px: 1 }), gesture = React.useRef<Gesture | null>(null), raf = React.useRef(0), alive = React.useRef(true);71  const style = React.useRef({ tool, color, size }); style.current = { tool, color, size };72  const paper = backgroundFill(attrs.background);73  const bump = () => setRev((n) => n + 1);7475  // ---- painting: committed strokes live in an offscreen cache, a frame = cache + the stroke being drawn ----76  const rebuild = React.useCallback(() => {77    const c = canvas.current; if (!c) return;78    const off = (cache.current ??= document.createElement("canvas")); if (off.width !== c.width || off.height !== c.height) { off.width = c.width; off.height = c.height; }79    const ctx = off.getContext("2d"); if (!ctx) return;80    ctx.clearRect(0, 0, off.width, off.height); if (paper) { ctx.fillStyle = paper; ctx.fillRect(0, 0, off.width, off.height); }81    drawInk(ctx, doc.current, geom.current.px);82  }, [paper]);83  const paint = React.useCallback(() => {84    raf.current = 0; const c = canvas.current, ctx = c?.getContext("2d"); if (!c || !ctx) return;85    ctx.clearRect(0, 0, c.width, c.height); if (cache.current && cache.current.width > 0) ctx.drawImage(cache.current, 0, 0);86    const g = gesture.current; if (!g) return;87    if (g.live) drawStroke(ctx, g.live, geom.current.px);88    else { ctx.save(); ctx.beginPath(); ctx.arc(g.last[0] * geom.current.px, g.last[1] * geom.current.px, WIDTHS.eraser[style.current.size] * geom.current.px, 0, Math.PI * 2); ctx.lineWidth = Math.max(1, geom.current.px / geom.current.css); ctx.strokeStyle = "#8a8f98"; ctx.stroke(); ctx.restore(); }89  }, []);90  const schedule = React.useCallback(() => { if (!raf.current) raf.current = requestAnimationFrame(paint); }, [paint]);91  const refresh = React.useCallback(() => { rebuild(); schedule(); }, [rebuild, schedule]);9293  // ---- load the existing ink (never start blank over a drawing that cannot be read) ----94  React.useEffect(() => {95    alive.current = true; const ac = new AbortController();96    (async () => {97      if (!attrs.ink) {98        if (attrs.preview) return setPhase({ state: "error", message: "This drawing has an image but no editable ink data, so it cannot be edited here." });99        doc.current = initial.current = emptyInk(DEFAULT_W, DEFAULT_H); return setPhase({ state: "ready" });100      }101      try {102        const r = await fetch(fileUrl(attrs.ink), { credentials: "same-origin", signal: ac.signal });103        if (!r.ok) throw new Error(r.status === 404 ? "The ink file of this drawing no longer exists." : `The ink file could not be loaded (${r.status}).`);104        const parsed = parseInk(await r.text()); if (ac.signal.aborted) return;105        doc.current = initial.current = parsed; setPhase({ state: "ready" });106      } catch (e) { if (!ac.signal.aborted) setPhase({ state: "error", message: e instanceof Error ? e.message : "The ink file could not be read." }); }107    })();108    return () => { alive.current = false; ac.abort(); if (raf.current) cancelAnimationFrame(raf.current); raf.current = 0; };109  }, [attrs.ink, attrs.preview]);110111  // ---- size: canvas units → CSS px (fit width and the visible height) → device px; measured only when the stage resizes ----112  const ready = phase.state === "ready";113  React.useLayoutEffect(() => {114    const el = stage.current, c = canvas.current; if (!ready || !el || !c) return;115    const fit = (avail: number) => {116      if (!(avail > 0)) return; const W = doc.current.width, H = doc.current.height, dpr = Math.min(3, window.devicePixelRatio || 1);117      const room = Math.max(160, (window.visualViewport?.height ?? window.innerHeight) - 270), css = Math.min(avail / W, room / H), cw = Math.max(1, Math.floor(W * css)), ch = Math.max(1, Math.floor(H * css));118      const pw = Math.round(cw * dpr), ph = Math.round(ch * dpr); if (c.width === pw && c.height === ph) return;119      c.style.width = `${cw}px`; c.style.height = `${ch}px`; c.width = pw; c.height = ph; geom.current = { css: cw / W, px: pw / W }; rebuild(); paint();120    };121    fit(el.clientWidth);122    const ro = new ResizeObserver((entries) => fit(entries[0].contentRect.width)); ro.observe(el);123    return () => ro.disconnect();124  }, [ready, rebuild, paint]);125126  // ---- history ----127  const commit = (next: InkDoc, before: InkDoc = doc.current) => { if (next === before) return; past.current.push(before); if (past.current.length > HISTORY_LIMIT) past.current.shift(); future.current = []; doc.current = next; setConfirm(false); bump(); refresh(); };128  const undo = () => { const p = past.current.pop(); if (!p || gesture.current) return; future.current.push(doc.current); doc.current = p; bump(); refresh(); };129  const redo = () => { const f = future.current.pop(); if (!f || gesture.current) return; past.current.push(doc.current); doc.current = f; bump(); refresh(); };130  const clear = () => { if (doc.current.strokes.length && !gesture.current) commit({ ...doc.current, strokes: [] }); };131  const dirty = doc.current !== initial.current;132133  // ---- pointer input ----134  const at = (g: Gesture, e: { clientX: number; clientY: number; pressure: number; pointerType: string }): InkPoint => {135    const d = doc.current, x = Math.max(0, Math.min(d.width, (e.clientX - g.left) / geom.current.css)), y = Math.max(0, Math.min(d.height, (e.clientY - g.top) / geom.current.css));136    let p = e.pressure; if (e.pointerType !== "pen" || !(p > 0)) p = 1; // no force sensor (mouse, finger) → p = 1, the nominal width (same law on every platform)137    return [x, y, Math.min(1, p)];138  };139  const erase = (g: Gesture, pts: InkPoint[]) => { const next = eraseAt(doc.current, pts, WIDTHS.eraser[style.current.size]); if (next !== doc.current) { doc.current = next; rebuild(); } };140  const onDown = (e: React.PointerEvent<HTMLCanvasElement>) => {141    if (gesture.current || saving || (e.pointerType === "mouse" && e.button !== 0)) return;142    e.preventDefault(); const c = e.currentTarget; try { c.setPointerCapture(e.pointerId); } catch { /* synthetic pointer */ }143    const r = c.getBoundingClientRect(), s = style.current, g: Gesture = { id: e.pointerId, left: r.left, top: r.top, live: null, before: null, last: [0, 0] }, p = at(g, e); g.last = [p[0], p[1]];144    if (s.tool === "eraser") { g.before = doc.current; erase(g, [p]); }145    else g.live = { tool: s.tool, color: `${s.color}${s.tool === "highlighter" ? "66" : "ff"}`, width: WIDTHS[s.tool][s.size], points: [p] };146    gesture.current = g; schedule();147  };148  const onMove = (e: React.PointerEvent<HTMLCanvasElement>) => {149    const g = gesture.current; if (!g || g.id !== e.pointerId) return;150    const native = e.nativeEvent, batch = typeof native.getCoalescedEvents === "function" ? native.getCoalescedEvents() : []; const events = batch.length ? batch : [native];151    for (const ev of events) {152      const p = at(g, ev); if (Math.hypot(p[0] - g.last[0], p[1] - g.last[1]) < 0.35) continue;153      if (g.live) g.live.points.push(p); else erase(g, [[g.last[0], g.last[1], 0.5], p]);154      g.last = [p[0], p[1]];155    }156    schedule();157  };158  const finish = (e: React.PointerEvent<HTMLCanvasElement>, cancelled: boolean) => {159    const g = gesture.current; if (!g || g.id !== e.pointerId) return;160    gesture.current = null; try { e.currentTarget.releasePointerCapture(e.pointerId); } catch { /* already released */ }161    if (g.live) { if (!cancelled) commit({ ...doc.current, strokes: [...doc.current.strokes, { ...g.live, points: simplifyStroke(g.live.points, 0.3) }] }); else schedule(); }162    else if (g.before) { if (cancelled) { doc.current = g.before; refresh(); } else if (doc.current !== g.before) { const after = doc.current; doc.current = g.before; commit(after, g.before); } else schedule(); }163  };164165  // ---- save ----166  const save = async () => {167    if (saving || gesture.current) return; setSaving(true);168    try {169      const d = doc.current, ts = Date.now(), png = await renderPng(d, paper);170      const [ink, preview] = await Promise.all([uploadBlob(serializeInk(d), `drawing-${ts}.ink.json`, "application/json", pageId), uploadBlob(png, `drawing-${ts}.png`, "image/png", pageId)]);171      if (alive.current) onSaved({ ink: ink.id, preview: preview.id, pk: null, width: Math.round(d.width), height: Math.round(d.height) });172    } catch (e) {173      toast("Drawing not saved", { description: `${e instanceof Error ? e.message : "Upload failed"} — your strokes are still here, try again.`, tone: "danger" });174      if (alive.current) setSaving(false);175    }176  };177  const requestClose = () => { if (saving) return; if (dirty && !confirm) setConfirm(true); else onClose(); };178  const onKey = (e: React.KeyboardEvent) => { if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== "z" || !ready) return; e.preventDefault(); if (e.shiftKey) redo(); else undo(); };179180  const n = doc.current.strokes.length;181  return (182    <Dialog open onOpenChange={(o) => { if (!o) requestClose(); }}>183      <SheetContent title={attrs.ink ? "Edit drawing" : "New drawing"} className="sm:w-[min(60rem,calc(100vw-2rem))] sm:max-h-[94dvh]" onCloseAutoFocus={(e) => e.preventDefault()} onInteractOutside={(e) => e.preventDefault()} onKeyDown={onKey}>184        {phase.state === "loading" && <div className="flex items-center gap-2 py-10 text-ui text-fg-muted" role="status"><Spinner /> Loading the drawing…</div>}185        {phase.state === "error" && (186          <div className="py-4">187            <NodeState icon={<PenLine />} tone="danger" title="This drawing cannot be edited" hint={`${phase.message} Nothing was changed.`} />188            <div className="mt-3 flex justify-end"><Button variant="secondary" onClick={onClose}>Close</Button></div>189          </div>190        )}191        {ready && (192          <div className="dr-editor">193            <div className="dr-tools" role="toolbar" aria-label="Drawing tools">194              <div className="dr-group">{TOOLS.map((t) => <NodeButton key={t.tool} label={t.label} active={tool === t.tool} onClick={() => setTool(t.tool)}>{t.icon}</NodeButton>)}</div>195              <div className="dr-group" role="group" aria-label="Colour">196                {COLORS.map((c) => <button key={c.hex} type="button" className="dr-swatch" title={c.name} aria-label={c.name} aria-pressed={color === c.hex} disabled={tool === "eraser"} onClick={() => setColor(c.hex)}><span style={{ background: c.hex }} /></button>)}197              </div>198              <div className="dr-group" role="group" aria-label="Width">199                {WIDTH_NAMES.map((name, i) => <NodeButton key={name} label={name} active={size === i} onClick={() => setSize(i)}><span className="dr-dot" style={{ width: 4 + i * 4, height: 4 + i * 4 }} /></NodeButton>)}200              </div>201              <div className="dr-group">202                <NodeButton label="Undo" disabled={!past.current.length} onClick={undo}><Undo2 /></NodeButton>203                <NodeButton label="Redo" disabled={!future.current.length} onClick={redo}><Redo2 /></NodeButton>204                <NodeButton label="Clear" tone="danger" disabled={!n} onClick={clear}><Trash2 /></NodeButton>205              </div>206            </div>207            <div ref={stage} className="dr-stage">208              <canvas ref={canvas} data-testid="ink-canvas" className="dr-canvas" data-tool={tool} aria-label="Drawing surface" style={{ touchAction: "none", background: paper ?? undefined }}209                onPointerDown={onDown} onPointerMove={onMove} onPointerUp={(e) => finish(e, false)} onPointerCancel={(e) => finish(e, true)} onContextMenu={(e) => e.preventDefault()} />210            </div>211            <div className="dr-foot">212              {confirm ? (213                <><span className="min-w-0 flex-1 text-ui text-fg" role="alert">Discard the changes to this drawing?</span><Button variant="secondary" onClick={() => setConfirm(false)}>Keep editing</Button><Button variant="danger" onClick={onClose}>Discard</Button></>214              ) : (215                <><span className="nb-meta min-w-0 flex-1" aria-live="polite">{n} stroke{n === 1 ? "" : "s"}{dirty ? " · unsaved" : ""}</span><Button variant="ghost" onClick={requestClose} disabled={saving}>Cancel</Button>216                  <Button onClick={save} disabled={saving || !dirty} aria-label="Save drawing">{saving && <Spinner className="size-3.5" />}Save drawing</Button></>217              )}218            </div>219          </div>220        )}221      </SheetContent>222    </Dialog>223  );224}225226/** PNG of the strokes at 2× (less for a very large canvas, to stay under mobile canvas limits); transparent unless there is paper. */227function renderPng(doc: InkDoc, paper: string | null): Promise<Blob> {228  const scale = Math.min(2, Math.sqrt(16_000_000 / Math.max(1, doc.width * doc.height)));229  const c = document.createElement("canvas"); c.width = Math.max(1, Math.round(doc.width * scale)); c.height = Math.max(1, Math.round(doc.height * scale));230  const ctx = c.getContext("2d"); if (!ctx) return Promise.reject(new Error("This browser could not render the drawing"));231  if (paper) { ctx.fillStyle = paper; ctx.fillRect(0, 0, c.width, c.height); }232  drawInk(ctx, doc, c.width / doc.width);233  return new Promise((resolve, reject) => c.toBlob((b) => (b ? resolve(b) : reject(new Error("This browser could not render the drawing"))), "image/png"));234}235
Files main
Menu

Theme