Repository Public
1"use client";2/**3 * Editing surface. The drawing is the reader's own (layoutDiagram + DiagramSvg); this component adds the pannable /4 * zoomable viewport, the grid, the selection overlay and every pointer gesture. Hit-testing is geometric (ops.hitTest)5 * so targets are at least 44 px under a finger whatever the zoom, and no element of the drawing needs a listener.6 */7import { useEffect, useId, useRef, useState, type Dispatch, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";8import type { Sheet } from "@/schema";9import { DiagramSvg, type DiagramHighlight } from "@/renderer/diagram/DiagramSvg";10import type { DiagramLayout, Pt, Rect } from "@/renderer/diagram/layout";11import { V } from "@/renderer/tone";12import {13 EMPTY_SELECTION, GRID, boxesOf, clampZoom, hitTest, mergeSelection, moveNodes, selectInRect, toWorld, toggleSelect, zoomAt,14 type Boxes, type Diagram, type Hit, type Selection, type View,15} from "./ops";1617export type Tool = "select" | "pan" | "connect" | "step";1819export interface CanvasProps {20 /** Committed block: the base of every drag. */21 block: Diagram;22 /** Layout of what is shown (the committed block, or the draft of the drag in progress). */23 layout: DiagramLayout;24 theme: Sheet["theme"];25 view: View;26 onView: Dispatch<SetStateAction<View>>;27 onSize: (size: { width: number; height: number }) => void;28 tool: Tool;29 /** Touch equivalent of shift-click. */30 multi: boolean;31 snap: boolean;32 selection: Selection;33 onSelect: (selection: Selection) => void;34 /** Live preview of a move; null cancels it. */35 onDraft: (block: Diagram | null) => void;36 onCommit: (block: Diagram) => void;37 onConnect: (from: string, to: string) => void;38 onStepToggle: (kind: "nodes" | "edges", id: string) => void;39 /** A drag tried to move locked nodes only. */40 onLockedMove: () => void;41 highlight?: DiagramHighlight;42 label: string;43 hint: string;44}4546type Drag =47 | { kind: "pan"; start: Pt; view: View; moved: boolean; touch: boolean; hit: Hit | null; additive: boolean; selects: boolean }48 | { kind: "move"; start: Pt; base: Diagram; boxes: Boxes; ids: string[]; moved: boolean; touch: boolean; id: string; wasSelected: boolean; additive: boolean }49 | { kind: "marquee"; start: Pt; origin: Pt; base: Selection; moved: boolean; touch: boolean; additive: boolean }50 | { kind: "connect"; from: string; touch: boolean }51 | { kind: "pinch"; dist: number; mid: Pt; view: View };5253const HANDLE_GAP = 18;54/** Connector handle: to the right of the only selected node, with the select tool. */55function handleOf(layout: DiagramLayout, selection: Selection, tool: Tool, k: number): (Pt & { node: string }) | null {56 if (tool !== "select" || selection.nodes.length !== 1 || selection.edges.length !== 0) return null;57 const n = layout.nodes.find((b) => b.id === selection.nodes[0]);58 return n ? { node: n.id, x: n.left + n.width + HANDLE_GAP / k, y: n.y } : null;59}6061const CURSOR: Record<Tool, string> = { select: "default", pan: "grab", connect: "crosshair", step: "pointer" };6263export function Canvas(props: CanvasProps) {64 const { block, layout, view, theme, selection, tool, highlight, label, hint } = props;65 const latest = useRef(props);66 latest.current = props;67 const ref = useRef<HTMLDivElement>(null);68 const uid = useId().replace(/[^a-zA-Z0-9_-]/g, "");69 const pointers = useRef(new Map<number, Pt>());70 const drag = useRef<Drag | null>(null);71 const [marquee, setMarquee] = useState<Rect | null>(null);72 const [rubber, setRubber] = useState<{ from: string; to: Pt; target: string | null } | null>(null);7374 useEffect(() => {75 const el = ref.current;76 if (!el) return;77 const report = () => latest.current.onSize({ width: el.clientWidth, height: el.clientHeight });78 report();79 if (typeof ResizeObserver === "undefined") return;80 const ro = new ResizeObserver(report);81 ro.observe(el);82 return () => ro.disconnect();83 }, []);8485 // Pinch on a trackpad (ctrl + wheel) and a mouse wheel zoom about the pointer; a two-finger trackpad scroll pans.86 useEffect(() => {87 const el = ref.current;88 if (!el) return;89 const onWheel = (e: WheelEvent) => {90 e.preventDefault();91 const r = el.getBoundingClientRect(), sx = e.clientX - r.left, sy = e.clientY - r.top;92 const mouseWheel = e.deltaMode !== 0 || (e.deltaX === 0 && Number.isInteger(e.deltaY) && Math.abs(e.deltaY) >= 50);93 if (e.ctrlKey || e.metaKey || mouseWheel) {94 const unit = e.deltaMode === 1 ? 33 : e.deltaMode === 2 ? 400 : 1;95 const factor = Math.exp(-e.deltaY * unit * (mouseWheel ? 0.0015 : 0.01));96 latest.current.onView((v) => zoomAt(v, factor, sx, sy));97 } else {98 const dx = e.deltaX, dy = e.deltaY;99 latest.current.onView((v) => ({ k: v.k, x: v.x - dx, y: v.y - dy }));100 }101 };102 el.addEventListener("wheel", onWheel, { passive: false });103 return () => el.removeEventListener("wheel", onWheel);104 }, []);105106 const local = (e: { clientX: number; clientY: number }): Pt => {107 const r = ref.current?.getBoundingClientRect();108 return { x: e.clientX - (r?.left ?? 0), y: e.clientY - (r?.top ?? 0) };109 };110 const cancelDrag = () => {111 if (drag.current?.kind === "move") latest.current.onDraft(null);112 drag.current = null; setMarquee(null); setRubber(null);113 };114 const nodeAt = (P: CanvasProps, w: Pt, touch: boolean): string | null =>115 hitTest({ nodes: P.layout.nodes, edges: [] }, w, { minSize: touch ? 44 / P.view.k : 0 })?.id ?? null;116117 const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {118 const P = latest.current, el = ref.current;119 if (!el || (e.pointerType === "mouse" && e.button !== 0 && e.button !== 1)) return;120 if (e.target instanceof Element && e.target.closest("[data-canvas-ignore]")) return;121 el.focus({ preventScroll: true });122 el.setPointerCapture(e.pointerId);123 const s = local(e);124 pointers.current.set(e.pointerId, s);125 if (pointers.current.size === 2) {126 // A second finger turns any gesture into pan + pinch.127 cancelDrag();128 const [a, b] = [...pointers.current.values()];129 drag.current = { kind: "pinch", dist: Math.max(1, Math.hypot(b.x - a.x, b.y - a.y)), mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }, view: P.view };130 return;131 }132 if (pointers.current.size > 2) return;133 if (e.pointerType === "mouse") e.preventDefault();134135 const touch = e.pointerType !== "mouse";136 const k = P.view.k, w = toWorld(P.view, s.x, s.y);137 const hit = hitTest(P.layout, w, { tolerance: (touch ? 22 : 7) / k, minSize: touch ? 44 / k : 0 });138 const additive = e.shiftKey || P.multi;139 const active: Tool = e.button === 1 ? "pan" : P.tool;140 const pan = (selects: boolean): Drag => ({ kind: "pan", start: s, view: P.view, moved: false, touch, hit, additive, selects });141 const startConnect = (from: string) => { drag.current = { kind: "connect", from, touch }; setRubber({ from, to: w, target: null }); };142143 if (active === "pan") { drag.current = pan(e.button !== 1); return; }144 if (active === "step") {145 if (hit) { P.onStepToggle(hit.kind, hit.id); drag.current = null; } else drag.current = pan(false);146 return;147 }148 if (active === "connect") {149 if (hit?.kind === "nodes") startConnect(hit.id); else drag.current = pan(false);150 return;151 }152 const handle = handleOf(P.layout, P.selection, P.tool, k);153 if (handle && Math.hypot(w.x - handle.x, w.y - handle.y) <= (touch ? 22 : 12) / k) { startConnect(handle.node); return; }154 if (hit?.kind === "nodes") {155 const wasSelected = P.selection.nodes.includes(hit.id);156 let sel = P.selection;157 if (!wasSelected) { sel = toggleSelect(sel, "nodes", hit.id, additive); P.onSelect(sel); }158 drag.current = { kind: "move", start: s, base: P.block, boxes: boxesOf(P.layout), ids: sel.nodes, moved: false, touch, id: hit.id, wasSelected, additive };159 return;160 }161 if (hit) { P.onSelect(toggleSelect(P.selection, "edges", hit.id, additive)); drag.current = null; return; }162 drag.current = { kind: "marquee", start: s, origin: w, base: additive ? P.selection : EMPTY_SELECTION, moved: false, touch, additive };163 };164165 const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {166 if (!pointers.current.has(e.pointerId)) return;167 const s = local(e);168 pointers.current.set(e.pointerId, s);169 const d = drag.current, P = latest.current;170 if (!d) return;171 if (d.kind === "pinch") {172 if (pointers.current.size < 2) return;173 const [a, b] = [...pointers.current.values()];174 const dist = Math.max(1, Math.hypot(b.x - a.x, b.y - a.y)), mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };175 const k = clampZoom((d.view.k * dist) / d.dist), w = toWorld(d.view, d.mid.x, d.mid.y);176 P.onView({ k, x: mid.x - w.x * k, y: mid.y - w.y * k });177 return;178 }179 if (d.kind === "connect") {180 const w = toWorld(P.view, s.x, s.y), over = nodeAt(P, w, d.touch);181 setRubber({ from: d.from, to: w, target: over && over !== d.from ? over : null });182 return;183 }184 const dx = s.x - d.start.x, dy = s.y - d.start.y;185 if (!d.moved && Math.hypot(dx, dy) < (d.touch ? 8 : 4)) return;186 d.moved = true;187 if (d.kind === "pan") P.onView({ k: d.view.k, x: d.view.x + dx, y: d.view.y + dy });188 else if (d.kind === "move") P.onDraft(moveNodes(d.base, d.ids, dx / P.view.k, dy / P.view.k, d.boxes, P.snap ? GRID : 0));189 else {190 const w = toWorld(P.view, s.x, s.y);191 const rect = { x: d.origin.x, y: d.origin.y, width: w.x - d.origin.x, height: w.y - d.origin.y };192 setMarquee(rect);193 P.onSelect(mergeSelection(d.base, selectInRect(P.layout, rect)));194 }195 };196197 const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {198 if (!pointers.current.delete(e.pointerId)) return;199 const el = ref.current;200 if (el?.hasPointerCapture(e.pointerId)) el.releasePointerCapture(e.pointerId);201 const d = drag.current, P = latest.current;202 if (!d) return;203 if (d.kind === "pinch") { if (pointers.current.size < 2) drag.current = null; return; }204 if (e.type === "pointercancel") { cancelDrag(); return; }205 drag.current = null;206 const s = local(e);207 switch (d.kind) {208 case "pan":209 if (!d.moved && d.selects) P.onSelect(d.hit ? toggleSelect(P.selection, d.hit.kind, d.hit.id, d.additive) : d.additive ? P.selection : EMPTY_SELECTION);210 break;211 case "move":212 if (d.moved) {213 const next = moveNodes(d.base, d.ids, (s.x - d.start.x) / P.view.k, (s.y - d.start.y) / P.view.k, d.boxes, P.snap ? GRID : 0);214 if (next === d.base && d.base.nodes.some((n) => d.ids.includes(n.id) && n.locked)) P.onLockedMove();215 P.onCommit(next);216 } else if (d.wasSelected) P.onSelect(toggleSelect(P.selection, "nodes", d.id, d.additive));217 break;218 case "marquee":219 setMarquee(null);220 if (!d.moved && !d.additive) P.onSelect(EMPTY_SELECTION);221 break;222 case "connect": {223 setRubber(null);224 const over = nodeAt(P, toWorld(P.view, s.x, s.y), d.touch);225 if (over) P.onConnect(d.from, over);226 break;227 }228 }229 };230231 const k = view.k, vb = layout.viewBox;232 let step = GRID * k;233 while (step < 14) step *= 2;234 const px = (n: number) => n / k;235 const selectedNodes = new Set(selection.nodes), selectedEdges = new Set(selection.edges);236 const handle = handleOf(layout, selection, tool, k);237 const rubberFrom = rubber ? layout.nodes.find((n) => n.id === rubber.from) : undefined;238 const rubberTarget = rubber?.target ? layout.nodes.find((n) => n.id === rubber.target) : undefined;239 const m = marquee ? { x: Math.min(marquee.x, marquee.x + marquee.width), y: Math.min(marquee.y, marquee.y + marquee.height), width: Math.abs(marquee.width), height: Math.abs(marquee.height) } : null;240241 return (242 <div ref={ref} className="sheet" data-theme={theme.preset} data-accent={theme.accent} tabIndex={0} role="group" aria-label={label} aria-describedby={`${uid}-hint`}243 onPointerDown={onPointerDown} onPointerMove={onPointerMove} onPointerUp={onPointerUp} onPointerCancel={onPointerUp}244 style={{245 position: "relative", width: "100%", height: "100%", overflow: "hidden", touchAction: "none", userSelect: "none", WebkitUserSelect: "none", cursor: CURSOR[tool], outlineOffset: -2,246 backgroundColor: V.bg, backgroundImage: `radial-gradient(circle at 1px 1px, ${V.grid} 1px, transparent 1.5px)`,247 backgroundSize: `${step}px ${step}px`, backgroundPosition: `${view.x - 1}px ${view.y - 1}px`,248 }}>249 <p id={`${uid}-hint`} style={{ position: "absolute", width: 1, height: 1, overflow: "hidden", clipPath: "inset(50%)", whiteSpace: "nowrap" }}>{hint}</p>250 <div style={{ position: "absolute", left: view.x + vb.x * k, top: view.y + vb.y * k, width: vb.width * k, height: vb.height * k, pointerEvents: "none" }}>251 <DiagramSvg layout={layout} idPrefix={`ed${uid}`} highlight={highlight} width={vb.width * k} height={vb.height * k} />252 </div>253 <svg aria-hidden="true" focusable="false" width="100%" height="100%" style={{ position: "absolute", inset: 0, width: "100%", height: "100%", maxWidth: "none", pointerEvents: "none", overflow: "visible" }}>254 <g transform={`translate(${view.x} ${view.y}) scale(${k})`} fill="none" stroke={V.accent} strokeLinecap="round" strokeLinejoin="round">255 {layout.edges.filter((e) => selectedEdges.has(e.id)).map((e) => (256 <g key={e.id} data-selected-edge={e.id}>257 <path d={e.d} strokeWidth={px(7)} strokeOpacity={0.3} />258 {e.label ? <rect x={e.label.x - px(3)} y={e.label.y - px(3)} width={e.label.width + px(6)} height={e.label.height + px(6)} rx={px(8)} strokeWidth={px(2)} /> : null}259 {[e.points[0], e.points[e.points.length - 1]].map((p, i) => (p ? <circle key={i} cx={p.x} cy={p.y} r={px(4)} fill={V.surface} strokeWidth={px(2)} /> : null))}260 </g>261 ))}262 {layout.nodes.filter((n) => selectedNodes.has(n.id)).map((n) => (263 <rect key={n.id} data-selected-node={n.id} x={n.left - px(5)} y={n.top - px(5)} width={n.width + px(10)} height={n.height + px(10)} rx={px(8)} strokeWidth={px(2)}264 strokeDasharray={block.nodes.find((b) => b.id === n.id)?.locked ? `${px(6)} ${px(5)}` : undefined} />265 ))}266 {rubberTarget ? <rect x={rubberTarget.left - px(6)} y={rubberTarget.top - px(6)} width={rubberTarget.width + px(12)} height={rubberTarget.height + px(12)} rx={px(9)} strokeWidth={px(3)} /> : null}267 {rubber && rubberFrom ? <path d={`M${rubberFrom.x} ${rubberFrom.y}L${rubber.to.x} ${rubber.to.y}`} strokeWidth={px(2)} strokeDasharray={`${px(6)} ${px(5)}`} /> : null}268 {handle && !rubber ? (269 <g data-connector-handle={handle.node}>270 <path d={`M${handle.x - px(HANDLE_GAP - 5)} ${handle.y}H${handle.x - px(9)}`} strokeWidth={px(2)} />271 <circle cx={handle.x} cy={handle.y} r={px(9)} fill={V.accent} stroke={V.surface} strokeWidth={px(2)} />272 <path d={`M${handle.x - px(4)} ${handle.y}H${handle.x + px(4)}M${handle.x} ${handle.y - px(4)}V${handle.y + px(4)}`} stroke={V.surface} strokeWidth={px(1.8)} />273 </g>274 ) : null}275 {m ? <rect x={m.x} y={m.y} width={m.width} height={m.height} fill={V.accent} fillOpacity={0.08} strokeWidth={px(1.2)} strokeDasharray={`${px(4)} ${px(3)}`} /> : null}276 </g>277 </svg>278 </div>279 );280}281