Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : src/lib/canvas/core.ts9 * Description : pure document operations of the `spn-canvas-1` canvas10 * (SPEC §3.4): tolerant reading, structural equality, ids,11 * defaults per node kind, add / update / remove, z-order,12 * geometry, hit-testing, snapping guides, group move /13 * resize, align / distribute, clone (copy / paste /14 * duplicate). Every function returns a new document and15 * never rebuilds a node or an edge from its known fields:16 * objects are spread, so the fields, node kinds and17 * top-level keys this client does not know survive a load →18 * edit → save. No DOM, no I/O — mirrored natively by19 * SPNotesCore (`Canvas.swift`); see docs/next/CANVAS.md.20 * Module : lib21 * Repository : https://git.spboucher.ai/note-spboucher-ai22 * Project Website : https://note.spboucher.ai23 * Created : 2026-11-1924 * Last Modified : 2026-11-1925 *26 * Author : Simon-Pierre Boucher27 * Position : Professor of Finance28 * Institution : Université du Québec en Outaouais (UQO)29 * Organization : SP Boucher30 * Website : https://spboucher.ai31 * Git : https://git.spboucher.ai32 *33 * Preferred Contact: contact@spboucher.ai34 * Development : dev@spboucher.ai35 * Support : support@spboucher.ai36 * Security/Admin : admin@spboucher.ai37 *38 * Copyright (c) 202639 * Simon-Pierre Boucher40 * All rights reserved where applicable. This file is governed by the41 * applicable project license, copyright notices and relevant law.42 * Existing third-party rights and notices remain unaffected.43 *44 * License : None specified (no license file in this repository)45 *46 * Do not embed credentials, private keys, access tokens,47 * certificates or confidential personal information.48 *49 * =============================================================================50 * END OF SP BOUCHER SOURCE HEADER51 * =============================================================================52 */5354import { CANVAS_FORMAT, type CanvasData, type CanvasEdge, type CanvasNode } from "./format";5556export type { CanvasData, CanvasEdge, CanvasNode };57export interface Point { x: number; y: number }58export interface Rect { x: number; y: number; w: number; h: number }59export type NodeKind = "text" | "page" | "image" | "pdf" | "link" | "drawing" | "shape" | "reference" | "math" | "table";60export type ShapeKind = "rect" | "ellipse" | "diamond";6162/* ------------------------------------------------------------------ equality, ids, reading ------------------------------------------------------------------ */6364/** Structural JSON equality: key order is irrelevant, an `undefined` value equals an absent key, `null` is a value of its own. */65export function jsonEqual(a: unknown, b: unknown): boolean {66 if (a === b) return true;67 if (typeof a !== typeof b || a === null || b === null || typeof a !== "object") return false;68 if (Array.isArray(a) !== Array.isArray(b)) return false;69 if (Array.isArray(a)) { const y = b as unknown[]; if (a.length !== y.length) return false; for (let i = 0; i < a.length; i++) if (!jsonEqual(a[i], y[i])) return false; return true; }70 const x = a as Record<string, unknown>, y = b as Record<string, unknown>;71 let n = 0;72 for (const k in x) { if (x[k] === undefined) continue; n++; if (!jsonEqual(x[k], y[k])) return false; }73 for (const k in y) if (y[k] !== undefined) n--;74 return n === 0;75}7677/** Order of strings by Unicode scalar value (what Swift's `unicodeScalars.lexicographicallyPrecedes` gives; JS `<` compares UTF-16 units). */78export function compareCodePoints(a: string, b: string): number {79 let i = 0, j = 0;80 while (i < a.length && j < b.length) {81 const x = a.codePointAt(i)!, y = b.codePointAt(j)!;82 if (x !== y) return x - y;83 i += x > 0xffff ? 2 : 1; j += y > 0xffff ? 2 : 1;84 }85 return (a.length - i) - (b.length - j);86}8788/** A fresh element id: a lower-case UUID (36 characters; the server accepts 1…64). `random` is injectable for deterministic tests. */89export function newId(random?: () => number): string {90 if (!random && typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") return crypto.randomUUID().toLowerCase();91 const r = random ?? Math.random; let s = "";92 for (let i = 0; i < 32; i++) { const v = i === 12 ? 4 : i === 16 ? 8 + Math.floor(r() * 4) : Math.floor(r() * 16); s += v.toString(16); if (i === 7 || i === 11 || i === 15 || i === 19) s += "-"; }93 return s;94}9596export const emptyCanvas = (): CanvasData => ({ format: CANVAS_FORMAT, nodes: [], edges: [], viewport: { x: 0, y: 0, zoom: 1 } });97const fin = (v: unknown): v is number => typeof v === "number" && Number.isFinite(v);9899/**100 * Tolerant reader: whatever arrives becomes a usable document without losing anything. Missing `nodes` / `edges` become `[]`, a101 * missing or invalid viewport becomes `{x:0, y:0, zoom:1}` (unknown viewport keys are kept), elements that are not objects with a102 * string id are dropped (they could not be addressed), everything else — unknown kinds, unknown fields, unknown top-level keys — is kept.103 */104export function readCanvas(input: unknown): CanvasData {105 const o = (input && typeof input === "object" && !Array.isArray(input) ? input : {}) as Record<string, unknown>;106 const ok = (e: unknown) => !!e && typeof e === "object" && typeof (e as { id?: unknown }).id === "string" && (e as { id: string }).id.length > 0;107 const vp = (o.viewport && typeof o.viewport === "object" ? o.viewport : {}) as Record<string, unknown>;108 return {109 ...o, format: CANVAS_FORMAT,110 nodes: (Array.isArray(o.nodes) ? o.nodes.filter(ok) : []) as CanvasNode[],111 edges: (Array.isArray(o.edges) ? o.edges.filter(ok) : []) as CanvasEdge[],112 viewport: { ...vp, x: fin(vp.x) ? vp.x : 0, y: fin(vp.y) ? vp.y : 0, zoom: fin(vp.zoom) && vp.zoom > 0 ? vp.zoom : 1 },113 };114}115116/* ------------------------------------------------------------------ node kinds ------------------------------------------------------------------ */117118export const NODE_KINDS: readonly NodeKind[] = ["text", "page", "image", "pdf", "link", "drawing", "shape", "reference", "math", "table"];119export const isKnownKind = (k: string): k is NodeKind => (NODE_KINDS as readonly string[]).includes(k);120export const DEFAULT_SIZE: Record<NodeKind, { w: number; h: number }> = {121 text: { w: 240, h: 120 }, page: { w: 280, h: 132 }, image: { w: 320, h: 240 }, pdf: { w: 240, h: 320 }, link: { w: 280, h: 96 },122 drawing: { w: 360, h: 240 }, shape: { w: 160, h: 120 }, reference: { w: 300, h: 120 }, math: { w: 240, h: 100 }, table: { w: 320, h: 160 },123};124export const MIN_NODE_SIZE = 24;125/** The colours a card can take — the semantic hues of the design system (measured light-theme sRGB, DESIGN-SYSTEM-NEXT §1); stored as `#rrggbb`. */126export const NODE_COLORS: readonly { name: string; hex: string }[] = [127 { name: "Ultramarine", hex: "#2f5ddb" }, { name: "Green", hex: "#008b4e" }, { name: "Amber", hex: "#d98b09" }, { name: "Red", hex: "#cc272e" }, { name: "Graphite", hex: "#535862" },128];129130/** A new node of `kind` centred on `at`, with the default size of its kind. `z` is set by `addNode`. */131export function makeNode(kind: NodeKind, at: Point, extra: Partial<CanvasNode> = {}, id: string = newId()): CanvasNode {132 const s = DEFAULT_SIZE[kind]; const w = fin(extra.w) ? extra.w : s.w, h = fin(extra.h) ? extra.h : s.h;133 return { id, kind, x: round2(at.x - w / 2), y: round2(at.y - h / 2), w, h, z: 0, ...(kind === "shape" ? { shape: "rect" } : {}), ...extra };134}135const round2 = (n: number) => { const v = Math.round(n * 100) / 100; return v === 0 ? 0 : v; };136137/* ------------------------------------------------------------------ editing ------------------------------------------------------------------ */138139export const nodeById = (d: CanvasData, id: string) => d.nodes.find((n) => n.id === id);140export const edgeById = (d: CanvasData, id: string) => d.edges.find((e) => e.id === id);141export const zOf = (n: CanvasNode) => (fin(n.z) ? n.z : 0);142const maxZ = (nodes: readonly CanvasNode[]) => nodes.reduce((m, n) => Math.max(m, zOf(n)), -Infinity);143144/** Appends a node in front of the others (its `z` is raised above the current maximum when it is not already). No-op when the id exists. */145export function addNode(d: CanvasData, node: CanvasNode): CanvasData {146 if (nodeById(d, node.id)) return d;147 const top = maxZ(d.nodes); const n = d.nodes.length && zOf(node) <= top ? { ...node, z: top + 1 } : node;148 return { ...d, nodes: [...d.nodes, n] };149}150export function addNodes(d: CanvasData, nodes: readonly CanvasNode[]): CanvasData { return nodes.reduce(addNode, d); }151/** Changes fields of one node (spread: every other field, known or not, is kept). `id` cannot be changed. A patch value of `undefined` removes the key. */152export function updateNode(d: CanvasData, id: string, patch: Partial<CanvasNode>): CanvasData {153 let hit = false;154 const nodes = d.nodes.map((n) => { if (n.id !== id) return n; hit = true; return applyPatch(n, patch); });155 return hit ? { ...d, nodes } : d;156}157function applyPatch<T extends { id: string }>(o: T, patch: Partial<T>): T {158 const out: Record<string, unknown> = { ...o };159 for (const [k, v] of Object.entries(patch)) { if (k === "id") continue; if (v === undefined) delete out[k]; else out[k] = v; }160 return out as T;161}162/** Removes nodes and every edge attached to them. */163export function removeNodes(d: CanvasData, ids: Iterable<string>): CanvasData {164 const gone = new Set(ids); if (!gone.size) return d;165 const nodes = d.nodes.filter((n) => !gone.has(n.id)); if (nodes.length === d.nodes.length) return d;166 return { ...d, nodes, edges: d.edges.filter((e) => !gone.has(e.from) && !gone.has(e.to)) };167}168/** Appends an edge. No-op when the id is used or an end is not a node of the canvas. */169export function addEdge(d: CanvasData, edge: CanvasEdge): CanvasData {170 if (edgeById(d, edge.id) || !nodeById(d, edge.from) || !nodeById(d, edge.to)) return d;171 return { ...d, edges: [...d.edges, edge] };172}173export function updateEdge(d: CanvasData, id: string, patch: Partial<CanvasEdge>): CanvasData {174 let hit = false;175 const edges = d.edges.map((e) => { if (e.id !== id) return e; hit = true; return applyPatch(e, patch); });176 return hit ? { ...d, edges } : d;177}178export function removeEdges(d: CanvasData, ids: Iterable<string>): CanvasData {179 const gone = new Set(ids); const edges = d.edges.filter((e) => !gone.has(e.id));180 return edges.length === d.edges.length ? d : { ...d, edges };181}182/** Edges whose `from` or `to` is not a node of the canvas (the server refuses them). */183export function danglingEdges(d: CanvasData): CanvasEdge[] { const ids = new Set(d.nodes.map((n) => n.id)); return d.edges.filter((e) => !ids.has(e.from) || !ids.has(e.to)); }184/** Moves a node inside the array (the order of the outline / list mode; stacking is decided by `z`, not by this order). */185export function reorderNode(d: CanvasData, id: string, toIndex: number): CanvasData {186 const from = d.nodes.findIndex((n) => n.id === id); if (from < 0) return d;187 const to = Math.max(0, Math.min(d.nodes.length - 1, Math.trunc(toIndex))); if (to === from) return d;188 const nodes = d.nodes.slice(); const [n] = nodes.splice(from, 1); nodes.splice(to, 0, n);189 return { ...d, nodes };190}191192/* ------------------------------------------------------------------ z-order ------------------------------------------------------------------ */193194/** The nodes in drawing order: ascending `z`, array order breaks ties (a missing `z` counts as 0). */195export function backToFront(d: CanvasData): CanvasNode[] {196 return d.nodes.map((n, i) => ({ n, i })).sort((a, b) => zOf(a.n) - zOf(b.n) || a.i - b.i).map((x) => x.n);197}198/** Puts the nodes in front of every other, keeping their relative order. Only the moved nodes change. */199export function bringToFront(d: CanvasData, ids: Iterable<string>): CanvasData {200 const sel = new Set(ids); const moving = backToFront(d).filter((n) => sel.has(n.id)); if (!moving.length) return d;201 const others = d.nodes.filter((n) => !sel.has(n.id)); if (!others.length) return d;202 let top = maxZ(others); const z = new Map<string, number>();203 for (const n of moving) { top += 1; z.set(n.id, top); }204 if (moving.every((n) => zOf(n) > maxZ(others)) ) return d;205 return { ...d, nodes: d.nodes.map((n) => (z.has(n.id) ? { ...n, z: z.get(n.id)! } : n)) };206}207/** Puts the nodes behind every other, keeping their relative order. */208export function sendToBack(d: CanvasData, ids: Iterable<string>): CanvasData {209 const sel = new Set(ids); const moving = backToFront(d).filter((n) => sel.has(n.id)); if (!moving.length) return d;210 const others = d.nodes.filter((n) => !sel.has(n.id)); if (!others.length) return d;211 const bottom = others.reduce((m, n) => Math.min(m, zOf(n)), Infinity);212 if (moving.every((n) => zOf(n) < bottom)) return d;213 const z = new Map<string, number>(); moving.forEach((n, i) => z.set(n.id, bottom - moving.length + i));214 return { ...d, nodes: d.nodes.map((n) => (z.has(n.id) ? { ...n, z: z.get(n.id)! } : n)) };215}216/** Renumbers `z` to 0, 1, 2… keeping the stacking order. */217export function normalizeZ(d: CanvasData): CanvasData {218 const rank = new Map(backToFront(d).map((n, i) => [n.id, i]));219 return d.nodes.every((n) => n.z === rank.get(n.id)) ? d : { ...d, nodes: d.nodes.map((n) => (n.z === rank.get(n.id) ? n : { ...n, z: rank.get(n.id)! })) };220}221/** One step up (`dir` = 1) or down (−1) in the stacking order: each selected node swaps rank with its unselected neighbour. Renumbers `z`. */222export function stepZ(d: CanvasData, ids: Iterable<string>, dir: 1 | -1): CanvasData {223 const sel = new Set(ids); const order = backToFront(d).map((n) => n.id);224 if (dir === 1) { for (let i = order.length - 2; i >= 0; i--) if (sel.has(order[i]) && !sel.has(order[i + 1])) [order[i], order[i + 1]] = [order[i + 1], order[i]]; }225 else for (let i = 1; i < order.length; i++) if (sel.has(order[i]) && !sel.has(order[i - 1])) [order[i], order[i - 1]] = [order[i - 1], order[i]];226 const rank = new Map(order.map((id, i) => [id, i]));227 if (backToFront(d).every((n, i) => rank.get(n.id) === i)) return d;228 return { ...d, nodes: d.nodes.map((n) => (n.z === rank.get(n.id) ? n : { ...n, z: rank.get(n.id)! })) };229}230231/* ------------------------------------------------------------------ geometry, hit-testing ------------------------------------------------------------------ */232233export const rectOf = (n: CanvasNode): Rect => ({ x: n.x, y: n.y, w: Math.max(0, n.w), h: Math.max(0, n.h) });234export const centerOf = (r: Rect): Point => ({ x: r.x + r.w / 2, y: r.y + r.h / 2 });235export const rectsIntersect = (a: Rect, b: Rect) => a.x <= b.x + b.w && b.x <= a.x + a.w && a.y <= b.y + b.h && b.y <= a.y + a.h;236export const rectContains = (outer: Rect, inner: Rect) => inner.x >= outer.x && inner.y >= outer.y && inner.x + inner.w <= outer.x + outer.w && inner.y + inner.h <= outer.y + outer.h;237export const rectFromPoints = (a: Point, b: Point): Rect => ({ x: Math.min(a.x, b.x), y: Math.min(a.y, b.y), w: Math.abs(a.x - b.x), h: Math.abs(a.y - b.y) });238/** Smallest rectangle around the rectangles; null for none. */239export function unionRects(rects: readonly Rect[]): Rect | null {240 if (!rects.length) return null;241 let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;242 for (const r of rects) { if (r.x < x0) x0 = r.x; if (r.y < y0) y0 = r.y; if (r.x + r.w > x1) x1 = r.x + r.w; if (r.y + r.h > y1) y1 = r.y + r.h; }243 return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };244}245/** Bounds of the whole canvas (or of the given nodes); null when empty. */246export function contentBounds(d: CanvasData, ids?: Iterable<string>): Rect | null {247 const sel = ids ? new Set(ids) : null;248 return unionRects(d.nodes.filter((n) => !sel || sel.has(n.id)).map(rectOf));249}250/** Is the point inside the node's outline? Shapes are tested against their real outline (ellipse, diamond); every other kind is its rectangle. */251export function pointInNode(n: CanvasNode, p: Point, tolerance = 0): boolean {252 const r = rectOf(n); const hw = r.w / 2 + tolerance, hh = r.h / 2 + tolerance;253 const dx = p.x - (r.x + r.w / 2), dy = p.y - (r.y + r.h / 2);254 if (Math.abs(dx) > hw || Math.abs(dy) > hh) return false;255 if (n.kind !== "shape" || hw === 0 || hh === 0) return true;256 if (n.shape === "ellipse") return (dx * dx) / (hw * hw) + (dy * dy) / (hh * hh) <= 1;257 if (n.shape === "diamond") return Math.abs(dx) / hw + Math.abs(dy) / hh <= 1;258 return true;259}260/** The front-most node under the point (highest `z`, then last in the array). */261export function nodeAt(d: CanvasData, p: Point, tolerance = 0): CanvasNode | null {262 const order = backToFront(d);263 for (let i = order.length - 1; i >= 0; i--) if (pointInNode(order[i], p, tolerance)) return order[i];264 return null;265}266/** Nodes touched by the rectangle (marquee), back to front. `contain` = only the nodes entirely inside. */267export function nodesInRect(d: CanvasData, r: Rect, contain = false): CanvasNode[] {268 return backToFront(d).filter((n) => (contain ? rectContains(r, rectOf(n)) : rectsIntersect(r, rectOf(n))));269}270/** Distance from a point to a polyline (Infinity for fewer than one point). */271export function distanceToPolyline(p: Point, pts: readonly Point[]): number {272 if (!pts.length) return Infinity; if (pts.length === 1) return Math.hypot(p.x - pts[0].x, p.y - pts[0].y);273 let best = Infinity;274 for (let i = 1; i < pts.length; i++) {275 const a = pts[i - 1], b = pts[i]; const dx = b.x - a.x, dy = b.y - a.y, l2 = dx * dx + dy * dy;276 const t = l2 === 0 ? 0 : Math.max(0, Math.min(1, ((p.x - a.x) * dx + (p.y - a.y) * dy) / l2));277 const dist = Math.hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy)); if (dist < best) best = dist;278 }279 return best;280}281282/* ------------------------------------------------------------------ move, snap, resize ------------------------------------------------------------------ */283284/** Translates the nodes by (dx, dy), rounded to 1/100 of a unit. */285export function moveNodes(d: CanvasData, ids: Iterable<string>, dx: number, dy: number): CanvasData {286 const sel = new Set(ids); if (!sel.size || (dx === 0 && dy === 0)) return d;287 return { ...d, nodes: d.nodes.map((n) => (sel.has(n.id) ? { ...n, x: round2(n.x + dx), y: round2(n.y + dy) } : n)) };288}289export interface Guide { axis: "x" | "y"; /** world coordinate of the line */ at: number; /** extent of the line on the other axis */ from: number; to: number }290export interface Snap { dx: number; dy: number; guides: Guide[] }291/**292 * Alignment snapping for a move. `moving` is the bounding box of what is dragged, already translated by the raw pointer delta;293 * `others` are the rectangles it can align with. On each axis the three lines of the box (start, centre, end) are compared with the294 * three lines of every other rectangle; the smallest correction within `threshold` wins (ties: the first rectangle, then start <295 * centre < end). Returns the correction to ADD to the delta and one guide per snapped axis spanning both rectangles.296 */297export function snapMove(moving: Rect, others: readonly Rect[], threshold: number): Snap {298 const out: Snap = { dx: 0, dy: 0, guides: [] };299 for (const axis of ["x", "y"] as const) {300 const pos = axis === "x" ? moving.x : moving.y, size = axis === "x" ? moving.w : moving.h;301 const mine = [pos, pos + size / 2, pos + size];302 let best: { delta: number; at: number; other: Rect } | null = null;303 for (const o of others) {304 const op = axis === "x" ? o.x : o.y, os = axis === "x" ? o.w : o.h;305 for (const target of [op, op + os / 2, op + os]) for (const m of mine) {306 const delta = target - m;307 if (Math.abs(delta) <= threshold && (!best || Math.abs(delta) < Math.abs(best.delta))) best = { delta, at: target, other: o };308 }309 }310 if (!best) continue;311 if (axis === "x") { out.dx = best.delta; out.guides.push({ axis, at: best.at, from: Math.min(moving.y, best.other.y), to: Math.max(moving.y + moving.h, best.other.y + best.other.h) }); }312 else { out.dy = best.delta; out.guides.push({ axis, at: best.at, from: Math.min(moving.x, best.other.x), to: Math.max(moving.x + moving.w, best.other.x + best.other.w) }); }313 }314 return out;315}316export const snapToGrid = (v: number, step: number) => (step > 0 ? Math.round(v / step) * step : v);317318export type Handle = "n" | "s" | "e" | "w" | "ne" | "nw" | "se" | "sw";319/**320 * Resizes a group: the bounding box of the nodes is dragged by `handle` by (dx, dy) and every node is scaled with it (positions and321 * sizes proportionally; a single node is simply resized). The box never gets smaller than `min` on a side and never flips.322 * `keepAspect` keeps the proportions of the box (corner handles: the larger scale wins; side handles: the other axis follows, centred).323 */324export function resizeNodes(d: CanvasData, ids: Iterable<string>, handle: Handle, dx: number, dy: number, opts: { min?: number; keepAspect?: boolean } = {}): CanvasData {325 const sel = new Set(ids); const box = contentBounds(d, sel); if (!box) return d;326 const next = resizeRect(box, handle, dx, dy, opts.min ?? MIN_NODE_SIZE, opts.keepAspect ?? false);327 if (next.x === box.x && next.y === box.y && next.w === box.w && next.h === box.h) return d;328 const sx = box.w > 0 ? next.w / box.w : 1, sy = box.h > 0 ? next.h / box.h : 1;329 return { ...d, nodes: d.nodes.map((n) => (sel.has(n.id) ? { ...n, x: round2(next.x + (n.x - box.x) * sx), y: round2(next.y + (n.y - box.y) * sy), w: round2(Math.max(0, n.w) * sx), h: round2(Math.max(0, n.h) * sy) } : n)) };330}331export function resizeRect(box: Rect, handle: Handle, dx: number, dy: number, min: number, keepAspect: boolean): Rect {332 let x0 = box.x, y0 = box.y, x1 = box.x + box.w, y1 = box.y + box.h;333 const minW = Math.min(min, box.w || min), minH = Math.min(min, box.h || min);334 if (handle.includes("w")) x0 = Math.min(x0 + dx, x1 - minW);335 if (handle.includes("e")) x1 = Math.max(x1 + dx, x0 + minW);336 if (handle.includes("n")) y0 = Math.min(y0 + dy, y1 - minH);337 if (handle.includes("s")) y1 = Math.max(y1 + dy, y0 + minH);338 if (keepAspect && box.w > 0 && box.h > 0) {339 const sx = (x1 - x0) / box.w, sy = (y1 - y0) / box.h;340 const s = handle.length === 2 ? Math.max(sx, sy) : handle === "e" || handle === "w" ? sx : sy;341 const w = box.w * s, h = box.h * s;342 if (handle.length === 2) { if (handle.includes("w")) x0 = x1 - w; else x1 = x0 + w; if (handle.includes("n")) y0 = y1 - h; else y1 = y0 + h; }343 else if (handle === "e" || handle === "w") { const cy = box.y + box.h / 2; y0 = cy - h / 2; y1 = cy + h / 2; }344 else { const cx = box.x + box.w / 2; x0 = cx - w / 2; x1 = cx + w / 2; }345 }346 return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };347}348349/* ------------------------------------------------------------------ align, distribute ------------------------------------------------------------------ */350351export type Alignment = "left" | "center" | "right" | "top" | "middle" | "bottom";352/** Aligns the nodes on an edge or the centre line of their common bounding box (needs at least two nodes). */353export function alignNodes(d: CanvasData, ids: Iterable<string>, how: Alignment): CanvasData {354 const sel = new Set(ids); const box = contentBounds(d, sel); if (!box || d.nodes.filter((n) => sel.has(n.id)).length < 2) return d;355 return { ...d, nodes: d.nodes.map((n) => {356 if (!sel.has(n.id)) return n; const w = Math.max(0, n.w), h = Math.max(0, n.h);357 const x = how === "left" ? box.x : how === "center" ? box.x + (box.w - w) / 2 : how === "right" ? box.x + box.w - w : n.x;358 const y = how === "top" ? box.y : how === "middle" ? box.y + (box.h - h) / 2 : how === "bottom" ? box.y + box.h - h : n.y;359 return x === n.x && y === n.y ? n : { ...n, x: round2(x), y: round2(y) };360 }) };361}362/** Equal gaps between the nodes along an axis; the first and the last (by position, then by array order) do not move (needs at least three). */363export function distributeNodes(d: CanvasData, ids: Iterable<string>, axis: "horizontal" | "vertical"): CanvasData {364 const sel = new Set(ids); const h = axis === "horizontal";365 const items = d.nodes.map((n, i) => ({ n, i })).filter((x) => sel.has(x.n.id)).sort((a, b) => (h ? a.n.x - b.n.x : a.n.y - b.n.y) || a.i - b.i).map((x) => x.n);366 if (items.length < 3) return d;367 const size = (n: CanvasNode) => Math.max(0, h ? n.w : n.h), pos = (n: CanvasNode) => (h ? n.x : n.y);368 const first = items[0], last = items[items.length - 1];369 const free = pos(last) + size(last) - pos(first) - items.reduce((s, n) => s + size(n), 0); const gap = free / (items.length - 1);370 const at = new Map<string, number>(); let cursor = pos(first);371 for (const n of items) { at.set(n.id, round2(cursor)); cursor += size(n) + gap; }372 at.set(last.id, pos(last));373 return { ...d, nodes: d.nodes.map((n) => { const v = at.get(n.id); return v === undefined || v === pos(n) ? n : h ? { ...n, x: v } : { ...n, y: v }; }) };374}375376/* ------------------------------------------------------------------ copy, paste, duplicate ------------------------------------------------------------------ */377378export interface Clip { nodes: CanvasNode[]; edges: CanvasEdge[] }379/** What a copy takes: the selected nodes and the edges whose two ends are selected (verbatim, unknown fields included). */380export function copyNodes(d: CanvasData, ids: Iterable<string>): Clip {381 const sel = new Set(ids);382 return { nodes: d.nodes.filter((n) => sel.has(n.id)), edges: d.edges.filter((e) => sel.has(e.from) && sel.has(e.to)) };383}384/** Pastes a clip with fresh ids, translated by `offset`, in front of everything (relative stacking kept). Returns the new document and the new node ids. */385export function pasteClip(d: CanvasData, clip: Clip, offset: Point, idgen: () => string = newId): { data: CanvasData; ids: string[] } {386 const map = new Map<string, string>(); let top = d.nodes.length ? maxZ(d.nodes) : -1;387 const order = clip.nodes.map((n, i) => ({ n, i })).sort((a, b) => zOf(a.n) - zOf(b.n) || a.i - b.i);388 const z = new Map<string, number>(); for (const { n } of order) { top += 1; z.set(n.id, top); }389 const nodes = clip.nodes.map((n) => { const id = idgen(); map.set(n.id, id); return { ...n, id, x: round2(n.x + offset.x), y: round2(n.y + offset.y), z: z.get(n.id)! }; });390 const edges = clip.edges.filter((e) => map.has(e.from) && map.has(e.to)).map((e) => ({ ...e, id: idgen(), from: map.get(e.from)!, to: map.get(e.to)! }));391 return { data: { ...d, nodes: [...d.nodes, ...nodes], edges: [...d.edges, ...edges] }, ids: nodes.map((n) => n.id) };392}393394/* ------------------------------------------------------------------ text of a node ------------------------------------------------------------------ */395396/** Cells of a `table` node. Convention (SPEC gives a table no field of its own): `text` holds a GitHub-flavoured Markdown table. */397export function parseTable(text: string | undefined | null): string[][] {398 const rows = String(text ?? "").split("\n").map((l) => l.trim()).filter((l) => l.startsWith("|"));399 const cells = rows.filter((l) => !/^\|\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?$/.test(l)).map((l) => l.replace(/^\|/, "").replace(/\|$/, "").split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|").replace(/<br\s*\/?>/gi, "\n")));400 const width = cells.reduce((m, r) => Math.max(m, r.length), 0);401 return cells.map((r) => (r.length < width ? [...r, ...Array(width - r.length).fill("")] : r));402}403export function serializeTable(cells: readonly (readonly string[])[]): string {404 if (!cells.length) return "";405 const width = cells.reduce((m, r) => Math.max(m, r.length), 1);406 const line = (r: readonly string[]) => `| ${Array.from({ length: width }, (_, i) => String(r[i] ?? "").replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>")).join(" | ")} |`;407 return [line(cells[0]), `| ${Array.from({ length: width }, () => "---").join(" | ")} |`, ...cells.slice(1).map(line)].join("\n");408}409export const emptyTable = (rows = 3, cols = 3) => serializeTable(Array.from({ length: rows }, () => Array.from({ length: cols }, () => "")));410/** One line that names the node in lists, outlines and exports (never empty). `titles` resolves page / reference ids to their titles. */411export function nodeLabel(n: CanvasNode, titles?: (id: string) => string | undefined): string {412 const first = (s: unknown) => (typeof s === "string" ? s.split("\n").map((l) => l.replace(/^[#>*\-\s]+/, "").trim()).find(Boolean) ?? "" : "");413 const text = first(n.text);414 switch (n.kind) {415 case "page": return (typeof n.pageId === "string" && titles?.(n.pageId)) || text || "Page";416 case "reference": return (typeof n.refId === "string" && titles?.(n.refId)) || text || "Reference";417 case "link": return text || (typeof n.url === "string" ? n.url : "") || "Link";418 case "math": return (typeof n.latex === "string" && n.latex.trim()) || text || "Formula";419 case "image": return text || "Image";420 case "pdf": return text || "PDF";421 case "drawing": return text || "Drawing";422 case "table": { const c = parseTable(n.text as string); return c[0]?.filter(Boolean).join(" · ") || "Table"; }423 case "shape": return text || (typeof n.shape === "string" ? n.shape[0].toUpperCase() + n.shape.slice(1) : "Shape");424 case "text": return text || "Text";425 default: return text || `Card (${n.kind})`;426 }427}428