Repository Public
1/**2 * Diagram layout engine. Pure and deterministic: the same block always gives the same geometry, on the server, in3 * the browser and in the export worker (text is measured from a table, never from the DOM).4 *5 * 1. node sizes from the measured label / sublabel / icon and the shape;6 * 2. layered placement by dagre (direction TB or LR, groups as compound clusters);7 * 3. manual x/y on a node override its computed position;8 * 4. ports and edge routing computed here, from the final positions, so edges follow manually placed nodes;9 * 5. edge labels placed along their path where they do not cover a node or another label.10 */11import { Graph, layout as dagreLayout } from "@dagrejs/dagre";12import type { BlockOf, Icon, Tone } from "@/schema";13import { NODE_SHAPES } from "@/schema";14import { plainMath } from "../mathtext";15import { blockWidth, measureText, wrapText } from "./text-measure";1617export type DiagramBlockData = Pick<BlockOf<"diagram">, "direction" | "routing" | "nodes" | "edges" | "groups">;18export type NodeShape = (typeof NODE_SHAPES)[number];19export type Side = "top" | "right" | "bottom" | "left";20export interface Pt { x: number; y: number }21export interface Rect { x: number; y: number; width: number; height: number }2223export interface NodeBox {24 id: string; shape: NodeShape; tone: Tone; icon?: Icon; manual: boolean;25 /** Centre. */26 x: number; y: number; width: number; height: number;27 /** Top-left corner (x − width/2, y − height/2). */28 left: number; top: number;29 labelLines: string[]; sublabelLines: string[];30 /** Horizontal centre of the text block and baseline of each line. */31 textX: number; labelBaselines: number[]; sublabelBaselines: number[];32 /** Top-left corner of the icon, when the node has one. */33 iconBox: { x: number; y: number; size: number } | null;34}35export interface GroupBox extends Rect { id: string; label: string; tone: Tone; labelX: number; labelY: number }36export interface EdgeLabelBox extends Rect { lines: string[]; cx: number; baselines: number[] }37export interface EdgePath {38 id: string; from: string; to: string; tone: Tone;39 style: "solid" | "dashed" | "dotted"; arrow: "end" | "both" | "none";40 /** SVG path data. */41 d: string;42 /** Points along the path, in order (used for label placement and hit-testing). */43 points: Pt[];44 fromSide: Side; toSide: Side;45 label: EdgeLabelBox | null;46}47export interface DiagramLayout {48 width: number; height: number;49 viewBox: Rect;50 direction: "TB" | "LR"; routing: "orthogonal" | "curved" | "straight";51 nodes: NodeBox[]; edges: EdgePath[]; groups: GroupBox[];52}5354export const LABEL_FONT = { size: 14, weight: 600, line: 18 } as const;55export const SUBLABEL_FONT = { size: 12, weight: 400, line: 16 } as const;56export const EDGE_FONT = { size: 12, weight: 500, line: 15 } as const;57export const GROUP_FONT = { size: 11, weight: 650 } as const;58const ICON = 20, ICON_GAP = 10, MAX_TEXT = 176, PAD_X = 16, PAD_Y = 12, MIN_W = 72, MIN_H = 44;59const GROUP_PAD = 18, GROUP_HEAD = 24, MARGIN = 16, STUB = 16, CORNER = 10;6061const r1 = (n: number): number => Math.round(n * 10) / 10;62const pt = (x: number, y: number): Pt => ({ x: r1(x), y: r1(y) });6364// ── 1. Node sizes ───────────────────────────────────────────────────────────────────────────────────6566interface Sized {67 width: number; height: number; labelLines: string[]; sublabelLines: string[];68 /** Offsets from the node centre. */69 textDx: number; textTopDy: number; icon: { dx: number; dy: number } | null;70}71const ICON_ABOVE: ReadonlySet<NodeShape> = new Set<NodeShape>(["circle", "diamond", "hexagon"]);7273function sizeNode(n: DiagramBlockData["nodes"][number]): Sized {74 const labelLines = wrapText(plainMath(n.label), MAX_TEXT, LABEL_FONT.size, { weight: LABEL_FONT.weight, maxLines: 3 });75 const sublabelLines = n.sublabel ? wrapText(plainMath(n.sublabel), MAX_TEXT, SUBLABEL_FONT.size, { weight: SUBLABEL_FONT.weight, maxLines: 3 }) : [];76 const textW = Math.max(blockWidth(labelLines, LABEL_FONT.size, LABEL_FONT.weight), blockWidth(sublabelLines, SUBLABEL_FONT.size, SUBLABEL_FONT.weight));77 const textH = labelLines.length * LABEL_FONT.line + (sublabelLines.length ? 3 + sublabelLines.length * SUBLABEL_FONT.line : 0);78 const above = ICON_ABOVE.has(n.shape);79 const hasIcon = n.icon !== undefined;80 const contentW = hasIcon && !above ? textW + ICON + ICON_GAP : Math.max(textW, hasIcon ? ICON : 0);81 const contentH = hasIcon && above ? textH + ICON + 6 : Math.max(textH, hasIcon ? ICON : 0);82 let width = contentW + PAD_X * 2, height = contentH + PAD_Y * 2;83 let shiftY = 0;84 switch (n.shape) {85 case "pill": width += height * 0.3; break;86 case "diamond": width = contentW * 1.45 + 44; height = contentH * 1.5 + 36; break;87 case "hexagon": width += Math.min(40, height * 0.5); break;88 case "cylinder": height += 16; shiftY = 6; break;89 case "circle": { const d = Math.sqrt(contentW * contentW + contentH * contentH) + 22; width = d; height = d; break; }90 case "note": width += 6; break;91 default: break;92 }93 width = Math.ceil(Math.max(width, MIN_W)); height = Math.ceil(Math.max(height, MIN_H));94 const textDx = hasIcon && !above ? (ICON + ICON_GAP) / 2 : 0;95 const textTopDy = shiftY + (hasIcon && above ? (ICON + 6) / 2 : 0) - textH / 2;96 const icon = !hasIcon ? null : above97 ? { dx: -ICON / 2, dy: shiftY - contentH / 2 }98 : { dx: -contentW / 2, dy: shiftY - ICON / 2 };99 return { width, height, labelLines, sublabelLines, textDx, textTopDy, icon };100}101102function makeBox(n: DiagramBlockData["nodes"][number], s: Sized, x: number, y: number, manual: boolean): NodeBox {103 const top = y + s.textTopDy;104 const labelBaselines = s.labelLines.map((_, i) => r1(top + i * LABEL_FONT.line + LABEL_FONT.size));105 const subTop = top + s.labelLines.length * LABEL_FONT.line + 3;106 const sublabelBaselines = s.sublabelLines.map((_, i) => r1(subTop + i * SUBLABEL_FONT.line + SUBLABEL_FONT.size - 1));107 return {108 id: n.id, shape: n.shape, tone: n.tone, icon: n.icon, manual,109 x: r1(x), y: r1(y), width: s.width, height: s.height, left: r1(x - s.width / 2), top: r1(y - s.height / 2),110 labelLines: s.labelLines, sublabelLines: s.sublabelLines,111 textX: r1(x + s.textDx), labelBaselines, sublabelBaselines,112 iconBox: s.icon ? { x: r1(x + s.icon.dx), y: r1(y + s.icon.dy), size: ICON } : null,113 };114}115116// ── 2. Placement ────────────────────────────────────────────────────────────────────────────────────117118interface Placed { positions: Map<string, Pt>; waypoints: Map<string, Pt[]> }119120/** Gaps between nodes and between ranks. The printed quick sheet uses the tight set: same text size, less air. */121const ROOMY = { node: 40, rank: 60 }, TIGHT = { node: 22, rank: 38 };122let gaps = ROOMY;123124function place(block: DiagramBlockData, sizes: Map<string, Sized>, compound: boolean): Placed {125 const g = new Graph({ compound, multigraph: true });126 g.setGraph({ rankdir: block.direction, nodesep: gaps.node, ranksep: gaps.rank, edgesep: gaps === TIGHT ? 12 : 20, marginx: 0, marginy: 0 });127 if (compound) for (const group of block.groups) g.setNode(`group:${group.id}`, {});128 for (const n of block.nodes) {129 const s = sizes.get(n.id)!;130 g.setNode(n.id, { width: s.width, height: s.height });131 if (compound && n.group) g.setParent(n.id, `group:${n.group}`);132 }133 for (const e of block.edges) {134 if (e.from === e.to) continue;135 const lines = e.label ? wrapText(plainMath(e.label), 140, EDGE_FONT.size, { weight: EDGE_FONT.weight, maxLines: 2 }) : [];136 g.setEdge(e.from, e.to, {137 width: lines.length ? blockWidth(lines, EDGE_FONT.size, EDGE_FONT.weight) + 14 : 0,138 height: lines.length ? lines.length * EDGE_FONT.line + 8 : 0, labelpos: "c", minlen: 1,139 }, e.id);140 }141 dagreLayout(g);142 const positions = new Map<string, Pt>();143 for (const n of block.nodes) { const p = g.node(n.id) as { x: number; y: number }; positions.set(n.id, { x: p.x, y: p.y }); }144 const waypoints = new Map<string, Pt[]>();145 for (const e of block.edges) {146 if (e.from === e.to) continue;147 const label = g.edge({ v: e.from, w: e.to, name: e.id }) as { points?: Pt[] } | undefined;148 if (label?.points) waypoints.set(e.id, label.points.map((p) => ({ x: p.x, y: p.y })));149 }150 return { positions, waypoints };151}152153/** Fallback when dagre cannot lay a graph out: a plain grid in document order. Never used for a valid acyclic layout. */154function placeGrid(block: DiagramBlockData, sizes: Map<string, Sized>): Placed {155 const positions = new Map<string, Pt>();156 const perLine = Math.max(1, Math.ceil(Math.sqrt(block.nodes.length)));157 const cellW = Math.max(...block.nodes.map((n) => sizes.get(n.id)!.width)) + gaps.node;158 const cellH = Math.max(...block.nodes.map((n) => sizes.get(n.id)!.height)) + gaps.rank;159 block.nodes.forEach((n, i) => {160 const a = i % perLine, b = Math.floor(i / perLine);161 positions.set(n.id, block.direction === "TB" ? { x: a * cellW + cellW / 2, y: b * cellH + cellH / 2 } : { x: b * cellW + cellW / 2, y: a * cellH + cellH / 2 });162 });163 return { positions, waypoints: new Map() };164}165166// ── 4. Ports and routing ────────────────────────────────────────────────────────────────────────────167168const NORMAL: Record<Side, Pt> = { top: { x: 0, y: -1 }, right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 } };169const isVertical = (s: Side): boolean => s === "top" || s === "bottom";170171function autoSides(a: NodeBox, b: NodeBox, direction: "TB" | "LR"): [Side, Side] {172 const below = b.top >= a.top + a.height - 1, above = b.top + b.height <= a.top + 1;173 const rightOf = b.left >= a.left + a.width - 1, leftOf = b.left + b.width <= a.left + 1;174 if (direction === "TB") {175 if (below) return ["bottom", "top"];176 if (above) return ["top", "bottom"];177 return b.x >= a.x ? ["right", "left"] : ["left", "right"];178 }179 if (rightOf) return ["right", "left"];180 if (leftOf) return ["left", "right"];181 return b.y >= a.y ? ["bottom", "top"] : ["top", "bottom"];182}183184const SPREADABLE: ReadonlySet<NodeShape> = new Set<NodeShape>(["rect", "round", "note"]);185186function sidePoint(box: NodeBox, side: Side, fraction: number): Pt {187 const f = SPREADABLE.has(box.shape) ? fraction : 0.5;188 switch (side) {189 case "top": return { x: box.left + box.width * f, y: box.top };190 case "bottom": return { x: box.left + box.width * f, y: box.top + box.height };191 case "left": return { x: box.left, y: box.top + box.height * f };192 case "right": return { x: box.left + box.width, y: box.top + box.height * f };193 }194}195196/** Where the segment from the centre of `box` towards `target` leaves the shape. */197export function boundaryPoint(box: NodeBox, target: Pt): Pt {198 const dx = target.x - box.x, dy = target.y - box.y;199 if (dx === 0 && dy === 0) return { x: box.x, y: box.y };200 const hw = box.width / 2, hh = box.height / 2;201 let k: number;202 if (box.shape === "circle") k = hw / Math.hypot(dx, dy);203 else if (box.shape === "diamond") k = 1 / (Math.abs(dx) / hw + Math.abs(dy) / hh);204 else k = Math.min(dx !== 0 ? hw / Math.abs(dx) : Infinity, dy !== 0 ? hh / Math.abs(dy) : Infinity);205 return { x: box.x + dx * k, y: box.y + dy * k };206}207208const fmt = (p: Pt): string => `${r1(p.x)} ${r1(p.y)}`;209210function dedupe(points: Pt[]): Pt[] {211 const out: Pt[] = [];212 for (const p of points) {213 const last = out[out.length - 1];214 if (last && Math.abs(last.x - p.x) < 0.05 && Math.abs(last.y - p.y) < 0.05) continue;215 out.push(p);216 }217 // Drop the middle of three collinear points.218 for (let i = out.length - 2; i > 0; i--) {219 const a = out[i - 1], b = out[i], c = out[i + 1];220 if (Math.abs((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) < 0.01) out.splice(i, 1);221 }222 return out;223}224225/** Polyline with rounded elbows. */226function roundedPath(points: Pt[], radius: number): string {227 if (points.length < 2) return "";228 let d = `M${fmt(points[0])}`;229 for (let i = 1; i < points.length - 1; i++) {230 const a = points[i - 1], b = points[i], c = points[i + 1];231 const la = Math.hypot(b.x - a.x, b.y - a.y), lc = Math.hypot(c.x - b.x, c.y - b.y);232 const r = Math.min(radius, la / 2, lc / 2);233 if (r < 0.5) { d += `L${fmt(b)}`; continue; }234 const p1 = { x: b.x + ((a.x - b.x) / la) * r, y: b.y + ((a.y - b.y) / la) * r };235 const p2 = { x: b.x + ((c.x - b.x) / lc) * r, y: b.y + ((c.y - b.y) / lc) * r };236 d += `L${fmt(p1)}Q${fmt(b)} ${fmt(p2)}`;237 }238 return d + `L${fmt(points[points.length - 1])}`;239}240241/** Orthogonal join of two points: leaves `a` along its axis, arrives at `b` along its axis. */242function orthoJoin(a: Pt, aVertical: boolean, b: Pt, bVertical: boolean): Pt[] {243 if (aVertical && bVertical) { const mid = (a.y + b.y) / 2; return [a, { x: a.x, y: mid }, { x: b.x, y: mid }, b]; }244 if (!aVertical && !bVertical) { const mid = (a.x + b.x) / 2; return [a, { x: mid, y: a.y }, { x: mid, y: b.y }, b]; }245 return aVertical ? [a, { x: a.x, y: b.y }, b] : [a, { x: b.x, y: a.y }, b];246}247248/** Cubic Hermite spline through `points` with given end tangents; returns path data and sampled points. */249function smoothPath(points: Pt[], startTangent: Pt, endTangent: Pt): { d: string; samples: Pt[] } {250 const n = points.length;251 const tangents: Pt[] = points.map((p, i) => {252 if (i === 0) return startTangent;253 if (i === n - 1) return endTangent;254 return { x: (points[i + 1].x - points[i - 1].x) / 2, y: (points[i + 1].y - points[i - 1].y) / 2 };255 });256 let d = `M${fmt(points[0])}`;257 const samples: Pt[] = [points[0]];258 for (let i = 0; i < n - 1; i++) {259 const p0 = points[i], p3 = points[i + 1];260 const c1 = { x: p0.x + tangents[i].x / 3, y: p0.y + tangents[i].y / 3 };261 const c2 = { x: p3.x - tangents[i + 1].x / 3, y: p3.y - tangents[i + 1].y / 3 };262 d += `C${fmt(c1)} ${fmt(c2)} ${fmt(p3)}`;263 for (let k = 1; k <= 12; k++) {264 const t = k / 12, u = 1 - t;265 samples.push({266 x: u * u * u * p0.x + 3 * u * u * t * c1.x + 3 * u * t * t * c2.x + t * t * t * p3.x,267 y: u * u * u * p0.y + 3 * u * u * t * c1.y + 3 * u * t * t * c2.y + t * t * t * p3.y,268 });269 }270 }271 return { d, samples };272}273274/** Point at fraction `t` of the length of a polyline. */275export function pointAlong(points: Pt[], t: number): Pt {276 if (points.length === 0) return { x: 0, y: 0 };277 let total = 0;278 for (let i = 1; i < points.length; i++) total += Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);279 let target = total * Math.max(0, Math.min(1, t));280 for (let i = 1; i < points.length; i++) {281 const seg = Math.hypot(points[i].x - points[i - 1].x, points[i].y - points[i - 1].y);282 if (target <= seg && seg > 0) { const k = target / seg; return { x: points[i - 1].x + (points[i].x - points[i - 1].x) * k, y: points[i - 1].y + (points[i].y - points[i - 1].y) * k }; }283 target -= seg;284 }285 return points[points.length - 1];286}287288export const rectsOverlap = (a: Rect, b: Rect, gap = 0): boolean =>289 a.x < b.x + b.width + gap && b.x < a.x + a.width + gap && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;290291// ── Main ────────────────────────────────────────────────────────────────────────────────────────────292293export function layoutDiagram(block: DiagramBlockData, tight = false): DiagramLayout {294 gaps = tight ? TIGHT : ROOMY;295 try { return layoutWithGaps(block); } finally { gaps = ROOMY; }296}297function layoutWithGaps(block: DiagramBlockData): DiagramLayout {298 const sizes = new Map<string, Sized>();299 for (const n of block.nodes) sizes.set(n.id, sizeNode(n));300 const groupIds = new Set(block.groups.map((g) => g.id));301 const compound = block.groups.length > 0 && block.nodes.some((n) => n.group !== undefined && groupIds.has(n.group));302303 let placed: Placed;304 try { placed = place(block, sizes, compound); }305 catch {306 try { placed = place(block, sizes, false); } catch { placed = placeGrid(block, sizes); }307 }308309 const nodes: NodeBox[] = block.nodes.map((n) => {310 const manual = n.x !== undefined && n.y !== undefined;311 const p = manual ? { x: n.x as number, y: n.y as number } : placed.positions.get(n.id) ?? { x: 0, y: 0 };312 return makeBox(n, sizes.get(n.id)!, p.x, p.y, manual);313 });314 const byId = new Map(nodes.map((n) => [n.id, n]));315316 // Groups: the box around their members (final positions), with room for the label.317 const groups: GroupBox[] = [];318 for (const group of block.groups) {319 const members = nodes.filter((n) => block.nodes.find((m) => m.id === n.id)?.group === group.id);320 if (members.length === 0) continue;321 const x0 = Math.min(...members.map((m) => m.left)) - GROUP_PAD, y0 = Math.min(...members.map((m) => m.top)) - GROUP_PAD - GROUP_HEAD;322 const x1 = Math.max(...members.map((m) => m.left + m.width)) + GROUP_PAD, y1 = Math.max(...members.map((m) => m.top + m.height)) + GROUP_PAD;323 const labelW = measureText(group.label.toUpperCase(), GROUP_FONT.size, GROUP_FONT.weight) * 1.08 + 28;324 const width = Math.max(x1 - x0, labelW);325 groups.push({ id: group.id, label: group.label, tone: group.tone, x: r1(x0), y: r1(y0), width: r1(width), height: r1(y1 - y0), labelX: r1(x0 + 14), labelY: r1(y0 + 17) });326 }327328 // Sides of every edge end, then a fraction along the side so several edges on one side do not share a point.329 interface End { edge: string; which: "from" | "to"; side: Side; other: Pt; fraction: number }330 const ends = new Map<string, End[]>();331 const sides = new Map<string, [Side, Side]>();332 for (const e of block.edges) {333 const a = byId.get(e.from), b = byId.get(e.to);334 if (!a || !b) continue;335 let pair: [Side, Side] = e.from === e.to ? ["right", "top"] : autoSides(a, b, block.direction);336 if (e.fromPort !== "auto") pair = [e.fromPort, pair[1]];337 if (e.toPort !== "auto") pair = [pair[0], e.toPort];338 sides.set(e.id, pair);339 const add = (node: string, end: End) => { const list = ends.get(node); if (list) list.push(end); else ends.set(node, [end]); };340 add(a.id, { edge: e.id, which: "from", side: pair[0], other: { x: b.x, y: b.y }, fraction: 0.5 });341 add(b.id, { edge: e.id, which: "to", side: pair[1], other: { x: a.x, y: a.y }, fraction: 0.5 });342 }343 const fractions = new Map<string, number>();344 for (const [, list] of ends) {345 for (const side of ["top", "right", "bottom", "left"] as const) {346 const onSide = list.filter((e) => e.side === side);347 onSide.sort((p, q) => (isVertical(side) ? p.other.x - q.other.x : p.other.y - q.other.y) || (p.edge < q.edge ? -1 : p.edge > q.edge ? 1 : 0));348 onSide.forEach((end, i) => fractions.set(`${end.edge}:${end.which}`, 0.5 + ((i + 1) / (onSide.length + 1) - 0.5) * 0.76));349 }350 }351352 const routes: { edge: DiagramBlockData["edges"][number]; d: string; points: Pt[]; fromSide: Side; toSide: Side }[] = [];353 for (const e of block.edges) {354 const a = byId.get(e.from), b = byId.get(e.to), pair = sides.get(e.id);355 if (!a || !b || !pair) continue;356 const [fromSide, toSide] = pair;357 if (e.from === e.to) {358 // Self-loop on the top-right corner.359 const p0 = { x: a.left + a.width, y: a.top + Math.min(14, a.height / 3) }, p1 = { x: a.left + a.width - Math.min(22, a.width / 4), y: a.top };360 const s = smoothPath([p0, p1], { x: 100, y: -40 }, { x: -40, y: 100 });361 routes.push({ edge: e, d: s.d, points: s.samples, fromSide: "right", toSide: "top" });362 continue;363 }364 const auto = e.fromPort === "auto" && e.toPort === "auto";365 const p0 = sidePoint(a, fromSide, fractions.get(`${e.id}:from`) ?? 0.5);366 const p3 = sidePoint(b, toSide, fractions.get(`${e.id}:to`) ?? 0.5);367 const n0 = NORMAL[fromSide], n1 = NORMAL[toSide];368 // dagre's intermediate points keep long edges clear of the ranks they cross; only valid for computed positions.369 const way = placed.waypoints.get(e.id);370 const inner = auto && !a.manual && !b.manual && way && way.length > 3 ? way.slice(1, -1) : [];371372 if (block.routing === "straight") {373 const start = e.fromPort === "auto" ? boundaryPoint(a, inner[0] ?? b) : p0;374 const end = e.toPort === "auto" ? boundaryPoint(b, inner[inner.length - 1] ?? a) : p3;375 const points = dedupe([start, ...inner, end]);376 routes.push({ edge: e, d: "M" + points.map(fmt).join("L"), points, fromSide, toSide });377 } else if (block.routing === "orthogonal") {378 const s0 = { x: p0.x + n0.x * STUB, y: p0.y + n0.y * STUB }, s1 = { x: p3.x + n1.x * STUB, y: p3.y + n1.y * STUB };379 const chain: { p: Pt; vertical: boolean }[] = [{ p: s0, vertical: isVertical(fromSide) }, ...inner.map((p) => ({ p, vertical: block.direction === "TB" })), { p: s1, vertical: isVertical(toSide) }];380 const poly: Pt[] = [p0];381 for (let i = 0; i < chain.length - 1; i++) poly.push(...orthoJoin(chain[i].p, chain[i].vertical, chain[i + 1].p, chain[i + 1].vertical));382 poly.push(p3);383 const points = dedupe(poly);384 routes.push({ edge: e, d: roundedPath(points, CORNER), points, fromSide, toSide });385 } else {386 const dist = Math.hypot(p3.x - p0.x, p3.y - p0.y);387 const k = Math.max(40, Math.min(220, dist * (inner.length ? 0.6 : 1.1)));388 const s = smoothPath([p0, ...inner, p3], { x: n0.x * k, y: n0.y * k }, { x: -n1.x * k, y: -n1.y * k });389 routes.push({ edge: e, d: s.d, points: s.samples, fromSide, toSide });390 }391 }392393 // Edge labels: first free spot along the path.394 const taken: Rect[] = nodes.map((n) => ({ x: n.left, y: n.top, width: n.width, height: n.height }));395 const edges: EdgePath[] = routes.map(({ edge, d, points, fromSide, toSide }) => {396 let label: EdgeLabelBox | null = null;397 if (edge.label) {398 const lines = wrapText(plainMath(edge.label), 140, EDGE_FONT.size, { weight: EDGE_FONT.weight, maxLines: 2 });399 const width = Math.ceil(blockWidth(lines, EDGE_FONT.size, EDGE_FONT.weight)) + 14, height = lines.length * EDGE_FONT.line + 7;400 let chosen: Rect | null = null;401 for (const t of [0.5, 0.42, 0.58, 0.34, 0.66, 0.26, 0.74, 0.2, 0.8]) {402 const c = pointAlong(points, t);403 const rect = { x: c.x - width / 2, y: c.y - height / 2, width, height };404 if (!taken.some((other) => rectsOverlap(rect, other, 3))) { chosen = rect; break; }405 }406 if (!chosen) { const c = pointAlong(points, 0.5); chosen = { x: c.x - width / 2, y: c.y - height / 2, width, height }; }407 taken.push(chosen);408 label = {409 x: r1(chosen.x), y: r1(chosen.y), width, height, lines, cx: r1(chosen.x + width / 2),410 baselines: lines.map((_, i) => r1(chosen.y + 3.5 + i * EDGE_FONT.line + EDGE_FONT.size - 1)),411 };412 }413 return { id: edge.id, from: edge.from, to: edge.to, tone: edge.tone, style: edge.style, arrow: edge.arrow, d, points: points.map((p) => pt(p.x, p.y)), fromSide, toSide, label };414 });415416 // Bounds.417 let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;418 const grow = (r: Rect) => { x0 = Math.min(x0, r.x); y0 = Math.min(y0, r.y); x1 = Math.max(x1, r.x + r.width); y1 = Math.max(y1, r.y + r.height); };419 for (const n of nodes) grow({ x: n.left, y: n.top, width: n.width, height: n.height });420 for (const g of groups) grow(g);421 for (const e of edges) { if (e.label) grow(e.label); for (const p of e.points) grow({ x: p.x - 4, y: p.y - 4, width: 8, height: 8 }); }422 if (!Number.isFinite(x0)) { x0 = 0; y0 = 0; x1 = 100; y1 = 60; }423 const viewBox = { x: Math.floor(x0 - MARGIN), y: Math.floor(y0 - MARGIN), width: Math.ceil(x1 - x0 + MARGIN * 2), height: Math.ceil(y1 - y0 + MARGIN * 2) };424 return { width: viewBox.width, height: viewBox.height, viewBox, direction: block.direction, routing: block.routing, nodes, edges, groups };425}426427/**428 * The layout a reader can actually read. A left-to-right diagram much wider than a column is drawn at a fraction of429 * its size (labels of 4 px); when the top-to-bottom layout of the same graph keeps a larger scale at `target` width,430 * that one is used. The author's direction wins whenever it is readable or no worse.431 */432export function layoutReadable(block: DiagramBlockData, target = 760): DiagramLayout {433 const own = layoutDiagram(block);434 const scale = (l: DiagramLayout) => Math.min(1, target / l.width);435 if (block.direction !== "LR" || scale(own) >= 0.72) return own;436 const other = layoutDiagram({ ...block, direction: "TB" });437 return scale(other) > scale(own) + 0.12 ? other : own;438}439440/**441 * How a diagram is printed on the quick sheet (PDF): which direction, and in which panel.442 * narrow one column, the drawing above its legend and steps443 * wide two columns, the drawing above, steps in two columns below (wide, flat drawings)444 * side two columns, the drawing on the left and legend, steps and caption on the right (tall drawings)445 * Every candidate is laid out with the tight gaps; the height left for the drawing is what the page leaves once the446 * text of the panel is counted. The candidate drawn at the largest scale wins; a narrow panel is preferred when it447 * is large enough (it leaves a column for the text), then the author's direction.448 * Sizes are those of the print layout in src/worker/export.ts (CSS px before the print scale).449 */450const PRINT_PAGE = 880, PRINT_NARROW = 525, PRINT_WIDE = 1100;451export interface PrintDiagramPlan { layout: DiagramLayout; wide: boolean; side: boolean; scale: number }452export function printDiagramPlan(block: DiagramBlockData & { legend?: unknown[]; animation?: { steps?: unknown[] }; caption?: string }): PrintDiagramPlan {453 const steps = block.animation?.steps?.length ?? 0, legend = block.legend?.length ?? 0;454 const head = 70 + (block.caption ? 60 : 0);455 const textNarrow = head + steps * 84 + Math.ceil(legend / 2) * 30, textWide = head + Math.ceil(steps / 2) * 62 + Math.ceil(legend / 5) * 30;456 const fit = (l: DiagramLayout, width: number, maxHeight: number) => (maxHeight < 120 ? 0 : Math.min(1, width / l.width, maxHeight / l.height));457 const own = layoutDiagram(block, true);458 const other = layoutDiagram({ ...block, direction: block.direction === "TB" ? "LR" : "TB" }, true);459 const cands: (PrintDiagramPlan & { rank: number })[] = [];460 [own, other].forEach((layout, k) => {461 cands.push({ layout, wide: false, side: false, scale: fit(layout, PRINT_NARROW, PRINT_PAGE - textNarrow), rank: k });462 cands.push({ layout, wide: true, side: false, scale: fit(layout, PRINT_WIDE, Math.min(640, PRINT_PAGE - textWide)), rank: 2 + k });463 if (steps + legend > 0) cands.push({ layout, wide: true, side: true, scale: fit(layout, PRINT_NARROW + 20, PRINT_PAGE - 60), rank: 4 + k });464 });465 const best = Math.max(...cands.map((c) => c.scale));466 const pick = cands.filter((c) => c.scale >= Math.min(best * 0.88, 0.72)).sort((x, y) => x.rank - y.rank)[0];467 return { layout: pick.layout, wide: pick.wide, side: pick.side, scale: pick.scale };468}469