Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Note SPBoucher AI8 * File : src/lib/canvas/routing.ts9 * Description : geometry of the connections of a canvas — where an edge10 * leaves and reaches a card (anchored on the card's real11 * outline: rectangle, ellipse or diamond), the three routes12 * (straight, orthogonal elbow, curved), the arrowhead and13 * the label position. Pure: returns points and an SVG path14 * string; the same numbers feed the on-screen SVG,15 * hit-testing and the SVG / PNG export.16 * Module : lib17 * Repository : https://git.spboucher.ai/note-spboucher-ai18 * Project Website : https://note.spboucher.ai19 * Created : 2026-11-1920 * Last Modified : 2026-11-1921 *22 * Author : Simon-Pierre Boucher23 * Position : Professor of Finance24 * Institution : Université du Québec en Outaouais (UQO)25 * Organization : SP Boucher26 * Website : https://spboucher.ai27 * Git : https://git.spboucher.ai28 *29 * Preferred Contact: contact@spboucher.ai30 * Development : dev@spboucher.ai31 * Support : support@spboucher.ai32 * Security/Admin : admin@spboucher.ai33 *34 * Copyright (c) 202635 * Simon-Pierre Boucher36 * All rights reserved where applicable. This file is governed by the37 * applicable project license, copyright notices and relevant law.38 * Existing third-party rights and notices remain unaffected.39 *40 * License : None specified (no license file in this repository)41 *42 * Do not embed credentials, private keys, access tokens,43 * certificates or confidential personal information.44 *45 * =============================================================================46 * END OF SP BOUCHER SOURCE HEADER47 * =============================================================================48 */4950import type { CanvasEdge, CanvasNode } from "./format";51import { centerOf, rectOf, type Point, type Rect } from "./core";5253/** Route style. Stored in the optional edge field `route` (web extension of spn-canvas-1; absent = "straight"; unknown values draw straight). */54export type RouteStyle = "straight" | "orthogonal" | "curved";55export type Side = "top" | "right" | "bottom" | "left";56export interface Route {57 style: RouteStyle;58 /** Polyline of the route (curves are sampled) — first point on the outline of `from`, last point on the outline of `to`. */59 points: Point[];60 /** SVG path data of the route. */61 d: string;62 /** Direction of arrival at the last point, in radians (atan2 convention, y down). */63 endAngle: number;64 /** Where a label sits: the midpoint of the route by length. */65 label: Point;66}67const r2 = (n: number) => { const v = Math.round(n * 100) / 100; return v === 0 ? 0 : v; };68const P = (x: number, y: number): Point => ({ x: r2(x), y: r2(y) });69export const routeStyleOf = (e: CanvasEdge): RouteStyle => (e.route === "orthogonal" || e.route === "curved" ? e.route : "straight");70/** An edge draws an arrowhead unless its `kind` is "line" (absent or unknown kinds are arrows). */71export const hasArrow = (e: CanvasEdge) => e.kind !== "line";7273/**74 * The point where the ray from the node's centre towards `toward` crosses the node's outline. Rectangle for every kind except a75 * `shape` node with `shape: "ellipse" | "diamond"`. When `toward` is the centre itself the top-centre point is returned.76 */77export function anchorToward(n: CanvasNode, toward: Point): Point {78 const r = rectOf(n), c = centerOf(r); const dx = toward.x - c.x, dy = toward.y - c.y; const hw = r.w / 2, hh = r.h / 2;79 if (dx === 0 && dy === 0) return P(c.x, r.y);80 if (hw === 0 || hh === 0) return P(c.x, c.y);81 let t: number;82 if (n.kind === "shape" && n.shape === "ellipse") t = 1 / Math.sqrt((dx * dx) / (hw * hw) + (dy * dy) / (hh * hh));83 else if (n.kind === "shape" && n.shape === "diamond") t = 1 / (Math.abs(dx) / hw + Math.abs(dy) / hh);84 else t = Math.min(dx === 0 ? Infinity : hw / Math.abs(dx), dy === 0 ? Infinity : hh / Math.abs(dy));85 return P(c.x + dx * t, c.y + dy * t);86}87/** Midpoint of a side of the node's bounding box (also on the outline of an ellipse and of a diamond). */88export function sideAnchor(n: CanvasNode, side: Side): Point {89 const r = rectOf(n);90 return side === "top" ? P(r.x + r.w / 2, r.y) : side === "bottom" ? P(r.x + r.w / 2, r.y + r.h) : side === "left" ? P(r.x, r.y + r.h / 2) : P(r.x + r.w, r.y + r.h / 2);91}92/**93 * Sides used by the orthogonal and curved routes: the pair facing each other along the axis with the larger gap between the two94 * boxes (horizontal wins a tie). Null when the boxes overlap on both axes — the caller then draws a straight line.95 */96export function facingSides(a: Rect, b: Rect): { from: Side; to: Side } | null {97 const gapX = Math.max(b.x - (a.x + a.w), a.x - (b.x + b.w)), gapY = Math.max(b.y - (a.y + a.h), a.y - (b.y + b.h));98 if (gapX < 0 && gapY < 0) return null;99 if (gapX >= gapY) return b.x + b.w / 2 >= a.x + a.w / 2 ? { from: "right", to: "left" } : { from: "left", to: "right" };100 return b.y + b.h / 2 >= a.y + a.h / 2 ? { from: "bottom", to: "top" } : { from: "top", to: "bottom" };101}102const NORMAL: Record<Side, Point> = { top: { x: 0, y: -1 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 }, right: { x: 1, y: 0 } };103104function polylineMid(pts: readonly Point[]): Point {105 let total = 0; for (let i = 1; i < pts.length; i++) total += Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);106 let half = total / 2;107 for (let i = 1; i < pts.length; i++) {108 const seg = Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);109 if (half <= seg && seg > 0) { const t = half / seg; return P(pts[i - 1].x + (pts[i].x - pts[i - 1].x) * t, pts[i - 1].y + (pts[i].y - pts[i - 1].y) * t); }110 half -= seg;111 }112 return pts[0] ?? { x: 0, y: 0 };113}114const pathOf = (pts: readonly Point[]) => pts.map((p, i) => `${i ? "L" : "M"}${p.x} ${p.y}`).join(" ");115const angle = (a: Point, b: Point) => Math.atan2(b.y - a.y, b.x - a.x);116117/**118 * Route of an edge between two nodes.119 * - straight: from the outline of `a` towards the centre of `b` to the outline of `b` towards the centre of `a`;120 * - orthogonal: leaves and arrives at the middle of the facing sides, with one elbow half-way between them (3 segments);121 * - curved: a cubic Bézier between the same side anchors, control points pushed out along the side normals by half the distance122 * between the anchors (at least 40), sampled in 24 segments for hit-testing;123 * - a node connected to itself: a loop above its top-right corner;124 * - overlapping boxes fall back to the straight route.125 */126export function routeEdge(a: CanvasNode, b: CanvasNode, style: RouteStyle = "straight"): Route {127 if (a.id === b.id) {128 const r = rectOf(a); const x0 = r.x + r.w * 0.7, s = Math.max(24, Math.min(48, r.w * 0.3));129 const pts = [P(x0, r.y), P(x0, r.y - s), P(r.x + r.w + s, r.y - s), P(r.x + r.w + s, r.y + r.h * 0.3), P(r.x + r.w, r.y + r.h * 0.3)];130 return { style, points: pts, d: pathOf(pts), endAngle: Math.PI, label: P(r.x + r.w + s, r.y - s) };131 }132 const ra = rectOf(a), rb = rectOf(b); const sides = style === "straight" ? null : facingSides(ra, rb);133 if (!sides) {134 const p0 = anchorToward(a, centerOf(rb)), p1 = anchorToward(b, centerOf(ra)); const pts = [p0, p1];135 return { style: "straight", points: pts, d: pathOf(pts), endAngle: angle(p0, p1), label: polylineMid(pts) };136 }137 const p0 = sideAnchor(a, sides.from), p1 = sideAnchor(b, sides.to);138 if (style === "orthogonal") {139 const horizontal = sides.from === "left" || sides.from === "right";140 const pts = horizontal ? [p0, P((p0.x + p1.x) / 2, p0.y), P((p0.x + p1.x) / 2, p1.y), p1] : [p0, P(p0.x, (p0.y + p1.y) / 2), P(p1.x, (p0.y + p1.y) / 2), p1];141 return { style, points: pts, d: pathOf(pts), endAngle: angle(pts[2], pts[3]), label: polylineMid(pts) };142 }143 const reach = Math.max(40, Math.hypot(p1.x - p0.x, p1.y - p0.y) / 2); const n0 = NORMAL[sides.from], n1 = NORMAL[sides.to];144 const c0 = P(p0.x + n0.x * reach, p0.y + n0.y * reach), c1 = P(p1.x + n1.x * reach, p1.y + n1.y * reach);145 const pts: Point[] = [];146 for (let i = 0; i <= 24; i++) { const t = i / 24, u = 1 - t; pts.push(P(u * u * u * p0.x + 3 * u * u * t * c0.x + 3 * u * t * t * c1.x + t * t * t * p1.x, u * u * u * p0.y + 3 * u * u * t * c0.y + 3 * u * t * t * c1.y + t * t * t * p1.y)); }147 return { style, points: pts, d: `M${p0.x} ${p0.y} C${c0.x} ${c0.y} ${c1.x} ${c1.y} ${p1.x} ${p1.y}`, endAngle: angle(c1, p1), label: polylineMid(pts) };148}149150/** Triangle of an arrowhead whose tip is `tip`, pointing along `angleRad`. Returns the three corners (tip first). */151export function arrowHead(tip: Point, angleRad: number, size = 10): [Point, Point, Point] {152 const spread = Math.PI / 7;153 return [P(tip.x, tip.y), P(tip.x - size * Math.cos(angleRad - spread), tip.y - size * Math.sin(angleRad - spread)), P(tip.x - size * Math.cos(angleRad + spread), tip.y - size * Math.sin(angleRad + spread))];154}155