SPB Git

Repository Public

DiagramEditor.tsx 18.6 KB 308 lines tsx

1"use client";2/**3 * Visual editor of a `diagram` block.4 *5 * The canvas draws with the reader's own layout engine and SVG component, so what is edited is what is published.6 * State: a local undo / redo history of schema-valid blocks; every committed change is validated with BlockSchema and7 * handed to the host through `onChange` (one call = one undo step for the host). Pure logic lives in ./ops.8 *9 * Desktop: toolbar on top, layers on the left, canvas in the middle, properties / steps on the right.10 * Phone (< 768 px): full-width canvas, a bottom bar of large buttons, panels as bottom drawers. Nothing needs hover,11 * and the layers list with the property panel is a complete keyboard alternative to the pointer gestures.12 */13import { useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";14import { stableStringify, type BlockOf, type Locale, type Sheet } from "@/schema";15import { fill } from "@/i18n/dict";16import { layoutDiagram } from "@/renderer/diagram/layout";17import { Canvas, type Tool } from "./Canvas";18import {19  EMPTY_SELECTION, GRID, LIMITS, actualSize, addNode, addedIds, assignGroup, boxesOf, connect, connectIssue, createGroup, deleteSelection, duplicateSelection,20  fitView, nudge, pruneSelection, resetLayout, selectAll, selectionSize, setLocked, snap, stepsOf, toWorld, toggleStepItem, validate, zoomAt,21  type Diagram, type Selection, type View,22} from "./ops";23import { LayersPanel, PropertiesPanel, StepsPanel } from "./panels";24import { T } from "./strings";25import { IconButton } from "./ui";2627export interface DiagramEditorProps {28  block: BlockOf<"diagram">;29  /** Called with a complete, schema-valid block on every committed change (one call = one undo step in the host). */30  onChange: (next: BlockOf<"diagram">) => void;31  locale: Locale;32  /** Sheet theme, so the canvas uses the sheet's colours. */33  theme: Sheet["theme"];34}3536interface History { past: Diagram[]; present: Diagram; future: Diagram[] }37const HISTORY = 200;38type Message = { kind: "error" | "info"; text: string };3940const Sep = () => <span className="mx-1 h-6 w-px shrink-0 bg-line" aria-hidden="true" />;41const DRAWER = "absolute inset-x-0 bottom-0 z-20 max-h-[72%] min-h-0 flex-col overflow-hidden rounded-t-2xl border-t border-line bg-surface shadow-2xl md:static md:z-auto md:flex md:max-h-none md:rounded-none md:border-t-0 md:shadow-none";4243export function DiagramEditor({ block, onChange, locale, theme }: DiagramEditorProps) {44  const t = T(locale);4546  // ── Document, history, validity ──47  const [hist, setHist] = useState<History>({ past: [], present: block, future: [] });48  const [external, setExternal] = useState(block);49  if (block !== external) {50    // The host changed the block itself (its own undo, an AI edit): adopt it as a new step of the session.51    setExternal(block);52    if (stableStringify(block) !== stableStringify(hist.present)) setHist({ past: [...hist.past, hist.present].slice(-HISTORY), present: block, future: [] });53  }54  const present = hist.present;55  const [draft, setDraft] = useState<Diagram | null>(null);56  const shown = draft ?? present;57  const layout = useMemo(() => layoutDiagram(shown), [shown]);58  const boxes = useMemo(() => boxesOf(layout), [layout]);59  const [message, setMessage] = useState<Message | null>(null);60  const info = (text: string) => setMessage({ kind: "info", text });6162  const commit = useCallback((next: Diagram): boolean => {63    setDraft(null);64    if (next === present) return false;65    const v = validate(next);66    if (!v.ok) { setMessage({ kind: "error", text: fill(t.errInvalid, { issue: v.issue }) }); return false; }67    setMessage(null);68    setHist((h) => ({ past: [...h.past, h.present].slice(-HISTORY), present: v.block, future: [] }));69    onChange(v.block);70    return true;71  }, [present, onChange, t]);72  const apply = useCallback((op: (b: Diagram) => Diagram): boolean => commit(op(present)), [commit, present]);7374  const undo = () => {75    const prev = hist.past[hist.past.length - 1];76    if (!prev) return;77    setDraft(null); setMessage(null);78    setHist({ past: hist.past.slice(0, -1), present: prev, future: [present, ...hist.future] });79    onChange(prev);80  };81  const redo = () => {82    const next = hist.future[0];83    if (!next) return;84    setDraft(null); setMessage(null);85    setHist({ past: [...hist.past, present], present: next, future: hist.future.slice(1) });86    onChange(next);87  };8889  // ── Selection, tools, view ──90  const [rawSelection, setSelection] = useState<Selection>(EMPTY_SELECTION);91  const selection = useMemo(() => pruneSelection(shown, rawSelection), [shown, rawSelection]);92  const [tool, setTool] = useState<Exclude<Tool, "step">>("select");93  const [multi, setMulti] = useState(false);94  const [snapOn, setSnapOn] = useState(true);95  const [view, setView] = useState<View>({ k: 1, x: 0, y: 0 });96  const [size, setSize] = useState({ width: 0, height: 0 });97  const [drawer, setDrawer] = useState<null | "layers" | "right">(null);98  const [rightTab, setRightTab] = useState<"props" | "steps">("props");99  const [showKeys, setShowKeys] = useState(false);100  const [stepRaw, setStepIndex] = useState<number | null>(null);101  const [pickingRaw, setPicking] = useState(false);102103  const steps = stepsOf(shown);104  const stepIndex = stepRaw !== null && stepRaw < steps.length ? stepRaw : null;105  const picking = pickingRaw && stepIndex !== null;106  const activeTool: Tool = picking ? "step" : tool;107  const highlight = stepIndex !== null ? { nodes: steps[stepIndex].nodes, edges: steps[stepIndex].edges } : undefined;108  const chooseTool = (next: Exclude<Tool, "step">) => { setTool(next); setPicking(false); };109110  const fitted = useRef(false);111  useEffect(() => {112    if (fitted.current || size.width === 0 || size.height === 0) return;113    fitted.current = true;114    setView(fitView(layout.viewBox, size));115  }, [size, layout]);116  const onSize = useCallback((s: { width: number; height: number }) => setSize((old) => (old.width === s.width && old.height === s.height ? old : s)), []);117  const zoomBy = (factor: number) => setView((v) => zoomAt(v, factor, size.width / 2, size.height / 2));118  const fit = () => setView(fitView(layout.viewBox, size));119120  // ── Commands ──121  const selectedNodes = present.nodes.filter((n) => selection.nodes.includes(n.id));122  const allLocked = selectedNodes.length > 0 && selectedNodes.every((n) => n.locked);123  const canAdd = present.nodes.length < LIMITS.nodes;124125  const addNodeAtCentre = () => {126    if (!canAdd) { info(t.errLimitNodes); return; }127    const c = size.width > 0 ? toWorld(view, size.width / 2, size.height / 2) : { x: layout.viewBox.x + layout.viewBox.width / 2, y: layout.viewBox.y + layout.viewBox.height / 2 };128    const next = addNode(present, snapOn ? { x: snap(c.x, GRID), y: snap(c.y, GRID) } : c, t.newNode);129    if (commit(next)) setSelection(addedIds(present, next));130  };131  const duplicate = () => {132    if (selection.nodes.length === 0) return;133    const next = duplicateSelection(present, selection, boxes);134    if (next === present) { info(t.errLimitNodes); return; }135    if (commit(next)) setSelection(addedIds(present, next));136  };137  const remove = () => {138    if (selectionSize(selection) === 0) return;139    const next = deleteSelection(present, selection);140    if (next === present) { info(allLocked ? t.errLocked : t.errLastNode); return; }141    const kept = commit(next) && selectedNodes.some((n) => n.locked);142    if (kept) info(t.errLocked);143  };144  const connectNodes = (from: string, to: string) => {145    const issue = connectIssue(present, from, to);146    if (issue === "self") { info(t.errSelf); return; }147    if (issue === "duplicate") { info(t.errDuplicate); return; }148    if (issue === "limit") { info(t.errLimitEdges); return; }149    if (issue) return;150    const next = connect(present, from, to);151    if (commit(next)) setSelection(addedIds(present, next));152  };153  const toggleGroup = () => {154    if (selectedNodes.length === 0) return;155    const first = selectedNodes[0].group;156    if (first && selectedNodes.every((n) => n.group === first)) { apply((b) => assignGroup(b, selection.nodes, null)); return; }157    if (present.groups.length >= LIMITS.groups) { info(t.errLimitGroups); return; }158    apply((b) => createGroup(b, selection.nodes, `${t.groupDefault} ${b.groups.length + 1}`));159  };160  const toggleLock = () => { if (selectedNodes.length > 0) apply((b) => setLocked(b, selection.nodes, !allLocked)); };161  const autoPlace = () => apply((b) => resetLayout(b, selection.nodes));162  const move = (dx: number, dy: number) => {163    if (selection.nodes.length === 0) return;164    if (allLocked) { info(t.errLocked); return; }165    apply((b) => nudge(b, selection.nodes, dx, dy, boxes));166  };167168  // ── Keyboard (never while typing in a field) ──169  const onKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {170    if (e.target instanceof Element && e.target.closest("input, textarea, select, [contenteditable='true']")) return;171    const mod = e.metaKey || e.ctrlKey, key = e.key.length === 1 ? e.key.toLowerCase() : e.key;172    let handled = true;173    if (mod && key === "z") { if (e.shiftKey) redo(); else undo(); }174    else if (mod && key === "y") redo();175    else if (mod && key === "d") duplicate();176    else if (mod && key === "a") setSelection(selectAll(present));177    else if (mod || e.altKey) handled = false;178    else if (key === "Delete" || key === "Backspace") remove();179    else if (key === "Escape") {180      if (selectionSize(selection) === 0 && !showKeys && !picking && drawer === null) handled = false;181      else { setSelection(EMPTY_SELECTION); setShowKeys(false); setPicking(false); setDrawer(null); }182    }183    else if (key === "ArrowLeft" || key === "ArrowRight" || key === "ArrowUp" || key === "ArrowDown") {184      if (selection.nodes.length === 0) handled = false;185      else { const d = e.shiftKey ? 1 : GRID; move(key === "ArrowLeft" ? -d : key === "ArrowRight" ? d : 0, key === "ArrowUp" ? -d : key === "ArrowDown" ? d : 0); }186    }187    else if (key === "+" || key === "=") zoomBy(1.25);188    else if (key === "-" || key === "_") zoomBy(0.8);189    else if (key === "0") fit();190    else if (key === "v") chooseTool("select");191    else if (key === "h") chooseTool("pan");192    else if (key === "c") chooseTool("connect");193    else if (key === "g") toggleGroup();194    else handled = false;195    if (handled) { e.preventDefault(); e.stopPropagation(); }196  };197198  const openRight = (tab: "props" | "steps") => {199    if (drawer === "right" && rightTab === tab) { setDrawer(null); return; }200    setRightTab(tab); setDrawer("right");201  };202  const hasSelection = selectionSize(selection) > 0;203  const tools: ReactNode = (204    <>205      <IconButton glyph="select" label={t.toolSelect} pressed={activeTool === "select"} onClick={() => chooseTool("select")} />206      <IconButton glyph="pan" label={t.toolPan} pressed={activeTool === "pan"} onClick={() => chooseTool("pan")} />207      <IconButton glyph="connect" label={t.toolConnect} pressed={activeTool === "connect"} onClick={() => chooseTool("connect")} />208      <IconButton glyph="multi" label={t.multi} pressed={multi} onClick={() => setMulti(!multi)} />209    </>210  );211  const edits: ReactNode = (212    <>213      <IconButton glyph="plus" label={t.addNode} disabled={!canAdd} onClick={addNodeAtCentre} />214      <IconButton glyph="trash" label={t.delete} disabled={!hasSelection} onClick={remove} />215      <IconButton glyph="undo" label={t.undo} disabled={hist.past.length === 0} onClick={undo} />216      <IconButton glyph="redo" label={t.redo} disabled={hist.future.length === 0} onClick={redo} />217    </>218  );219  const keys: [string, string][] = [220    ["V", t.kSelect], ["H", t.kPan], ["C", t.kConnect], ["G", t.kGroup], ["Suppr / ⌫", t.kDelete], ["⌘/Ctrl + D", t.duplicate],221    ["⌘/Ctrl + Z", t.undo], ["⇧ + ⌘/Ctrl + Z", t.redo], ["⌘/Ctrl + A", t.selectAll], [t.kArrows, t.kNudge], ["+ / −", t.kZoom], ["0", t.kFit], ["Esc", t.kEscape],222  ];223224  return (225    <div className="flex h-full min-h-[420px] w-full flex-col overflow-hidden bg-surface text-ink" data-diagram-editor="" role="region" aria-label={t.editor} onKeyDown={onKeyDown}>226      <div role="toolbar" aria-label={t.toolbar} className="flex shrink-0 items-center gap-0.5 overflow-x-auto border-b border-line px-2 py-1.5">227        <div className="hidden md:contents">{tools}<Sep /></div>228        <IconButton glyph="grid" label={t.snap} pressed={snapOn} onClick={() => setSnapOn(!snapOn)} />229        <Sep />230        <div className="hidden md:contents">{edits}</div>231        <IconButton glyph="duplicate" label={`${t.duplicate} (⌘/Ctrl + D)`} disabled={selection.nodes.length === 0} onClick={duplicate} />232        <Sep />233        <IconButton glyph="group" label={`${t.kGroup} (G)`} disabled={selectedNodes.length === 0} onClick={toggleGroup} />234        <IconButton glyph={allLocked ? "unlock" : "lock"} label={allLocked ? t.unlock : t.lock} disabled={selectedNodes.length === 0} onClick={toggleLock} />235        <IconButton glyph="auto" label={selection.nodes.length ? t.autoPlace : t.autoPlaceAll} disabled={!present.nodes.some((n) => n.x !== undefined && !n.locked)} onClick={autoPlace} />236        <Sep />237        <IconButton glyph="minus" label={t.zoomOut} onClick={() => zoomBy(0.8)} />238        <button type="button" className="btn btn-ghost btn-sm min-h-11 shrink-0 px-2 tabular-nums md:min-h-9" aria-label={`${t.actual} — ${Math.round(view.k * 100)} %`} title={t.actual} onClick={() => setView((v) => actualSize(v, size))}>{Math.round(view.k * 100)} %</button>239        <IconButton glyph="plus" label={t.zoomIn} onClick={() => zoomBy(1.25)} />240        <div className="hidden md:contents"><IconButton glyph="fit" label={t.fit} onClick={fit} /></div>241        <span className="flex-1" />242        <IconButton glyph="keyboard" label={t.shortcuts} pressed={showKeys} onClick={() => setShowKeys(!showKeys)} />243      </div>244245      {message ? (246        <div role={message.kind === "error" ? "alert" : "status"} className="flex shrink-0 items-center justify-between gap-2 border-b border-line px-3 py-1 text-sm"247          style={{ color: message.kind === "error" ? "var(--ui-bad)" : "var(--ui-ink)", background: "var(--ui-raised)" }}>248          <span>{message.text}</span>249          <IconButton glyph="close" label={t.close} onClick={() => setMessage(null)} />250        </div>251      ) : null}252      {picking ? <p role="status" className="shrink-0 border-b border-line px-3 py-1.5 text-sm text-muted">{t.stepPickOn}</p> : null}253254      <div className="relative min-h-0 flex-1 md:grid md:grid-cols-[minmax(200px,260px)_minmax(0,1fr)_minmax(260px,320px)] md:grid-rows-[minmax(0,1fr)]">255        <aside aria-label={t.layers} className={`${drawer === "layers" ? "flex" : "hidden"} ${DRAWER} md:border-r`}>256          <div className="flex shrink-0 items-center justify-between border-b border-line px-3 py-1">257            <h2 className="py-2 text-sm font-semibold">{t.layers}</h2>258            <div className="md:hidden"><IconButton glyph="close" label={t.close} onClick={() => setDrawer(null)} /></div>259          </div>260          <LayersPanel t={t} block={present} selection={selection} multi={multi} onSelect={setSelection} apply={apply} />261        </aside>262263        <div className="absolute inset-0 min-h-0 min-w-0 md:relative md:inset-auto">264          <Canvas block={present} layout={layout} theme={theme} view={view} onView={setView} onSize={onSize} tool={activeTool} multi={multi} snap={snapOn}265            selection={selection} onSelect={setSelection} onDraft={setDraft} onCommit={commit} onConnect={connectNodes}266            onStepToggle={(kind, id) => { if (stepIndex !== null) apply((b) => toggleStepItem(b, stepIndex, kind, id)); }}267            onLockedMove={() => info(t.errLocked)} highlight={highlight} label={present.title ? `${t.canvas} — ${present.title}` : t.canvas} hint={t.canvasHint} />268          {showKeys ? (269            <div className="card absolute right-2 top-2 z-30 max-h-[calc(100%-1rem)] w-72 max-w-[calc(100%-1rem)] overflow-y-auto p-3 shadow-xl" role="dialog" aria-label={t.shortcuts}>270              <div className="mb-1 flex items-center justify-between"><h2 className="text-sm font-semibold">{t.shortcuts}</h2><IconButton glyph="close" label={t.close} onClick={() => setShowKeys(false)} /></div>271              <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1.5 text-sm">272                {keys.map(([k, text]) => <div key={k} className="contents"><dt><kbd className="rounded border border-line bg-raised px-1.5 py-0.5 text-xs">{k}</kbd></dt><dd className="text-muted">{text}</dd></div>)}273              </dl>274            </div>275          ) : null}276        </div>277278        <aside aria-label={rightTab === "props" ? t.properties : t.steps} className={`${drawer === "right" ? "flex" : "hidden"} ${DRAWER} md:border-l`}>279          <div className="flex shrink-0 items-center gap-1 border-b border-line px-2 py-1">280            <button type="button" className="btn btn-ghost btn-sm min-h-11 md:min-h-9" aria-pressed={rightTab === "props"} style={rightTab === "props" ? { background: "var(--ui-raised)" } : undefined} onClick={() => setRightTab("props")}>{t.properties}</button>281            <button type="button" className="btn btn-ghost btn-sm min-h-11 md:min-h-9" aria-pressed={rightTab === "steps"} style={rightTab === "steps" ? { background: "var(--ui-raised)" } : undefined} onClick={() => setRightTab("steps")}>{t.steps}{steps.length ? ` (${steps.length})` : ""}</button>282            <span className="flex-1" />283            <div className="md:hidden"><IconButton glyph="close" label={t.close} onClick={() => setDrawer(null)} /></div>284          </div>285          {rightTab === "props" ? (286            <PropertiesPanel t={t} locale={locale} block={present} boxes={boxes} selection={selection} apply={apply} onDuplicate={duplicate} onDelete={remove} onConnect={connectNodes} />287          ) : (288            <StepsPanel t={t} block={present} apply={apply} index={stepIndex} onIndex={setStepIndex} picking={picking} onPicking={(on) => { setPicking(on); if (on) setDrawer(null); }} />289          )}290        </aside>291      </div>292293      <div className="safe-b shrink-0 border-t border-line px-2 pt-1 md:hidden" role="toolbar" aria-label={t.toolbar}>294        <div className="flex items-center justify-between">295          {tools}296          <IconButton large glyph="layers" label={t.layers} pressed={drawer === "layers"} onClick={() => setDrawer(drawer === "layers" ? null : "layers")} />297          <IconButton large glyph="sliders" label={t.properties} pressed={drawer === "right" && rightTab === "props"} onClick={() => openRight("props")} />298          <IconButton large glyph="steps" label={t.steps} pressed={drawer === "right" && rightTab === "steps"} onClick={() => openRight("steps")} />299        </div>300        <div className="flex items-center justify-around">301          {edits}302          <IconButton large glyph="fit" label={t.fit} onClick={fit} />303        </div>304      </div>305    </div>306  );307}308
Files main
Menu

Theme