SPB Git

Repository Public

ops.ts 31.4 KB 521 lines typescript

1/**2 * Diagram editor — pure operations. Every function takes a diagram block (plus plain arguments) and returns a new3 * block, or the same reference when there is nothing to do or the operation is refused. No React, no DOM.4 *5 * Geometry comes from the real layout engine: callers pass `boxesOf(layoutDiagram(block))`, so "where a node is"6 * always means "where the reader sees it", whether the node is placed by hand or by the engine.7 */8import { BlockSchema, newId, type BlockOf, type Icon, type Tone } from "@/schema";9import type { DiagramLayout, Pt, Rect } from "@/renderer/diagram/layout";1011export type Diagram = BlockOf<"diagram">;12export type DNode = Diagram["nodes"][number];13export type DEdge = Diagram["edges"][number];14export type DGroup = Diagram["groups"][number];15export type DLegend = Diagram["legend"][number];16export type DStep = NonNullable<Diagram["animation"]>["steps"][number];17export type Port = DEdge["fromPort"];1819export interface Selection { nodes: string[]; edges: string[] }20export const EMPTY_SELECTION: Selection = { nodes: [], edges: [] };2122/** Maxima of the schema (src/schema/sheet.ts), enforced by the operations and shown by the interface. */23export const LIMITS = {24  nodes: 60, edges: 120, groups: 12, legend: 8, steps: 20,25  label: 80, sublabel: 120, edgeLabel: 80, groupLabel: 80, title: 200, caption: 400, alt: 600,26  legendLabel: 200, stepTitle: 200, stepText: 600, coord: 20000,27} as const;28export const GRID = 8;2930/** Centre and size of a node as drawn. */31export interface Box { x: number; y: number; width: number; height: number }32export type Boxes = ReadonlyMap<string, Box>;33export const boxesOf = (layout: Pick<DiagramLayout, "nodes">): Boxes =>34  new Map(layout.nodes.map((n) => [n.id, { x: n.x, y: n.y, width: n.width, height: n.height }]));3536// ── Helpers ─────────────────────────────────────────────────────────────────────────────────────────3738const r1 = (n: number): number => Math.round(n * 10) / 10;39const coord = (n: number): number => Math.max(-LIMITS.coord, Math.min(LIMITS.coord, r1(n)));4041/** Drops keys whose value is undefined: the schema is strict and stored documents never carry empty keys. */42function compact<T extends object>(o: T): T {43  const out = { ...o };44  for (const k of Object.keys(out) as (keyof T)[]) if (out[k] === undefined) delete out[k];45  return out;46}47/** Optional text: trimmed, cut to the schema maximum, undefined when empty. */48export const optText = (s: string | undefined, max: number): string | undefined => { const v = (s ?? "").trim().slice(0, max); return v === "" ? undefined : v; };4950export const snap = (v: number, grid: number = GRID): number => (grid > 0 ? Math.round(v / grid) * grid : v);5152/** A fresh id that no node, edge or group of the block uses. */53export function freshId(block: Diagram, prefix: "n" | "e" | "g", extra: Iterable<string> = [], make: (prefix: string) => string = newId): string {54  const taken = new Set<string>([...block.nodes.map((n) => n.id), ...block.edges.map((e) => e.id), ...block.groups.map((g) => g.id), ...extra]);55  for (let i = 0; i < 1000; i++) { const id = make(prefix); if (!taken.has(id)) return id; }56  let k = taken.size; while (taken.has(`${prefix}-${k}`)) k++;57  return `${prefix}-${k}`;58}5960export type Validation = { ok: true; block: Diagram } | { ok: false; issue: string };61/** Schema check of a candidate block; the editor never emits a block that fails it. */62export function validate(block: Diagram): Validation {63  const r = BlockSchema.safeParse(block);64  if (r.success && r.data.type === "diagram") return { ok: true, block: r.data };65  if (r.success) return { ok: false, issue: "type: not a diagram" };66  const first = r.error.issues[0];67  return { ok: false, issue: first ? `${first.path.join(".")}${first.path.length ? ": " : ""}${first.message}` : "invalid block" };68}6970/** Position of a node: its manual x/y, otherwise where the layout engine put it. */71export function positionOf(node: DNode, boxes: Boxes): Pt | null {72  if (node.x !== undefined && node.y !== undefined) return { x: node.x, y: node.y };73  const b = boxes.get(node.id);74  return b ? { x: b.x, y: b.y } : null;75}76const mapNodes = (block: Diagram, f: (n: DNode) => DNode): Diagram => {77  let changed = false;78  const nodes = block.nodes.map((n) => { const m = f(n); if (m !== n) changed = true; return m; });79  return changed ? { ...block, nodes } : block;80};81const placeAt = (n: DNode, x: number, y: number): DNode => { const nx = coord(x), ny = coord(y); return n.x === nx && n.y === ny ? n : { ...n, x: nx, y: ny }; };8283/** Steps only reference nodes and edges that exist; an animation left with fewer than two steps is removed. */84export function cleanAnimation(block: Diagram): Diagram {85  if (!block.animation) return block;86  const nodes = new Set(block.nodes.map((n) => n.id)), edges = new Set(block.edges.map((e) => e.id));87  let changed = false;88  const steps = block.animation.steps.map((s) => {89    const sn = s.nodes.filter((id) => nodes.has(id)), se = s.edges.filter((id) => edges.has(id));90    if (sn.length === s.nodes.length && se.length === s.edges.length) return s;91    changed = true;92    return { ...s, nodes: sn, edges: se };93  });94  if (steps.length < 2) { const { animation: _gone, ...rest } = block; void _gone; return rest as Diagram; }95  return changed ? { ...block, animation: { steps } } : block;96}9798// ── Selection ───────────────────────────────────────────────────────────────────────────────────────99100export const selectionSize = (sel: Selection): number => sel.nodes.length + sel.edges.length;101export const isSelected = (sel: Selection, kind: "nodes" | "edges", id: string): boolean => sel[kind].includes(id);102103/** Plain click: exactly this item. Additive (shift-click, multi-select mode): toggles it in the selection. */104export function toggleSelect(sel: Selection, kind: "nodes" | "edges", id: string, additive: boolean): Selection {105  if (!additive) return kind === "nodes" ? { nodes: [id], edges: [] } : { nodes: [], edges: [id] };106  const list = sel[kind].includes(id) ? sel[kind].filter((x) => x !== id) : [...sel[kind], id];107  return { ...sel, [kind]: list };108}109export const selectAll = (block: Diagram): Selection => ({ nodes: block.nodes.map((n) => n.id), edges: block.edges.map((e) => e.id) });110export function mergeSelection(a: Selection, b: Selection): Selection {111  return { nodes: [...new Set([...a.nodes, ...b.nodes])], edges: [...new Set([...a.edges, ...b.edges])] };112}113/** Removes ids that no longer exist (after undo, delete, or a change coming from the host). */114export function pruneSelection(block: Diagram, sel: Selection): Selection {115  const nodes = new Set(block.nodes.map((n) => n.id)), edges = new Set(block.edges.map((e) => e.id));116  const sn = sel.nodes.filter((id) => nodes.has(id)), se = sel.edges.filter((id) => edges.has(id));117  return sn.length === sel.nodes.length && se.length === sel.edges.length ? sel : { nodes: sn, edges: se };118}119/** Ids present in `next` and not in `prev`: what an add / duplicate just created. */120export function addedIds(prev: Diagram, next: Diagram): Selection {121  const pn = new Set(prev.nodes.map((n) => n.id)), pe = new Set(prev.edges.map((e) => e.id));122  return { nodes: next.nodes.filter((n) => !pn.has(n.id)).map((n) => n.id), edges: next.edges.filter((e) => !pe.has(e.id)).map((e) => e.id) };123}124125const normRect = (r: Rect): Rect => ({ x: Math.min(r.x, r.x + r.width), y: Math.min(r.y, r.y + r.height), width: Math.abs(r.width), height: Math.abs(r.height) });126/** Marquee: nodes the rectangle touches, edges it fully contains. */127export function selectInRect(layout: Pick<DiagramLayout, "nodes" | "edges">, rect: Rect): Selection {128  const r = normRect(rect);129  const inside = (p: Pt) => p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height;130  return {131    nodes: layout.nodes.filter((n) => n.left < r.x + r.width && r.x < n.left + n.width && n.top < r.y + r.height && r.y < n.top + n.height).map((n) => n.id),132    edges: layout.edges.filter((e) => e.points.length > 0 && e.points.every(inside)).map((e) => e.id),133  };134}135136function distToSegment(p: Pt, a: Pt, b: Pt): number {137  const dx = b.x - a.x, dy = b.y - a.y, len = dx * dx + dy * dy;138  const t = len === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / len));139  return Math.hypot(p.x - (a.x + dx * t), p.y - (a.y + dy * t));140}141export type Hit = { kind: "nodes" | "edges"; id: string };142/**143 * What is under a point (diagram units). Nodes win over edges and the last painted node wins. `minSize` widens small144 * nodes and `tolerance` widens edges, so touch targets reach 44 px whatever the zoom.145 */146export function hitTest(layout: Pick<DiagramLayout, "nodes" | "edges">, p: Pt, opts: { tolerance?: number; minSize?: number } = {}): Hit | null {147  const tol = opts.tolerance ?? 6, min = opts.minSize ?? 0;148  for (let i = layout.nodes.length - 1; i >= 0; i--) {149    const n = layout.nodes[i], hw = Math.max(n.width, min) / 2, hh = Math.max(n.height, min) / 2;150    if (Math.abs(p.x - n.x) <= hw && Math.abs(p.y - n.y) <= hh) return { kind: "nodes", id: n.id };151  }152  let best: { id: string; d: number } | null = null;153  for (const e of layout.edges) {154    let d = Infinity;155    if (e.label && p.x >= e.label.x && p.x <= e.label.x + e.label.width && p.y >= e.label.y && p.y <= e.label.y + e.label.height) d = 0;156    for (let i = 1; i < e.points.length && d > 0; i++) d = Math.min(d, distToSegment(p, e.points[i - 1], e.points[i]));157    if (d <= tol && (!best || d < best.d)) best = { id: e.id, d };158  }159  return best ? { kind: "edges", id: best.id } : null;160}161162// ── Move, nudge, snap, automatic placement ──────────────────────────────────────────────────────────163164/**165 * Moves the given nodes together by (dx, dy). A node placed by the engine becomes manually placed, starting from its166 * computed position, so nothing jumps. With `grid`, the first moved node lands on the grid and the others keep their167 * offset to it. Locked nodes stay where they are.168 */169export function moveNodes(block: Diagram, ids: readonly string[], dx: number, dy: number, boxes: Boxes, grid = 0): Diagram {170  const set = new Set(ids);171  const movable = block.nodes.filter((n) => set.has(n.id) && !n.locked && positionOf(n, boxes));172  if (movable.length === 0) return block;173  let ddx = dx, ddy = dy;174  if (grid > 0) {175    const anchor = positionOf(movable[0], boxes)!;176    ddx = snap(anchor.x + dx, grid) - anchor.x; ddy = snap(anchor.y + dy, grid) - anchor.y;177  }178  if (ddx === 0 && ddy === 0) return block;179  const moving = new Set(movable.map((n) => n.id));180  return mapNodes(block, (n) => { if (!moving.has(n.id)) return n; const p = positionOf(n, boxes)!; return placeAt(n, p.x + ddx, p.y + ddy); });181}182/** Keyboard move: 8 px, or 1 px with Shift. */183export const nudge = (block: Diagram, ids: readonly string[], dx: number, dy: number, boxes: Boxes): Diagram => moveNodes(block, ids, dx, dy, boxes, 0);184185/** Sets one coordinate (or both) of a node from the property panel; the other one comes from its current position. */186export function setNodePosition(block: Diagram, id: string, at: { x?: number; y?: number }, boxes: Boxes): Diagram {187  return mapNodes(block, (n) => {188    if (n.id !== id || n.locked) return n;189    const p = positionOf(n, boxes);190    const x = at.x ?? p?.x, y = at.y ?? p?.y;191    if (x === undefined || y === undefined || !Number.isFinite(x) || !Number.isFinite(y)) return n;192    return placeAt(n, x, y);193  });194}195196/** "Replacer automatiquement": clears x/y on the given nodes (all nodes when `ids` is omitted or empty). Locked nodes keep their place. */197export function resetLayout(block: Diagram, ids?: readonly string[]): Diagram {198  const set = ids && ids.length ? new Set(ids) : null;199  return mapNodes(block, (n) => {200    if ((set && !set.has(n.id)) || n.locked || (n.x === undefined && n.y === undefined)) return n;201    const { x: _x, y: _y, ...rest } = n; void _x; void _y;202    return rest;203  });204}205206// ── Align and distribute ────────────────────────────────────────────────────────────────────────────207208export type AlignMode = "left" | "center" | "right" | "top" | "middle" | "bottom";209interface Item { node: DNode; x: number; y: number; width: number; height: number }210function itemsOf(block: Diagram, ids: readonly string[], boxes: Boxes): Item[] {211  const set = new Set(ids), out: Item[] = [];212  for (const node of block.nodes) {213    if (!set.has(node.id)) continue;214    const p = positionOf(node, boxes), b = boxes.get(node.id);215    if (p && b) out.push({ node, x: p.x, y: p.y, width: b.width, height: b.height });216  }217  return out;218}219const applyPositions = (block: Diagram, target: Map<string, Pt>): Diagram =>220  mapNodes(block, (n) => { const p = target.get(n.id); return p && !n.locked ? placeAt(n, p.x, p.y) : n; });221222/** Aligns the selected nodes on an edge or the centre of their common bounding box (needs two nodes or more). */223export function align(block: Diagram, ids: readonly string[], mode: AlignMode, boxes: Boxes): Diagram {224  const items = itemsOf(block, ids, boxes);225  if (items.length < 2) return block;226  const left = Math.min(...items.map((i) => i.x - i.width / 2)), right = Math.max(...items.map((i) => i.x + i.width / 2));227  const top = Math.min(...items.map((i) => i.y - i.height / 2)), bottom = Math.max(...items.map((i) => i.y + i.height / 2));228  const target = new Map<string, Pt>();229  for (const i of items) {230    switch (mode) {231      case "left": target.set(i.node.id, { x: left + i.width / 2, y: i.y }); break;232      case "center": target.set(i.node.id, { x: (left + right) / 2, y: i.y }); break;233      case "right": target.set(i.node.id, { x: right - i.width / 2, y: i.y }); break;234      case "top": target.set(i.node.id, { x: i.x, y: top + i.height / 2 }); break;235      case "middle": target.set(i.node.id, { x: i.x, y: (top + bottom) / 2 }); break;236      case "bottom": target.set(i.node.id, { x: i.x, y: bottom - i.height / 2 }); break;237    }238  }239  return applyPositions(block, target);240}241242/** Equal gaps between the selected nodes along one axis; the two outermost nodes stay in place (needs three or more). */243export function distribute(block: Diagram, ids: readonly string[], axis: "horizontal" | "vertical", boxes: Boxes): Diagram {244  const h = axis === "horizontal";245  const items = itemsOf(block, ids, boxes).sort((a, b) => (h ? a.x - b.x : a.y - b.y));246  if (items.length < 3) return block;247  const size = (i: Item) => (h ? i.width : i.height), centre = (i: Item) => (h ? i.x : i.y);248  const first = items[0], last = items[items.length - 1];249  const start = centre(first) + size(first) / 2, end = centre(last) - size(last) / 2;250  const inner = items.slice(1, -1);251  const gap = (end - start - inner.reduce((s, i) => s + size(i), 0)) / (items.length - 1);252  const target = new Map<string, Pt>();253  let cursor = start + gap;254  for (const i of inner) {255    const c = cursor + size(i) / 2;256    target.set(i.node.id, h ? { x: c, y: i.y } : { x: i.x, y: c });257    cursor += size(i) + gap;258  }259  return applyPositions(block, target);260}261262// ── Create, duplicate, delete, connect ──────────────────────────────────────────────────────────────263264/** Adds a node at a manual position. Refused (same block) at the schema limit. */265export function addNode(block: Diagram, at: Pt, label: string, id: string = freshId(block, "n")): Diagram {266  if (block.nodes.length >= LIMITS.nodes || block.nodes.some((n) => n.id === id)) return block;267  // Never exactly on top of another node: step diagonally until the spot is free.268  let x = coord(at.x), y = coord(at.y);269  while (block.nodes.some((n) => n.x === x && n.y === y)) { x = coord(x + GRID * 3); y = coord(y + GRID * 3); if (x >= LIMITS.coord || y >= LIMITS.coord) break; }270  const node: DNode = { id, label: label.trim().slice(0, LIMITS.label) || "…", shape: "round", tone: "neutral", x, y };271  return { ...block, nodes: [...block.nodes, node] };272}273274/**275 * Copies the selected nodes (new ids, shifted by `offset`, unlocked) and the edges that join two copied nodes.276 * Refused when the copies would exceed the node limit; edges are copied as long as there is room.277 */278export function duplicateSelection(block: Diagram, sel: Selection, boxes: Boxes, opts: { offset?: number; makeId?: (prefix: string) => string } = {}): Diagram {279  const offset = opts.offset ?? GRID * 3;280  const set = new Set(sel.nodes);281  const sources = block.nodes.filter((n) => set.has(n.id));282  if (sources.length === 0 || block.nodes.length + sources.length > LIMITS.nodes) return block;283  const used: string[] = [], idMap = new Map<string, string>();284  for (const n of sources) { const id = freshId(block, "n", used, opts.makeId); used.push(id); idMap.set(n.id, id); }285  const copies: DNode[] = sources.map((n) => {286    const p = positionOf(n, boxes);287    const { locked: _locked, x: _x, y: _y, ...rest } = n; void _locked; void _x; void _y;288    return p ? { ...rest, id: idMap.get(n.id)!, x: coord(p.x + offset), y: coord(p.y + offset) } : { ...rest, id: idMap.get(n.id)! };289  });290  const edges: DEdge[] = [];291  for (const e of block.edges) {292    if (block.edges.length + edges.length >= LIMITS.edges) break;293    const from = idMap.get(e.from), to = idMap.get(e.to);294    if (!from || !to) continue;295    const id = freshId(block, "e", used, opts.makeId); used.push(id);296    edges.push({ ...e, id, from, to });297  }298  return { ...block, nodes: [...block.nodes, ...copies], edges: [...block.edges, ...edges] };299}300301/**302 * Deletes the selected edges and the selected unlocked nodes, with every edge attached to a deleted node; animation303 * steps are cleaned. A diagram keeps at least one node: deleting them all is refused (same block).304 */305export function deleteSelection(block: Diagram, sel: Selection): Diagram {306  const selNodes = new Set(sel.nodes), selEdges = new Set(sel.edges);307  const gone = new Set(block.nodes.filter((n) => selNodes.has(n.id) && !n.locked).map((n) => n.id));308  const nodes = block.nodes.filter((n) => !gone.has(n.id));309  const edges = block.edges.filter((e) => !selEdges.has(e.id) && !gone.has(e.from) && !gone.has(e.to));310  if (nodes.length === 0) return block;311  if (nodes.length === block.nodes.length && edges.length === block.edges.length) return block;312  return cleanAnimation({ ...block, nodes, edges });313}314315export type ConnectIssue = "self" | "duplicate" | "unknown" | "limit";316/** Why an edge from → to cannot be created, or null when it can. */317export function connectIssue(block: Diagram, from: string, to: string): ConnectIssue | null {318  if (from === to) return "self";319  if (!block.nodes.some((n) => n.id === from) || !block.nodes.some((n) => n.id === to)) return "unknown";320  if (block.edges.some((e) => e.from === from && e.to === to)) return "duplicate";321  if (block.edges.length >= LIMITS.edges) return "limit";322  return null;323}324/** Creates an edge. Self-loops, duplicates of an existing from → to edge and unknown endpoints are refused (same block). */325export function connect(block: Diagram, from: string, to: string, id: string = freshId(block, "e")): Diagram {326  if (connectIssue(block, from, to) || block.edges.some((e) => e.id === id)) return block;327  const edge: DEdge = { id, from, to, style: "solid", arrow: "end", tone: "neutral", fromPort: "auto", toPort: "auto" };328  return { ...block, edges: [...block.edges, edge] };329}330331// ── Properties ──────────────────────────────────────────────────────────────────────────────────────332333export interface NodePatch { label?: string; sublabel?: string | null; shape?: DNode["shape"]; tone?: Tone; icon?: Icon | null; group?: string | null }334/** Edits a node. `null` removes an optional field; an empty label is ignored (the schema requires one). */335export function updateNode(block: Diagram, id: string, patch: NodePatch): Diagram {336  const groups = new Set(block.groups.map((g) => g.id));337  return mapNodes(block, (n) => {338    if (n.id !== id) return n;339    const next = { ...n };340    if (patch.label !== undefined) { const v = optText(patch.label, LIMITS.label); if (v) next.label = v; }341    if (patch.sublabel !== undefined) next.sublabel = optText(patch.sublabel ?? "", LIMITS.sublabel);342    if (patch.shape !== undefined) next.shape = patch.shape;343    if (patch.tone !== undefined) next.tone = patch.tone;344    if (patch.icon !== undefined) next.icon = patch.icon ?? undefined;345    if (patch.group !== undefined) next.group = patch.group !== null && groups.has(patch.group) ? patch.group : undefined;346    return compact(next);347  });348}349350export interface EdgePatch { label?: string | null; style?: DEdge["style"]; arrow?: DEdge["arrow"]; tone?: Tone; fromPort?: Port; toPort?: Port }351export function updateEdge(block: Diagram, id: string, patch: EdgePatch): Diagram {352  if (!block.edges.some((e) => e.id === id)) return block;353  return { ...block, edges: block.edges.map((e) => {354    if (e.id !== id) return e;355    const { label, ...rest } = patch;356    const next = { ...e, ...compact(rest) };357    if (label !== undefined) next.label = optText(label ?? "", LIMITS.edgeLabel);358    return compact(next);359  }) };360}361/** Swaps the two ends of an edge, ports included. */362export function reverseEdge(block: Diagram, id: string): Diagram {363  if (!block.edges.some((e) => e.id === id)) return block;364  return { ...block, edges: block.edges.map((e) => (e.id === id ? { ...e, from: e.to, to: e.from, fromPort: e.toPort, toPort: e.fromPort } : e)) };365}366367export interface DiagramPatch { kind?: Diagram["kind"]; direction?: Diagram["direction"]; routing?: Diagram["routing"]; title?: string | null; caption?: string | null; alt?: string | null }368export function updateDiagram(block: Diagram, patch: DiagramPatch): Diagram {369  const next = { ...block };370  if (patch.kind !== undefined) next.kind = patch.kind;371  if (patch.direction !== undefined) next.direction = patch.direction;372  if (patch.routing !== undefined) next.routing = patch.routing;373  if (patch.title !== undefined) next.title = optText(patch.title ?? "", LIMITS.title);374  if (patch.caption !== undefined) next.caption = optText(patch.caption ?? "", LIMITS.caption);375  if (patch.alt !== undefined) next.alt = optText(patch.alt ?? "", LIMITS.alt);376  return compact(next);377}378379export function setLocked(block: Diagram, ids: readonly string[], locked: boolean): Diagram {380  const set = new Set(ids);381  return mapNodes(block, (n) => {382    if (!set.has(n.id) || (n.locked === true) === locked) return n;383    if (locked) return { ...n, locked: true };384    const { locked: _l, ...rest } = n; void _l;385    return rest;386  });387}388389/** Layers: array order is paint order. Moves a node or an edge by `delta` places (clamped). */390export function reorder(block: Diagram, kind: "nodes" | "edges", id: string, delta: number): Diagram {391  const move = <T extends { id: string }>(list: T[]): T[] | null => {392    const i = list.findIndex((x) => x.id === id);393    if (i < 0) return null;394    const j = Math.max(0, Math.min(list.length - 1, i + delta));395    if (j === i) return null;396    const out = [...list]; const [item] = out.splice(i, 1); out.splice(j, 0, item);397    return out;398  };399  if (kind === "nodes") { const nodes = move(block.nodes); return nodes ? { ...block, nodes } : block; }400  const edges = move(block.edges);401  return edges ? { ...block, edges } : block;402}403404// ── Groups ──────────────────────────────────────────────────────────────────────────────────────────405406/** Creates a group and puts the given nodes in it. Refused at the limit of groups. */407export function createGroup(block: Diagram, ids: readonly string[], label: string, tone: Tone = "neutral", id: string = freshId(block, "g")): Diagram {408  if (block.groups.length >= LIMITS.groups || block.groups.some((g) => g.id === id)) return block;409  const set = new Set(ids);410  const group: DGroup = { id, label: label.trim().slice(0, LIMITS.groupLabel), tone };411  return { ...block, groups: [...block.groups, group], nodes: block.nodes.map((n) => (set.has(n.id) ? { ...n, group: id } : n)) };412}413/** Puts nodes in an existing group, or takes them out of their group with `null`. */414export function assignGroup(block: Diagram, ids: readonly string[], groupId: string | null): Diagram {415  if (groupId !== null && !block.groups.some((g) => g.id === groupId)) return block;416  const set = new Set(ids);417  return mapNodes(block, (n) => {418    if (!set.has(n.id) || n.group === (groupId ?? undefined)) return n;419    if (groupId !== null) return { ...n, group: groupId };420    const { group: _g, ...rest } = n; void _g;421    return rest;422  });423}424export function updateGroup(block: Diagram, id: string, patch: { label?: string; tone?: Tone }): Diagram {425  if (!block.groups.some((g) => g.id === id)) return block;426  return { ...block, groups: block.groups.map((g) => (g.id === id ? { ...g, ...(patch.label !== undefined ? { label: patch.label.trim().slice(0, LIMITS.groupLabel) } : {}), ...(patch.tone ? { tone: patch.tone } : {}) } : g)) };427}428/** Deletes a group; nodes still in it are taken out so the block stays valid. */429export function deleteGroup(block: Diagram, id: string): Diagram {430  if (!block.groups.some((g) => g.id === id)) return block;431  const members = block.nodes.filter((n) => n.group === id).map((n) => n.id);432  const without = assignGroup(block, members, null);433  return { ...without, groups: without.groups.filter((g) => g.id !== id) };434}435export const groupMembers = (block: Diagram, id: string): number => block.nodes.filter((n) => n.group === id).length;436437// ── Legend ──────────────────────────────────────────────────────────────────────────────────────────438439export function addLegendEntry(block: Diagram, label: string, tone: Tone = "neutral", shape: DLegend["shape"] = "square"): Diagram {440  const text = optText(label, LIMITS.legendLabel);441  if (!text || block.legend.length >= LIMITS.legend) return block;442  return { ...block, legend: [...block.legend, { label: text, tone, shape }] };443}444export function updateLegendEntry(block: Diagram, index: number, patch: { label?: string; tone?: Tone; shape?: DLegend["shape"] }): Diagram {445  const entry = block.legend[index];446  if (!entry) return block;447  const label = patch.label !== undefined ? optText(patch.label, LIMITS.legendLabel) ?? entry.label : entry.label;448  return { ...block, legend: block.legend.map((l, i) => (i === index ? { label, tone: patch.tone ?? l.tone, shape: patch.shape ?? l.shape } : l)) };449}450export function removeLegendEntry(block: Diagram, index: number): Diagram {451  return block.legend[index] ? { ...block, legend: block.legend.filter((_, i) => i !== index) } : block;452}453454// ── Animation steps ─────────────────────────────────────────────────────────────────────────────────455456export const stepsOf = (block: Diagram): DStep[] => block.animation?.steps ?? [];457458/**459 * Adds a step at the end. The schema needs at least two steps, so the first "add" on a diagram without animation460 * creates two. `titleFor(n)` names step number n (1-based).461 */462export function addStep(block: Diagram, titleFor: (n: number) => string): Diagram {463  const steps = stepsOf(block);464  if (steps.length >= LIMITS.steps) return block;465  const make = (n: number): DStep => ({ title: titleFor(n).trim().slice(0, LIMITS.stepTitle) || String(n), nodes: [], edges: [] });466  const next = steps.length === 0 ? [make(1), make(2)] : [...steps, make(steps.length + 1)];467  return { ...block, animation: { steps: next } };468}469/** Removes a step; when fewer than two would remain, the whole animation goes. */470export function removeStep(block: Diagram, index: number): Diagram {471  const steps = stepsOf(block);472  if (!steps[index]) return block;473  return cleanAnimation({ ...block, animation: { steps: steps.filter((_, i) => i !== index) } });474}475export function moveStep(block: Diagram, index: number, delta: number): Diagram {476  const steps = stepsOf(block);477  const j = Math.max(0, Math.min(steps.length - 1, index + delta));478  if (!steps[index] || j === index) return block;479  const out = [...steps]; const [s] = out.splice(index, 1); out.splice(j, 0, s);480  return { ...block, animation: { steps: out } };481}482export function updateStep(block: Diagram, index: number, patch: { title?: string; text?: string | null }): Diagram {483  const steps = stepsOf(block);484  if (!steps[index]) return block;485  return { ...block, animation: { steps: steps.map((s, i) => {486    if (i !== index) return s;487    const next = { ...s };488    if (patch.title !== undefined) { const v = optText(patch.title, LIMITS.stepTitle); if (v) next.title = v; }489    if (patch.text !== undefined) next.text = optText(patch.text ?? "", LIMITS.stepText);490    return compact(next);491  }) } };492}493/** Step mode: toggles whether a node or an edge is highlighted by a step. */494export function toggleStepItem(block: Diagram, index: number, kind: "nodes" | "edges", id: string): Diagram {495  const steps = stepsOf(block);496  const exists = kind === "nodes" ? block.nodes.some((n) => n.id === id) : block.edges.some((e) => e.id === id);497  if (!steps[index] || !exists) return block;498  return { ...block, animation: { steps: steps.map((s, i) => (i === index ? { ...s, [kind]: s[kind].includes(id) ? s[kind].filter((x) => x !== id) : [...s[kind], id] } : s)) } };499}500501// ── View (pan / zoom) ───────────────────────────────────────────────────────────────────────────────502503/** screen = view.x + world · view.k */504export interface View { k: number; x: number; y: number }505export const MIN_ZOOM = 0.2, MAX_ZOOM = 4;506export const clampZoom = (k: number): number => Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, k));507export const toWorld = (view: View, sx: number, sy: number): Pt => ({ x: (sx - view.x) / view.k, y: (sy - view.y) / view.k });508/** Zooms by `factor` keeping the screen point (sx, sy) on the same diagram point. */509export function zoomAt(view: View, factor: number, sx: number, sy: number): View {510  const k = clampZoom(view.k * factor), w = toWorld(view, sx, sy);511  return { k, x: sx - w.x * k, y: sy - w.y * k };512}513/** Whole diagram visible and centred, never enlarged beyond `maxK`. */514export function fitView(box: Rect, size: { width: number; height: number }, pad = 24, maxK = 1.5): View {515  if (size.width <= 0 || size.height <= 0 || box.width <= 0 || box.height <= 0) return { k: 1, x: 0, y: 0 };516  const k = clampZoom(Math.min((size.width - pad * 2) / box.width, (size.height - pad * 2) / box.height, maxK));517  return { k, x: (size.width - box.width * k) / 2 - box.x * k, y: (size.height - box.height * k) / 2 - box.y * k };518}519/** 100 %, keeping the centre of the screen where it is. */520export const actualSize = (view: View, size: { width: number; height: number }): View => zoomAt(view, 1 / view.k, size.width / 2, size.height / 2);521
Files main
Menu

Theme