SPB Git

Repository Public

layout.ts 12.8 KB 206 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : src/lib/canvas/layout.ts9 * Description      : automatic layout of a canvas — a size-aware grid and a10 *                    deterministic, seeded force-directed layout (repulsion11 *                    between cards, springs along edges). Line-for-line port of12 *                    SPNotesCore `CanvasLayout.swift`: same generator13 *                    (SplitMix64), same order of floating-point operations,14 *                    same rounding (half away from zero, 1/100 unit), so the15 *                    same canvas + seed gives the same positions on the web and16 *                    on the native apps (fixtures:17 *                    tests/fixtures/canvas/layout-*.json). Pure.18 * Module           : lib19 * Repository       : https://git.spboucher.ai/note-spboucher-ai20 * Project Website  : https://note.spboucher.ai21 * Created          : 2026-11-1922 * Last Modified    : 2026-11-1923 *24 * Author           : Simon-Pierre Boucher25 * Position         : Professor of Finance26 * Institution      : Université du Québec en Outaouais (UQO)27 * Organization     : SP Boucher28 * Website          : https://spboucher.ai29 * Git              : https://git.spboucher.ai30 *31 * Preferred Contact: contact@spboucher.ai32 * Development      : dev@spboucher.ai33 * Support          : support@spboucher.ai34 * Security/Admin   : admin@spboucher.ai35 *36 * Copyright (c) 202637 * Simon-Pierre Boucher38 * All rights reserved where applicable. This file is governed by the39 * applicable project license, copyright notices and relevant law.40 * Existing third-party rights and notices remain unaffected.41 *42 * License          : None specified (no license file in this repository)43 *44 * Do not embed credentials, private keys, access tokens,45 * certificates or confidential personal information.46 *47 * =============================================================================48 * END OF SP BOUCHER SOURCE HEADER49 * =============================================================================50 */5152import type { CanvasData, CanvasNode } from "./format";53import type { Point } from "./core";5455const MASK = (1n << 64n) - 1n;56/** SplitMix64: the same seed gives the same sequence on every platform. */57export class LayoutRandom {58  private state: bigint;59  constructor(seed: number | bigint) { this.state = BigInt.asUintN(64, BigInt(seed)); }60  next(): bigint {61    this.state = (this.state + 0x9e3779b97f4a7c15n) & MASK;62    let z = this.state;63    z = ((z ^ (z >> 30n)) * 0xbf58476d1ce4e5b9n) & MASK;64    z = ((z ^ (z >> 27n)) * 0x94d049bb133111ebn) & MASK;65    return z ^ (z >> 31n);66  }67  /** A value in −1…1. */68  signedUnit(): number { return (Number(this.next() >> 11n) / 9007199254740992) * 2 - 1; }69}7071export interface Forces {72  /** Free space wanted between two cards. */ spacing: number;73  /** Strength of the push between cards closer than their sizes plus `spacing`. */ repulsion: number;74  /** Strength of the pull along an edge longer than its rest length. */ attraction: number;75  /** Largest move of a card in one step at temperature 1. */ maxStep: number;76}77export const DEFAULT_FORCES: Forces = { spacing: 48, repulsion: 0.5, attraction: 0.08, maxStep: 120 };7879/** Swift's `Double.rounded()`: to nearest, ties away from zero (`Math.round` sends −2.5 to −2). */80export function roundHalfAway(v: number): number { const a = Math.abs(v), f = Math.floor(a); const r = a - f >= 0.5 ? f + 1 : f; return v < 0 ? -r : r; }81const size = (n: CanvasNode): [number, number] => [Math.max(0, n.w), Math.max(0, n.h)];8283/**84 * Places the nodes on a grid, in array order, row by row. Each column is as wide as its widest card and each row as tall as its85 * tallest, so cards never overlap. `columns` undefined picks ⌈√n⌉. Sizes, edges and ids are untouched; `pinned` nodes keep their86 * position and take no cell.87 */88export function gridLayout(d: CanvasData, opts: { columns?: number; spacing?: number; origin?: Point; pinned?: ReadonlySet<string> } = {}): CanvasData {89  const pinned = opts.pinned ?? new Set<string>(); const origin = opts.origin ?? { x: 0, y: 0 }; const spacing = opts.spacing ?? 48;90  const movable: number[] = []; d.nodes.forEach((n, i) => { if (!pinned.has(n.id)) movable.push(i); });91  if (!movable.length) return d;92  const cols = Math.max(1, Math.trunc(opts.columns ?? Math.ceil(Math.sqrt(movable.length))));93  const gap = Number.isFinite(spacing) ? Math.max(0, spacing) : 0;94  const rows = Math.floor((movable.length + cols - 1) / cols);95  const colWidth = new Array<number>(cols).fill(0), rowHeight = new Array<number>(rows).fill(0);96  movable.forEach((i, n) => { const [w, h] = size(d.nodes[i]); colWidth[n % cols] = Math.max(colWidth[n % cols], w); rowHeight[Math.floor(n / cols)] = Math.max(rowHeight[Math.floor(n / cols)], h); });97  const colX = new Array<number>(cols).fill(origin.x), rowY = new Array<number>(rows).fill(origin.y);98  for (let c = 1; c < cols; c++) colX[c] = colX[c - 1] + colWidth[c - 1] + gap;99  for (let r = 1; r < rows; r++) rowY[r] = rowY[r - 1] + rowHeight[r - 1] + gap;100  const nodes = d.nodes.slice(); let changed = false;101  movable.forEach((i, n) => { const x = colX[n % cols], y = rowY[Math.floor(n / cols)]; if (nodes[i].x !== x || nodes[i].y !== y) { nodes[i] = { ...nodes[i], x, y }; changed = true; } });102  return changed ? { ...d, nodes } : d;103}104105/**106 * One step of the force-directed layout: every movable card is pushed away from the cards it is too close to (closer than the sum of107 * their half-diagonals plus `spacing`) and pulled along its edges (longer than that rest length), then moved by at most108 * `maxStep × temperature`. Cards at the same centre are separated in a direction drawn from `random`. Positions are rounded to 1/100.109 */110export function layoutStep(d: CanvasData, temperature: number, forces: Forces, pinned: ReadonlySet<string>, random: LayoutRandom): CanvasData {111  const count = d.nodes.length; if (!count) return d;112  const cx = new Float64Array(count), cy = new Float64Array(count), radius = new Float64Array(count); const index = new Map<string, number>();113  d.nodes.forEach((node, i) => { const [w, h] = size(node); cx[i] = node.x + w / 2; cy[i] = node.y + h / 2; radius[i] = Math.sqrt(w * w + h * h) / 2; if (!index.has(node.id)) index.set(node.id, i); });114  const spacing = Number.isFinite(forces.spacing) ? Math.max(0, forces.spacing) : 0;115  const fx = new Float64Array(count), fy = new Float64Array(count);116  for (let i = 0; i < count; i++) for (let j = i + 1; j < count; j++) {117    let dx = cx[i] - cx[j], dy = cy[i] - cy[j]; let dist = Math.sqrt(dx * dx + dy * dy);118    if (dist < 1e-6) {119      dx = random.signedUnit(); dy = random.signedUnit();120      if (Math.abs(dx) < 1e-3 && Math.abs(dy) < 1e-3) dx = 1;121      dist = Math.sqrt(dx * dx + dy * dy); dx /= dist; dy /= dist; dist = 0;122    } else { dx /= dist; dy /= dist; }123    const rest = radius[i] + radius[j] + spacing; if (!(dist < rest)) continue;124    const push = (rest - dist) * forces.repulsion;125    fx[i] += dx * push; fy[i] += dy * push; fx[j] -= dx * push; fy[j] -= dy * push;126  }127  for (const edge of d.edges) {128    const a = index.get(edge.from), b = index.get(edge.to); if (a === undefined || b === undefined || a === b) continue;129    const dx = cx[b] - cx[a], dy = cy[b] - cy[a]; const dist = Math.sqrt(dx * dx + dy * dy); const rest = radius[a] + radius[b] + spacing;130    if (!(dist > rest && dist > 1e-6)) continue;131    const pull = (dist - rest) * forces.attraction;132    fx[a] += (dx / dist) * pull; fy[a] += (dy / dist) * pull; fx[b] -= (dx / dist) * pull; fy[b] -= (dy / dist) * pull;133  }134  const limit = Math.max(0, Number.isFinite(forces.maxStep) ? forces.maxStep : 0) * Math.min(1, Math.max(0, Number.isFinite(temperature) ? temperature : 0));135  let nodes: CanvasNode[] | null = null;136  for (let i = 0; i < count; i++) {137    const node = d.nodes[i]; if (pinned.has(node.id)) continue;138    let mx = fx[i], my = fy[i]; const m = Math.sqrt(mx * mx + my * my);139    if (!(Number.isFinite(m) && m > 0)) continue;140    if (m > limit) { mx = (mx / m) * limit; my = (my / m) * limit; }141    const nx = roundHalfAway((node.x + mx) * 100) / 100, ny = roundHalfAway((node.y + my) * 100) / 100;142    if (!Number.isFinite(nx) || !Number.isFinite(ny)) continue;143    if (nx !== node.x || ny !== node.y) { nodes ??= d.nodes.slice(); nodes[i] = { ...node, x: nx === 0 ? 0 : nx, y: ny === 0 ? 0 : ny }; }144  }145  return nodes ? { ...d, nodes } : d;146}147148/** `iterations` steps with a linearly decreasing temperature (1 → 1/n). Deterministic for a canvas, a seed and parameters. */149export function forceLayout(d: CanvasData, opts: { iterations?: number; seed?: number | bigint; forces?: Partial<Forces>; pinned?: ReadonlySet<string> } = {}): CanvasData {150  const n = Math.max(0, Math.trunc(opts.iterations ?? 200)); const forces = { ...DEFAULT_FORCES, ...(opts.forces ?? {}) }; const pinned = opts.pinned ?? new Set<string>();151  const rng = new LayoutRandom(opts.seed ?? 1); let out = d;152  for (let i = 0; i < n; i++) out = layoutStep(out, 1 - i / n, forces, pinned, rng);153  return out;154}155156/** Total area shared by pairs of cards (0 = no overlap). */157export function overlapArea(d: CanvasData): number {158  let total = 0; const ns = d.nodes;159  for (let i = 0; i < ns.length; i++) for (let j = i + 1; j < ns.length; j++) {160    const [wi, hi] = size(ns[i]), [wj, hj] = size(ns[j]);161    const w = Math.min(ns[i].x + wi, ns[j].x + wj) - Math.max(ns[i].x, ns[j].x), h = Math.min(ns[i].y + hi, ns[j].y + hj) - Math.max(ns[i].y, ns[j].y);162    if (w > 0 && h > 0) total += w * h;163  }164  return total;165}166/** What the force-directed layout minimises (see `layoutStep`). */167export function layoutEnergy(d: CanvasData, forces: Forces = DEFAULT_FORCES): number {168  const c = d.nodes.map((n) => { const [w, h] = size(n); return [n.x + w / 2, n.y + h / 2, Math.sqrt(w * w + h * h) / 2] as const; });169  let e = 0;170  for (let i = 0; i < c.length; i++) for (let j = i + 1; j < c.length; j++) { const dist = Math.hypot(c[i][0] - c[j][0], c[i][1] - c[j][1]); const rest = c[i][2] + c[j][2] + forces.spacing; if (dist < rest) e += forces.repulsion * (rest - dist) * (rest - dist); }171  const index = new Map<string, number>(); d.nodes.forEach((n, i) => { if (!index.has(n.id)) index.set(n.id, i); });172  for (const edge of d.edges) { const a = index.get(edge.from), b = index.get(edge.to); if (a === undefined || b === undefined || a === b) continue; const dist = Math.hypot(c[a][0] - c[b][0], c[a][1] - c[b][1]); const rest = c[a][2] + c[b][2] + forces.spacing; if (dist > rest) e += forces.attraction * (dist - rest) * (dist - rest); }173  return e;174}175176/**177 * "Tidy up" (web UI policy, not a format rule): a canvas with connections gets the force-directed layout (fewer iterations when it is178 * large: the step is quadratic), one without connections gets the grid. The layout is anchored: the result is translated so that the179 * top-left corner of the content stays where it was. `only` restricts the move to those nodes (the others are pinned).180 */181export function tidyLayout(d: CanvasData, opts: { seed?: number; only?: ReadonlySet<string> } = {}): CanvasData {182  if (d.nodes.length < 2) return d;183  const pinned = opts.only ? new Set(d.nodes.filter((n) => !opts.only!.has(n.id)).map((n) => n.id)) : new Set<string>();184  const before = corner(d, pinned); if (!before) return d;185  const linked = d.edges.some((e) => e.from !== e.to && !pinned.has(e.from) && !pinned.has(e.to));186  const n = d.nodes.length - pinned.size;187  let out = linked ? forceLayout(d, { iterations: n > 600 ? 60 : n > 250 ? 120 : 200, seed: opts.seed ?? 1, pinned }) : gridLayout(d, { origin: before, pinned });188  const after = corner(out, pinned);189  if (after && (after.x !== before.x || after.y !== before.y)) {190    const dx = before.x - after.x, dy = before.y - after.y;191    out = { ...out, nodes: out.nodes.map((node) => (pinned.has(node.id) ? node : { ...node, x: roundHalfAway((node.x + dx) * 100) / 100, y: roundHalfAway((node.y + dy) * 100) / 100 })) };192  }193  return out;194}195function corner(d: CanvasData, pinned: ReadonlySet<string>): Point | null {196  let x = Infinity, y = Infinity;197  for (const n of d.nodes) if (!pinned.has(n.id)) { if (n.x < x) x = n.x; if (n.y < y) y = n.y; }198  return Number.isFinite(x) ? { x, y } : null;199}200/** Positions between two layouts of the same nodes at `t` (0…1) — the frames of the "Tidy up" animation. Only x / y are interpolated. */201export function interpolateLayout(from: CanvasData, to: CanvasData, t: number): CanvasData {202  if (t >= 1) return to; if (t <= 0) return from;203  const start = new Map(from.nodes.map((n) => [n.id, n]));204  return { ...to, nodes: to.nodes.map((n) => { const a = start.get(n.id); return a && (a.x !== n.x || a.y !== n.y) ? { ...n, x: a.x + (n.x - a.x) * t, y: a.y + (n.y - a.y) * t } : n; }) };205}206
Files main
Menu

Theme