@weasel-js/diagram 1.4.4 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _weasel_js_core from '@weasel-js/core';
2
- import { Path, Vec2, PoseProjection, DerivedDep, SceneRegistry, ChromeState, FillStyle, Stroke, CursorSpec, Affordance, InvocationCtx, GestureBinding, Action, Contribution, RenderLayer, SimulationNode, createSimulation, EasingFn, NodeId, Scene, NodeShapeEntry } from '@weasel-js/core';
2
+ import { Path, Vec2, PoseDescriptor, DerivedDep, SceneRegistry, ChromeState, FillStyle, Stroke, CursorSpec, Affordance, InvocationCtx, GestureBinding, Action, Contribution, RenderLayer, SimulationNode, createSimulation, EasingFn, NodeId, Scene, NodeShapeEntry } from '@weasel-js/core';
3
3
 
4
4
  /**
5
5
  * The shapes a built body can wear, as paths in the node's bounds.
@@ -11,7 +11,7 @@ import { Path, Vec2, PoseProjection, DerivedDep, SceneRegistry, ChromeState, Fil
11
11
  * kit's own `clipFromPose` factories are.
12
12
  */
13
13
 
14
- /** An axis-aligned box, in the shape `PoseProjection.getBounds` returns. */
14
+ /** An axis-aligned box, in the shape `PoseDescriptor.getBounds` returns. */
15
15
  interface Bounds {
16
16
  x: number;
17
17
  y: number;
@@ -406,7 +406,7 @@ declare const DEFAULT_PORTS: readonly PortSpec[];
406
406
  interface PortsOptions<TPose> {
407
407
  /** Reads the AABB a port is placed in, and the node's rotation. Defaults to
408
408
  * the kit's `AUTO_POSE_DESCRIPTOR`, which handles rect and path poses. */
409
- geometry?: PoseProjection<TPose>;
409
+ geometry?: PoseDescriptor<TPose>;
410
410
  /** How the `DiagramNode` trait is read off a node. */
411
411
  read?: DiagramNodeReader;
412
412
  }
@@ -589,7 +589,7 @@ interface PortAffordanceOptions<TPose> {
589
589
  /** Also the chrome-caps visibility id. Default {@link PORT_LAYER_ID}. */
590
590
  id?: string;
591
591
  read?: DiagramNodeReader;
592
- geometry?: PoseProjection<TPose>;
592
+ geometry?: PoseDescriptor<TPose>;
593
593
  /** Which participants show their ports. Default: all of them. Gate on
594
594
  * selection or hover by reading `state`. */
595
595
  shows?: (node: DiagramNodeLike, state: ChromeState) => boolean;
@@ -673,7 +673,7 @@ interface ConnectActionOptions<TPose> {
673
673
  /** Default {@link CONNECT_ACTION_ID}. */
674
674
  id?: string;
675
675
  read?: DiagramNodeReader;
676
- geometry?: PoseProjection<TPose>;
676
+ geometry?: PoseDescriptor<TPose>;
677
677
  /** Default {@link defaultCanConnect}. */
678
678
  canConnect?: CanConnect;
679
679
  /** How near the pointer must come to a port, in world units, before the
@@ -683,8 +683,6 @@ interface ConnectActionOptions<TPose> {
683
683
  * Default `'straight'`. */
684
684
  router?: string;
685
685
  routers?: Readonly<Record<string, Router>>;
686
- /** How the in-flight edge is painted. */
687
- stroke?: Stroke;
688
686
  /**
689
687
  * Mints and commits the edge. Called once, on release over a valid port.
690
688
  *
@@ -837,7 +835,7 @@ interface Graph {
837
835
  }
838
836
  interface BuildGraphOptions<TPose> {
839
837
  read?: DiagramNodeReader;
840
- geometry?: PoseProjection<TPose>;
838
+ geometry?: PoseDescriptor<TPose>;
841
839
  }
842
840
  /**
843
841
  * Read a graph out of a source of scene nodes.
@@ -875,7 +873,7 @@ declare function diagramLabelOf(node: {
875
873
  data: unknown;
876
874
  }): DiagramLabel | null;
877
875
  interface LabelPoseOptions<TPose> {
878
- geometry?: PoseProjection<TPose>;
876
+ geometry?: PoseDescriptor<TPose>;
879
877
  }
880
878
  /**
881
879
  * A `derivePose` that stations a label along its dependency's path.
@@ -1084,7 +1082,7 @@ interface LiveLayoutFrame {
1084
1082
  }
1085
1083
  type LiveLayoutProducer<TPose> = (ctx: LiveLayoutCtx<TPose>) => LiveLayoutFrame;
1086
1084
  interface ForceProducerOptions<TPose> extends ForceOptions {
1087
- geometry?: PoseProjection<TPose>;
1085
+ geometry?: PoseDescriptor<TPose>;
1088
1086
  /** Alpha held while something is pinned, so the graph keeps answering a drag
1089
1087
  * instead of freezing under it. Default 0.3. */
1090
1088
  dragAlpha?: number;
@@ -1131,7 +1129,7 @@ interface UseLiveLayoutOptions<TPose> {
1131
1129
  frames?: number;
1132
1130
  easing?: EasingFn;
1133
1131
  read?: DiagramNodeReader;
1134
- geometry?: PoseProjection<TPose>;
1132
+ geometry?: PoseDescriptor<TPose>;
1135
1133
  /** The undo entry's name. Default `'Layout'`. */
1136
1134
  label?: string;
1137
1135
  /** Fires once the run has settled or been stopped and its poses are in the
@@ -1204,7 +1202,7 @@ declare const layered: LayoutFn;
1204
1202
  /** The layouts this package ships. A consumer's own go in the same shape. */
1205
1203
  declare const LAYOUTS: Readonly<Record<string, LayoutFn>>;
1206
1204
  interface ApplyLayoutOptions<TPose> {
1207
- geometry?: PoseProjection<TPose>;
1205
+ geometry?: PoseDescriptor<TPose>;
1208
1206
  /** The undo entry's name. Default `'Layout'`. */
1209
1207
  label?: string;
1210
1208
  }
@@ -1232,7 +1230,7 @@ declare function applyLayout<TPose>(scene: Scene<unknown, string, TPose>, result
1232
1230
  * translation is measured from the node's document pose, which a run in flight
1233
1231
  * never changes, so a frame's answer does not depend on the frame before it.
1234
1232
  */
1235
- declare function layoutPoses<TPose>(scene: Scene<unknown, string, TPose>, result: LayoutResult, geometry?: PoseProjection<TPose>): Map<string, TPose>;
1233
+ declare function layoutPoses<TPose>(scene: Scene<unknown, string, TPose>, result: LayoutResult, geometry?: PoseDescriptor<TPose>): Map<string, TPose>;
1236
1234
  /** The default action id. */
1237
1235
  declare const LAYOUT_ACTION_ID = "diagram.layout";
1238
1236
  interface LayoutActionOptions<TPose> {
@@ -1249,7 +1247,7 @@ interface LayoutActionOptions<TPose> {
1249
1247
  algorithm?: string | LayoutFn;
1250
1248
  layout?: LayoutOptions;
1251
1249
  read?: DiagramNodeReader;
1252
- geometry?: PoseProjection<TPose>;
1250
+ geometry?: PoseDescriptor<TPose>;
1253
1251
  }
1254
1252
  /**
1255
1253
  * `diagram.layout` — rebuild the graph, run a layout, write the result.
@@ -1388,7 +1386,7 @@ interface DiagramShapeOptions<TPose> {
1388
1386
  /** How the trait is read. Default: the node's own `data.diagram`. */
1389
1387
  read?: DiagramNodeReader;
1390
1388
  /** Reads the box the outline is built in. Default `RECT_POSE_DESCRIPTOR`. */
1391
- geometry?: PoseProjection<TPose>;
1389
+ geometry?: PoseDescriptor<TPose>;
1392
1390
  /** Painted when the node's data declares neither. */
1393
1391
  defaultFill?: FillStyle | null;
1394
1392
  defaultStroke?: Stroke | null;
package/dist/index.js CHANGED
@@ -676,7 +676,6 @@ var DEFAULT_EDGE_STROKE = {
676
676
  markerEnd: "arrow"
677
677
  };
678
678
  var DEFAULT_ROUTER = "straight";
679
- var PREVIEW_STROKE = { paint: { color: "#7ba7c7" }, width: 2, dash: [4, 4] };
680
679
  function connectBinding(actionId = CONNECT_ACTION_ID) {
681
680
  return {
682
681
  spec: { kind: "drag", target: `affordance:${PORT_AFFORDANCE_KIND}` },
@@ -730,8 +729,7 @@ function createConnectAction(opts) {
730
729
  canConnect = defaultCanConnect,
731
730
  snapRadius = DEFAULT_SNAP,
732
731
  router: routerKey = DEFAULT_ROUTER,
733
- commit = commitEdgeToScene,
734
- stroke = PREVIEW_STROKE
732
+ commit = commitEdgeToScene
735
733
  } = opts;
736
734
  const routers = opts.routers ?? ROUTERS;
737
735
  const portOpts = {
@@ -787,12 +785,7 @@ function createConnectAction(opts) {
787
785
  const { end } = endAt(scratch.from, scratch.current);
788
786
  const points = route({ from: scratch.from, to: end, waypoints: [] });
789
787
  if (points.length < 2) return null;
790
- const cmd = {
791
- kind: "path",
792
- path: polylineFromPoints(points),
793
- stroke
794
- };
795
- return { kind: "commands", commands: [cmd], space: "world" };
788
+ return { kind: "polyline", points, role: "connector" };
796
789
  },
797
790
  onEnd(endCtx, reason) {
798
791
  scratch.open = false;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/outline.ts","../src/onOutline.ts","../src/trait.ts","../src/ports.ts","../src/body.ts","../src/label.ts","../src/edge.ts","../src/portAffordance.ts","../src/connect.ts","../src/portLayer.ts","../src/contribution.ts","../src/graph.ts","../src/layout.ts","../src/force.ts","../src/layered.ts","../src/tree.ts","../src/layoutAction.ts","../src/live.ts","../src/shape.ts"],"names":["left","right","top","bottom","center","AUTO_POSE_DESCRIPTOR","polylineFromPoints","push","cursor","translatePoseViaDescriptor"],"mappings":";;;;AAwBA,IAAM,IAAA,GAAO,GAAA;AAIb,IAAM,KAAA,GAAQ,kBAAA;AAIP,SAAS,WAAA,CAAY,SAAkB,MAAA,EAAsB;AAClE,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,EAAU,OAAO,OAAA;AACxC,EAAA,MAAM,EAAE,CAAA,EAAG,CAAA,EAAG,OAAO,CAAA,EAAG,MAAA,EAAQ,GAAE,GAAI,MAAA;AACtC,EAAA,IAAI,KAAK,CAAA,IAAK,CAAA,IAAK,CAAA,EAAG,OAAO,SAAS,CAAA,EAAG,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,GAAG,CAAC,CAAA,EAAG,KAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAE1E,EAAA,QAAQ,OAAA;AAAS,IACf,KAAK,MAAA;AACH,MAAA,OAAO,QAAA,CAAS,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA;AAAA,IAE5B,KAAK,SAAA;AACH,MAAA,OAAO,iBAAA,CAAkB;AAAA,QACvB,EAAE,CAAA,EAAG,CAAA,GAAI,CAAA,GAAI,GAAG,CAAA,EAAE;AAAA,QAClB,EAAE,CAAA,EAAG,CAAA,GAAI,GAAG,CAAA,EAAG,CAAA,GAAI,IAAI,CAAA,EAAE;AAAA,QACzB,EAAE,CAAA,EAAG,CAAA,GAAI,IAAI,CAAA,EAAG,CAAA,EAAG,IAAI,CAAA,EAAE;AAAA,QACzB,EAAE,CAAA,EAAG,CAAA,EAAG,CAAA,GAAI,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,SAAY,IAAA,GAAO,WAAA,CAAY,SAAS,QAAA,CAAS,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,IACrF;AAAA,GACF;AACF;AAOO,SAAS,oBAAA,CAA4B,IAAA,GAAmC,EAAC,EAAe;AAC7F,EAAA,OAAO,kBAAkB,YAAA,CAAa,IAAI,GAAG,EAAE,QAAA,EAAU,QAAQ,CAAA;AACnE","file":"index.js","sourcesContent":["/**\n * The shapes a built body can wear, as paths in the node's bounds.\n *\n * These are the flowchart vocabulary — a decision is a diamond, an I/O step a\n * parallelogram, a terminator a stadium — plus `'rect'` for everything else and\n * a `Path` escape hatch for a shape the vocabulary does not have. The path is\n * built in world coordinates from the bounds it is given, the same way the\n * kit's own `clipFromPose` factories are.\n */\nimport { PathBuilder, polygonFromPoints, rectPath, type Path } from '@weasel-js/core';\n\n/** An axis-aligned box, in the shape `PoseProjection.getBounds` returns. */\nexport interface Bounds {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A named flowchart shape, or a path a consumer built themselves. */\nexport type Outline = 'rect' | 'diamond' | 'stadium' | 'parallelogram' | Path;\n\n/** How far a parallelogram's top edge leans past its bottom one, as a\n * fraction of the box's width. The flowchart convention. */\nconst LEAN = 0.2;\n\n/** Cubic approximation of a quarter circle. A stadium's ends are two of these\n * each, which is the same construction `ellipsePath` uses. */\nconst KAPPA = 0.5522847498307936;\n\n/** The path `outline` describes inside `bounds`. A zero-area box gives a\n * zero-area rect rather than a degenerate polygon. */\nexport function outlinePath(outline: Outline, bounds: Bounds): Path {\n if (typeof outline !== 'string') return outline;\n const { x, y, width: w, height: h } = bounds;\n if (w <= 0 || h <= 0) return rectPath(x, y, Math.max(w, 0), Math.max(h, 0));\n\n switch (outline) {\n case 'rect':\n return rectPath(x, y, w, h);\n\n case 'diamond':\n return polygonFromPoints([\n { x: x + w / 2, y },\n { x: x + w, y: y + h / 2 },\n { x: x + w / 2, y: y + h },\n { x, y: y + h / 2 },\n ]);\n\n case 'parallelogram': {\n // The lean is clamped so a narrow box cannot fold through itself.\n const lean = Math.min(w * LEAN, w / 2);\n return polygonFromPoints([\n { x: x + lean, y },\n { x: x + w, y },\n { x: x + w - lean, y: y + h },\n { x, y: y + h },\n ]);\n }\n\n case 'stadium':\n return stadiumPath(x, y, w, h);\n }\n}\n\n/** A rect with semicircular ends — the Minkowski sum of a segment and a disc,\n * which puts the flat edges along the box's *longer* axis. A tall box is a\n * pill standing up, not an ellipse. */\nfunction stadiumPath(x: number, y: number, w: number, h: number): Path {\n const r = Math.min(w, h) / 2;\n const k = r * KAPPA;\n const b = new PathBuilder();\n\n if (w >= h) {\n const left = x + r;\n const right = x + w - r;\n const top = y;\n const bottom = y + h;\n const midY = y + h / 2;\n return b\n .moveTo(left, top)\n .lineTo(right, top)\n .curveTo(right + k, top, x + w, midY - k, x + w, midY)\n .curveTo(x + w, midY + k, right + k, bottom, right, bottom)\n .lineTo(left, bottom)\n .curveTo(left - k, bottom, x, midY + k, x, midY)\n .curveTo(x, midY - k, left - k, top, left, top)\n .close()\n .build();\n }\n\n const top = y + r;\n const bottom = y + h - r;\n const left = x;\n const right = x + w;\n const midX = x + w / 2;\n return b\n .moveTo(right, top)\n .lineTo(right, bottom)\n .curveTo(right, bottom + k, midX + k, y + h, midX, y + h)\n .curveTo(midX - k, y + h, left, bottom + k, left, bottom)\n .lineTo(left, top)\n .curveTo(left, top - k, midX - k, y, midX, y)\n .curveTo(midX + k, y, right, top - k, right, top)\n .close()\n .build();\n}\n\n/**\n * The largest axis-aligned box a shape's content can occupy without leaving\n * the shape. Rows lay out in here, not in the bounds — a diamond's corners and\n * a parallelogram's lean are outside its own box, and a label placed against\n * the bounding box lands there and gets clipped away by the silhouette.\n *\n * Conservative rather than exact: the inscribed rect of a rhombus is exact,\n * and a stadium reports the flat span between its rounded ends, which gives up\n * a little height near them.\n */\nexport function contentBox(outline: Outline, bounds: Bounds): Bounds {\n if (typeof outline !== 'string') return bounds;\n const { x, y, width: w, height: h } = bounds;\n switch (outline) {\n case 'rect':\n return bounds;\n case 'diamond':\n // Half the width and half the height, centered — the inscribed rect.\n return { x: x + w / 4, y: y + h / 4, width: w / 2, height: h / 2 };\n case 'parallelogram': {\n const lean = Math.min(w * LEAN, w / 2);\n return { x: x + lean, y, width: Math.max(w - lean * 2, 0), height: h };\n }\n case 'stadium': {\n const r = Math.min(w, h) / 2;\n return w >= h\n ? { x: x + r, y, width: Math.max(w - r * 2, 0), height: h }\n : { x, y: y + r, width: w, height: Math.max(h - r * 2, 0) };\n }\n }\n}\n\n/**\n * The box whose {@link contentBox} is at least `content` — the inverse, for\n * sizing a node to what its rows measured.\n *\n * The stadium case is the only inexact one: its inset depends on the height it\n * is solving for, so it assumes the wide orientation and adds one height's\n * worth of end caps.\n */\nexport function boxForContent(\n outline: Outline,\n content: { width: number; height: number },\n): { width: number; height: number } {\n if (typeof outline !== 'string') return content;\n switch (outline) {\n case 'rect':\n return content;\n case 'diamond':\n return { width: content.width * 2, height: content.height * 2 };\n case 'parallelogram':\n return { width: content.width / (1 - LEAN * 2), height: content.height };\n case 'stadium':\n return { width: content.width + content.height, height: content.height };\n }\n}\n","/**\n * Moving a port from the node's bounding box onto the shape it is drawn as.\n *\n * A port is placed as a fraction of the node's bounds, which is what makes it\n * survive a resize. For a rect that is already on the outline; for anything\n * else it can be well outside the ink — a parallelogram's west port floats in\n * the gap beside its leaning edge, and an edge that ends there ends in empty\n * space. So the point is cast back onto the outline along the ray from the\n * node's center, which is the direction an edge leaves anyway.\n */\nimport { PATH_C, PATH_L, PATH_M, PATH_Q, PATH_Z, flattenCubic, type Path } from '@weasel-js/core';\nimport { outlinePath, type Bounds, type Outline } from './outline';\nimport type { Port } from './types';\n\n/** Curve flattening tolerance, in world units. Finer than a port is wide. */\nconst TOLERANCE = 0.25;\n\n/** The outline as a closed polyline: `[x0, y0, x1, y1, …]`. */\nexport function outlinePolyline(outline: Outline, bounds: Bounds): number[] {\n const path = outlinePath(outline, bounds);\n return flattenPath(path);\n}\n\nfunction flattenPath(path: Path): number[] {\n if (path.kind === 'rect') {\n const { x, y, width: w, height: h } = path;\n return [x, y, x + w, y, x + w, y + h, x, y + h, x, y];\n }\n const out: number[] = [];\n const { commands, coords } = path as { commands: Uint8Array; coords: Float32Array };\n let ci = 0;\n let cx = 0;\n let cy = 0;\n let sx = 0;\n let sy = 0;\n for (const cmd of commands) {\n if (cmd === PATH_M) {\n cx = coords[ci]!; cy = coords[ci + 1]!; ci += 2;\n sx = cx; sy = cy;\n out.push(cx, cy);\n } else if (cmd === PATH_L) {\n cx = coords[ci]!; cy = coords[ci + 1]!; ci += 2;\n out.push(cx, cy);\n } else if (cmd === PATH_C) {\n const x1 = coords[ci]!, y1 = coords[ci + 1]!;\n const x2 = coords[ci + 2]!, y2 = coords[ci + 3]!;\n const x3 = coords[ci + 4]!, y3 = coords[ci + 5]!;\n ci += 6;\n flattenCubic(cx, cy, x1, y1, x2, y2, x3, y3, TOLERANCE, out);\n cx = x3; cy = y3;\n } else if (cmd === PATH_Q) {\n // Elevated to a cubic rather than given its own flattener.\n const qx = coords[ci]!, qy = coords[ci + 1]!;\n const x3 = coords[ci + 2]!, y3 = coords[ci + 3]!;\n ci += 4;\n flattenCubic(\n cx, cy,\n cx + (2 / 3) * (qx - cx), cy + (2 / 3) * (qy - cy),\n x3 + (2 / 3) * (qx - x3), y3 + (2 / 3) * (qy - y3),\n x3, y3, TOLERANCE, out,\n );\n cx = x3; cy = y3;\n } else if (cmd === PATH_Z) {\n out.push(sx, sy);\n cx = sx; cy = sy;\n }\n }\n // Close it, so a ray leaving through the last edge still finds a crossing.\n if (out.length >= 2 && (out[0] !== out[out.length - 2] || out[1] !== out[out.length - 1])) {\n out.push(out[0]!, out[1]!);\n }\n return out;\n}\n\n/**\n * Where the ray from `center` through `point` last crosses `poly`, or `null`\n * when it never does.\n *\n * The *last* crossing rather than the first: a concave outline can be crossed\n * more than once, and the far side is the boundary an edge should attach to.\n */\nexport function rayHit(\n poly: readonly number[],\n center: { x: number; y: number },\n point: { x: number; y: number },\n): { x: number; y: number } | null {\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n if (dx === 0 && dy === 0) return null;\n let bestT = -Infinity;\n let hit: { x: number; y: number } | null = null;\n for (let i = 0; i + 3 < poly.length; i += 2) {\n const ax = poly[i]!, ay = poly[i + 1]!;\n const bx = poly[i + 2]!, by = poly[i + 3]!;\n const ex = bx - ax;\n const ey = by - ay;\n const denom = dx * ey - dy * ex;\n if (denom === 0) continue;\n // t along the ray, u along the segment.\n const t = ((ax - center.x) * ey - (ay - center.y) * ex) / denom;\n const u = ((ax - center.x) * dy - (ay - center.y) * dx) / denom;\n if (t < 0 || u < 0 || u > 1) continue;\n if (t > bestT) {\n bestT = t;\n hit = { x: center.x + dx * t, y: center.y + dy * t };\n }\n }\n return hit;\n}\n\n/**\n * Every port moved onto `outline`. A port the ray misses — one at the node's\n * dead center, with no direction to cast along — is left where it was.\n */\nexport function portsOnOutline(\n ports: readonly Port[],\n outline: Outline,\n bounds: Bounds,\n): Port[] {\n if (bounds.width <= 0 || bounds.height <= 0) return [...ports];\n const poly = outlinePolyline(outline, bounds);\n const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };\n return ports.map((port) => {\n const hit = rayHit(poly, center, port.point);\n return hit === null ? port : { ...port, point: hit };\n });\n}\n","/**\n * Reading the `DiagramNode` trait off a scene node.\n *\n * Two ways to attach it, both of which this module's default reader answers:\n *\n * - **On the node.** `data.diagram` holds the trait. One node, one answer;\n * what a connect gesture writes when the author drags a new edge.\n * - **By kind.** A consumer declares once which data shapes take part, and\n * every matching node gets the trait without being stamped. This mirrors\n * `createNodeRouting` in the kit — a predicate over `data`, first match\n * wins — and is the shape to reach for when the participants are a class\n * of node rather than a hand-picked set.\n *\n * A reader is a plain function, so a consumer whose data lives somewhere else\n * entirely passes their own and never touches either form.\n */\nimport type { DiagramNode } from './types';\n\n/** The key on a node's `data` the default reader looks under. */\nexport const DIAGRAM_TRAIT_KEY = 'diagram';\n\n/** All a reader looks at. Deliberately not `SceneNode`: naming `TPose` there\n * would put it in a contravariant position for no gain, since nothing here\n * reads a pose. */\nexport interface DiagramNodeLike {\n id: string;\n kind: 'leaf' | 'container';\n data: unknown;\n}\n\n/** Answers \"is this node a diagram participant, and on what terms\" — `null`\n * for a node that takes no part. */\nexport type DiagramNodeReader = (node: DiagramNodeLike) => DiagramNode | null;\n\n/** One class of participant, declared once for every node whose data matches.\n * Mirrors `NodeRoutingEntry`. */\nexport interface DiagramNodeEntry {\n /** Unique within a reader; the same vocabulary as `NodeRoutingEntry.name`. */\n name: string;\n matches: (data: unknown) => boolean;\n /** The trait every matching node carries. A function when it varies with the\n * node's own data — a pipeline stage whose ports come from its rows. */\n trait: DiagramNode | ((data: unknown) => DiagramNode);\n}\n\n/** The trait on the node's own `data.diagram`, or `null`.\n *\n * An edge's trait lives under the same key, so `from` and `to` are what tells\n * the two apart. Without that test an edge reads as a participant declaring\n * no ports, and collects the four defaults on the degenerate pose an edge\n * carries — four grabbable ports in the middle of nowhere. */\nexport const dataKeyReader: DiagramNodeReader = (node) => {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const trait = (data as Record<string, unknown>)[DIAGRAM_TRAIT_KEY];\n if (trait === null || typeof trait !== 'object') return null;\n if ('from' in trait && 'to' in trait) return null;\n return trait as DiagramNode;\n};\n\n/**\n * A reader over declared kinds. A trait on the node's own data still wins, so\n * a single node can opt out of, or override, whatever its kind says.\n *\n * Throws on a duplicate `name`, for the reason `mergeContributions` does: a\n * class of node silently losing its ports is what this registry exists to make\n * loud.\n */\nexport function createDiagramNodes(entries: readonly DiagramNodeEntry[]): DiagramNodeReader {\n const seen = new Set<string>();\n for (const entry of entries) {\n if (seen.has(entry.name)) {\n throw new Error(`createDiagramNodes: duplicate entry name \"${entry.name}\"`);\n }\n seen.add(entry.name);\n }\n return (node) => {\n const own = dataKeyReader(node);\n if (own !== null) return own;\n for (const entry of entries) {\n if (!entry.matches(node.data)) continue;\n return typeof entry.trait === 'function' ? entry.trait(node.data) : entry.trait;\n }\n return null;\n };\n}\n\n/** The trait `node` carries, through `read` (default: its own `data.diagram`). */\nexport function diagramNodeOf(\n node: DiagramNodeLike,\n read: DiagramNodeReader = dataKeyReader,\n): DiagramNode | null {\n return read(node);\n}\n\n/** True when layout must leave this node where it is. */\nexport function isPinned(node: DiagramNodeLike, read?: DiagramNodeReader): boolean {\n return diagramNodeOf(node, read)?.pinned === true;\n}\n","/**\n * Where a node's ports are, in world coordinates.\n *\n * A port is placed in the node's **unrotated** bounds, then carried through\n * the pose's rotation — the same pivot every other kit reader uses, the AABB\n * center. Bounds come from the pose descriptor rather than from `pose.width`\n * and friends, so a node whose pose is a path, an ellipse or anything else a\n * consumer wired is connectable on the same terms as a rect.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n rotatePoint,\n type PoseProjection,\n type Vec2,\n} from '@weasel-js/core';\nimport { outlinePolyline, rayHit } from './onOutline';\nimport { diagramNodeOf, type DiagramNodeLike, type DiagramNodeReader } from './trait';\nimport type { Port, PortAnchor, PortSpec } from './types';\n\n/** The eight anchors almost everything wants, named the way a compass is. */\nexport const COMPASS = {\n nw: { u: 0, v: 0 },\n n: { u: 0.5, v: 0 },\n ne: { u: 1, v: 0 },\n e: { u: 1, v: 0.5 },\n se: { u: 1, v: 1 },\n s: { u: 0.5, v: 1 },\n sw: { u: 0, v: 1 },\n w: { u: 0, v: 0.5 },\n} as const satisfies Record<string, PortAnchor>;\n\n/**\n * What a node carrying no `ports` gets: the four edge midpoints of its own\n * bounds. Every node has bounds, so every node is connectable without saying\n * anything.\n */\nexport const DEFAULT_PORTS: readonly PortSpec[] = Object.freeze([\n { id: 'n', at: COMPASS.n },\n { id: 'e', at: COMPASS.e },\n { id: 's', at: COMPASS.s },\n { id: 'w', at: COMPASS.w },\n]);\n\nexport interface PortsOptions<TPose> {\n /** Reads the AABB a port is placed in, and the node's rotation. Defaults to\n * the kit's `AUTO_POSE_DESCRIPTOR`, which handles rect and path poses. */\n geometry?: PoseProjection<TPose>;\n /** How the `DiagramNode` trait is read off a node. */\n read?: DiagramNodeReader;\n}\n\n/**\n * The direction the anchor implies: away from the center of the bounds.\n *\n * `(2u-1, 2v-1)` is the anchor in a box that runs -1..1, which is exactly that\n * direction — an edge midpoint gets the axis-aligned normal, a corner gets the\n * diagonal. It is deliberately not scaled by the node's aspect: this is a\n * heading a router leaves along, not a point on the outline. A port at the\n * dead center has no direction, and says so.\n */\nfunction normalOf(at: PortAnchor): Vec2 | null {\n const x = at.u * 2 - 1;\n const y = at.v * 2 - 1;\n const len = Math.hypot(x, y);\n if (len === 0) return null;\n return { x: x / len, y: y / len };\n}\n\n/**\n * Every port on `node`, resolved against `pose`.\n *\n * Pass the pose the node is **painted** at — `effectivePose(scene, node)` —\n * not `node.pose`. A port that answers from the document pose while the node\n * is mid-drag puts an edge somewhere the user can see the node is not.\n */\nexport function portsOf<TPose>(\n node: DiagramNodeLike,\n pose: TPose,\n opts: PortsOptions<TPose> = {},\n): Port[] {\n const trait = diagramNodeOf(node, opts.read);\n if (trait === null) return [];\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>);\n const bounds = geometry.getBounds(pose);\n const rotation = geometry.getRotation?.(pose) ?? 0;\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n // A port is anchored in the bounds so it survives a resize, but it has to\n // *sit* on the shape: a parallelogram's west anchor is in the gap beside its\n // leaning edge, and an edge ending there ends in empty space. Flattened once\n // per call, not once per port.\n const poly = trait.outline === undefined || bounds.width <= 0 || bounds.height <= 0\n ? null\n : outlinePolyline(trait.outline, bounds);\n\n return (trait.ports ?? DEFAULT_PORTS).map((spec) => {\n const anchored: Vec2 = {\n x: bounds.x + spec.at.u * bounds.width,\n y: bounds.y + spec.at.v * bounds.height,\n };\n const flat = (poly === null ? null : rayHit(poly, { x: cx, y: cy }, anchored)) ?? anchored;\n const normal = spec.normal === undefined ? normalOf(spec.at) : spec.normal;\n if (rotation === 0) {\n return { id: spec.id, nodeId: node.id, point: flat, normal, ...typeOf(spec) };\n }\n return {\n id: spec.id,\n nodeId: node.id,\n point: rotatePoint(flat.x, flat.y, cx, cy, rotation),\n // A direction rotates about the origin, not about the node's center.\n normal: normal === null ? null : rotatePoint(normal.x, normal.y, 0, 0, rotation),\n ...typeOf(spec),\n };\n });\n}\n\n/** One named port, or `undefined` when the node has no such port. */\nexport function portOf<TPose>(\n node: DiagramNodeLike,\n pose: TPose,\n portId: string,\n opts: PortsOptions<TPose> = {},\n): Port | undefined {\n return portsOf(node, pose, opts).find((p) => p.id === portId);\n}\n\n/** Spread rather than assigned, so a port with no type has no `type` key at\n * all — `exactOptionalPropertyTypes` rejects an explicit `undefined`. */\nfunction typeOf(spec: PortSpec): { type?: string } {\n return spec.type === undefined ? {} : { type: spec.type };\n}\n","/**\n * The optional body builder: what a node looks like when it should read as a\n * flowchart box or a visual-programming operator, rather than as whatever\n * scene node it already was.\n *\n * **The body measures a floor; the author sets the rest.** Rows measure to a\n * `{ minWidth, minHeight }` and the node's pose is the max of that and what\n * the author gave it. Adding a port row can grow a node; nothing here ever\n * shrinks one back. Because the pose stays authored data, resize, align,\n * distribute, guides, snapping and undo need no special case, and a node that\n * did not come from the builder just has whatever size it already had.\n *\n * Text measurement is a seam rather than an import: measuring needs a 2D\n * context, which a geometry module has no business owning. `canvasMeasure`\n * adapts the kit's own `measureText` for a caller that has one.\n */\nimport { boxForContent, contentBox, outlinePath, type Bounds, type Outline } from './outline';\nimport { COMPASS } from './ports';\nimport type { DiagramNode, PortSpec } from './types';\n\n/** One line of body content. */\nexport type Row =\n /** Text. `label` is the node's name; `field` is a named value. */\n | { kind: 'label'; text: string; style?: RowTextStyle }\n | { kind: 'field'; label: string; value: string; style?: RowTextStyle }\n /** A row that carries ports on its own left and right edges — the\n * visual-programming shape, where an operator's inputs line up with the\n * rows they feed. */\n | { kind: 'ports'; left?: readonly RowPort[]; right?: readonly RowPort[]; height?: number }\n /** Reserved space a consumer paints into. */\n | { kind: 'slot'; height: number; id?: string };\n\n/** A port declared on a row rather than on the node's perimeter. */\nexport interface RowPort {\n id: string;\n /** Label shown beside it, and what the row measures against. */\n label?: string;\n type?: string;\n}\n\n/** The subset of a text style the body measures against. Deliberately small:\n * a full `ResolvedTextStyle` belongs to whatever paints the row. */\nexport interface RowTextStyle {\n fontSize?: number;\n fontFamily?: string;\n bold?: boolean;\n}\n\n/** Measures one run of text. Returns its advance width and its line height. */\nexport type MeasureRowText = (text: string, style: RowTextStyle) => { width: number; height: number };\n\nexport interface BodySpec {\n outline: Outline;\n rows: readonly Row[];\n /** Space between the outline and its rows. Default 8. */\n padding?: number;\n /** Space between adjacent rows. Default 4. */\n gap?: number;\n}\n\n/** What {@link buildBody} emits: the `AddNodeSpec` fields it fills in. Named\n * structurally rather than imported so a consumer whose scene is typed\n * differently can still spread one. */\nexport interface BodyNodeSpec<TData, TLayer extends string, TPose> {\n kind: 'container' | 'leaf';\n layer: TLayer;\n pose: TPose;\n data: TData;\n id?: string;\n parent?: string;\n /** Set `false` on every leaf the builder emits: the innermost hit wins, so a\n * row that answers a press is a body that cannot be dragged. */\n pickable?: boolean;\n}\n\n/** The floor a body's content puts under its node's size. */\nexport interface BodyFloor {\n minWidth: number;\n minHeight: number;\n}\n\n/** Where one row landed, in the same frame as the bounds it was laid out in.\n * A `ports` row's own ports anchor to this box. */\nexport interface RowBox extends Bounds {\n row: Row;\n index: number;\n}\n\n/** Where one row port's label sits, in the same frame as the row box it was\n * laid out in. Its vertical center is also where the port itself attaches, so\n * a label and the port it names cannot drift apart. */\nexport interface RowPortBox extends Bounds {\n port: RowPort;\n side: 'left' | 'right';\n /** Position within its own side, top to bottom. */\n index: number;\n}\n\nconst DEFAULT_PADDING = 8;\nconst DEFAULT_GAP = 4;\n/** What a row is worth when nothing measures its text. Enough that a body\n * laid out headlessly is not zero-height — a zero-height body renders as an\n * empty page with every unit test still green. */\nconst FALLBACK_LINE = 16;\n\n/** Adapts the kit's `measureText` for a caller holding a 2D context. Pass the\n * same context the renderer measures with, or the floor will not match what\n * is painted. */\nexport function canvasMeasure(\n ctx: { measureText(text: string): { width: number } ; font: string },\n): MeasureRowText {\n return (text, style) => {\n const size = style.fontSize ?? FALLBACK_LINE;\n ctx.font = `${style.bold === true ? 'bold ' : ''}${size}px ${style.fontFamily ?? 'sans-serif'}`;\n return { width: ctx.measureText(text).width, height: Math.ceil(size * 1.2) };\n };\n}\n\n/** What each row is worth on its own, before padding and gaps. */\nfunction measureRow(row: Row, measure: MeasureRowText | undefined): { width: number; height: number } {\n const text = (s: string, style?: RowTextStyle): { width: number; height: number } =>\n measure === undefined\n ? { width: s.length * (((style?.fontSize ?? FALLBACK_LINE) * 0.6)), height: FALLBACK_LINE }\n : measure(s, style ?? {});\n\n switch (row.kind) {\n case 'label':\n return text(row.text, row.style);\n case 'field': {\n // Label and value sit on one line with a gap between them.\n const l = text(row.label, row.style);\n const v = text(row.value, row.style);\n return { width: l.width + DEFAULT_GAP * 2 + v.width, height: Math.max(l.height, v.height) };\n }\n case 'ports': {\n const side = (ports: readonly RowPort[] | undefined): number =>\n (ports ?? []).reduce((w, p) => Math.max(w, p.label === undefined ? 0 : text(p.label).width), 0);\n const rows = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);\n return {\n width: side(row.left) + DEFAULT_GAP * 2 + side(row.right),\n height: row.height ?? rows * FALLBACK_LINE,\n };\n }\n case 'slot':\n return { width: 0, height: row.height };\n }\n}\n\n/**\n * The smallest box `spec`'s rows fit in. A node's pose is maxed against this,\n * never set to it.\n */\nexport function measureBody(spec: BodySpec, measure?: MeasureRowText): BodyFloor {\n const padding = spec.padding ?? DEFAULT_PADDING;\n const gap = spec.gap ?? DEFAULT_GAP;\n let width = 0;\n let height = 0;\n for (const [i, row] of spec.rows.entries()) {\n const m = measureRow(row, measure);\n width = Math.max(width, m.width);\n height += m.height + (i > 0 ? gap : 0);\n }\n // The rows fit the *content* box; the node's own box has to be whatever\n // contains that, or a diamond's label lands outside the diamond.\n const box = boxForContent(spec.outline, {\n width: width + padding * 2,\n height: height + padding * 2,\n });\n return { minWidth: box.width, minHeight: box.height };\n}\n\n/**\n * The authored size, grown to fit the body. Never shrinks: a row removed\n * leaves the node the size the author last saw it at, which is the only\n * behavior that survives a resize the author did on purpose.\n */\nexport function sizeToBody<TPose extends Bounds>(pose: TPose, floor: BodyFloor): TPose {\n const width = Math.max(pose.width, floor.minWidth);\n const height = Math.max(pose.height, floor.minHeight);\n if (width === pose.width && height === pose.height) return pose;\n return { ...pose, width, height };\n}\n\n/** Where each row sits inside `bounds`, top to bottom. Rows keep their\n * measured heights; the leftover goes unclaimed at the bottom rather than\n * being distributed, so a row does not move when a sibling grows. */\nexport function layoutBody(\n spec: BodySpec,\n bounds: Bounds,\n measure?: MeasureRowText,\n): RowBox[] {\n const padding = spec.padding ?? DEFAULT_PADDING;\n const gap = spec.gap ?? DEFAULT_GAP;\n const inner = contentBox(spec.outline, bounds);\n const width = Math.max(inner.width - padding * 2, 0);\n let y = inner.y + padding;\n return spec.rows.map((row, index) => {\n const h = measureRow(row, measure).height;\n const box: RowBox = { row, index, x: inner.x + padding, y, width, height: h };\n y += h + gap;\n return box;\n });\n}\n\n/**\n * Where each of a `ports` row's ports goes inside `box`, on the same terms\n * `layoutBody` gives one box per row.\n *\n * Both sides are cut into the same number of slots — the longer side's count —\n * so the nth input faces the nth output whichever side has more. A label box\n * is as wide as its own text and pinned to its own edge of the row; an\n * unlabeled port gets a zero-width box there, which is still where it attaches.\n */\nexport function layoutRowPorts(\n row: Extract<Row, { kind: 'ports' }>,\n box: Bounds,\n measure?: MeasureRowText,\n): RowPortBox[] {\n const width = (label: string | undefined): number =>\n label === undefined ? 0 : measureRow({ kind: 'label', text: label }, measure).width;\n const slots = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);\n const slotHeight = box.height / slots;\n const out: RowPortBox[] = [];\n const side = (ports: readonly RowPort[] | undefined, which: 'left' | 'right'): void => {\n for (const [index, port] of (ports ?? []).entries()) {\n const w = width(port.label);\n out.push({\n port,\n side: which,\n index,\n x: which === 'left' ? box.x : box.x + box.width - w,\n y: box.y + index * slotHeight,\n width: w,\n height: slotHeight,\n });\n }\n };\n side(row.left, 'left');\n side(row.right, 'right');\n return out;\n}\n\n/**\n * The `DiagramNode` trait a built body implies: perimeter ports for the\n * outline, plus one port per `ports`-row entry, anchored to that row's own\n * left or right edge.\n *\n * Anchors are normalized against `bounds`, so they survive the node being\n * resized — which is the whole reason `PortAnchor` is normalized.\n *\n * **A row port on a side takes that side's compass default with it.** Both sit\n * on the same edge, and a row near the vertical middle puts one exactly on top\n * of `w` or `e` — where the later region wins the hit and the other is\n * grabbable nowhere. A body that declares where its inputs attach has said what\n * that side is for.\n */\nexport function bodyTrait(spec: BodySpec, bounds: Bounds, measure?: MeasureRowText): DiagramNode {\n const outline = spec.outline;\n const compass: PortSpec[] = [\n { id: 'n', at: COMPASS.n },\n { id: 'e', at: COMPASS.e },\n { id: 's', at: COMPASS.s },\n { id: 'w', at: COMPASS.w },\n ];\n if (bounds.height <= 0) return { outline, ports: compass };\n\n const rowPorts: PortSpec[] = [];\n let hasLeft = false;\n let hasRight = false;\n for (const box of layoutBody(spec, bounds, measure)) {\n if (box.row.kind !== 'ports') continue;\n for (const pb of layoutRowPorts(box.row, box, measure)) {\n if (pb.side === 'left') hasLeft = true;\n else hasRight = true;\n const v = (pb.y + pb.height / 2 - bounds.y) / bounds.height;\n rowPorts.push(withType(\n { id: pb.port.id, at: { u: pb.side === 'left' ? 0 : 1, v } },\n pb.port.type,\n ));\n }\n }\n const kept = compass.filter((p) =>\n !(p.id === 'w' && hasLeft) && !(p.id === 'e' && hasRight));\n return { outline, ports: [...kept, ...rowPorts] };\n}\n\nfunction withType(spec: PortSpec, type: string | undefined): PortSpec {\n return type === undefined ? spec : { ...spec, type };\n}\n\n/** The outline path for a built body at `bounds` — what paints it, and what a\n * perimeter-hugging port will eventually be placed on. */\nexport function bodyOutline(spec: BodySpec, bounds: Bounds) {\n return outlinePath(spec.outline, bounds);\n}\n\n/** What a built body's rows are handed to, one call per row.\n *\n * `text` is the row's content already formatted — a `label`'s own text, or a\n * `field`'s `\"label: value\"` — so the common case needs no discrimination.\n * Return `null` for a row the consumer paints itself; `ports` and `slot` rows\n * arrive with `text` empty and are the usual ones to decline. */\nexport type RowNodeData<TData> = (text: string, box: RowBox) => TData | null;\n\nexport interface BuildBodyOptions<TData, TLayer extends string, TPose extends Bounds> {\n layer: TLayer;\n /** The container's id. Edges name it, so pass one for anything an edge or a\n * layout `pin` will refer to. */\n id?: string;\n measure?: MeasureRowText;\n /** The container's own data, given the trait the builder computed and the\n * pose it was computed against. */\n body: (trait: DiagramNode, pose: TPose) => TData;\n /** One row's data, or `null` to leave that row undrawn. */\n row: RowNodeData<TData>;\n /** One row port's label, or `null` to leave it undrawn. Ports with no\n * `label` are never offered. Omit to draw none — a body whose ports are\n * named only for the width they claim needs nothing here. */\n portLabel?: (text: string, box: RowPortBox) => TData | null;\n}\n\n/**\n * The scene nodes a built body is: one container carrying the trait, and one\n * leaf per row that wants drawing.\n *\n * Rows are ordinary scene nodes rather than something this package paints, so\n * the kit's own text painter draws them and text editing, styling and\n * selection work on them unchanged. The walk that places them is\n * `layoutBody` — the same one `bodyTrait` anchors its row ports against, which\n * is why a label and its ports cannot drift apart.\n *\n * The pose is `sizeToBody(at, measureBody(spec))`: the body measures a floor\n * and the authored size is grown to clear it, never shrunk.\n */\nexport function buildBody<TData, TLayer extends string, TPose extends Bounds>(\n spec: BodySpec,\n at: TPose,\n opts: BuildBodyOptions<TData, TLayer, TPose>,\n): { pose: TPose; specs: BodyNodeSpec<TData, TLayer, TPose>[] } {\n const pose = sizeToBody(at, measureBody(spec, opts.measure));\n const specs: BodyNodeSpec<TData, TLayer, TPose>[] = [{\n kind: 'container',\n layer: opts.layer,\n pose,\n data: opts.body(bodyTrait(spec, pose, opts.measure), pose),\n ...(opts.id === undefined ? {} : { id: opts.id }),\n }];\n\n const leaf = (box: Bounds, data: TData): void => {\n specs.push({\n kind: 'leaf',\n layer: opts.layer,\n pose: { ...pose, x: box.x, y: box.y, width: box.width, height: box.height },\n data,\n pickable: false,\n ...(opts.id === undefined ? {} : { parent: opts.id }),\n });\n };\n\n const portLabel = opts.portLabel;\n for (const box of layoutBody(spec, pose, opts.measure)) {\n const data = opts.row(rowText(box.row), box);\n if (data !== null) leaf(box, data);\n if (portLabel === undefined || box.row.kind !== 'ports') continue;\n for (const pb of layoutRowPorts(box.row, box, opts.measure)) {\n if (pb.port.label === undefined) continue;\n const labelData = portLabel(pb.port.label, pb);\n if (labelData !== null) leaf(pb, labelData);\n }\n }\n return { pose, specs };\n}\n\n/** A row's content as one string: empty for a row that carries no text. */\nfunction rowText(row: Row): string {\n if (row.kind === 'label') return row.text;\n if (row.kind === 'field') return `${row.label}: ${row.value}`;\n return '';\n}\n","/**\n * A label on an edge: an ordinary leaf node that derives its *pose* from the\n * route it sits on.\n *\n * It reads the edge's resolved path off its dependency rather than routing\n * again, so the label and the arrowhead can never disagree about where the\n * edge went. Everything else about it is a normal scene node — its own size,\n * data, styling, z-order and selection.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n pointAlongPath,\n translatePoseViaDescriptor,\n type DerivedDep,\n type PoseProjection,\n} from '@weasel-js/core';\n\n/** Where along an edge a label sits. */\nexport interface DiagramLabel {\n /** `'start'`, `'mid'` and `'end'` are 0, 0.5 and 1; a number is that\n * fraction of the route's length. */\n at: 'start' | 'mid' | 'end' | number;\n /** World units perpendicular to the route, to the **left of the direction of\n * travel** — above a left-to-right edge. Default 0, which centers the label\n * on the line. */\n offset?: number;\n}\n\nconst NAMED = { start: 0, mid: 0.5, end: 1 } as const;\n\n/** The label trait on a node's data, or `null`. */\nexport function diagramLabelOf(node: { data: unknown }): DiagramLabel | null {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const trait = (data as { diagram?: unknown }).diagram;\n if (trait === null || typeof trait !== 'object') return null;\n const label = (trait as { label?: unknown }).label;\n if (label === null || typeof label !== 'object') return null;\n return 'at' in label ? (label as DiagramLabel) : null;\n}\n\nexport interface LabelPoseOptions<TPose> {\n geometry?: PoseProjection<TPose>;\n}\n\n/**\n * A `derivePose` that stations a label along its dependency's path.\n *\n * Returns `null` — nothing derived, so the node keeps its authored pose —\n * when the node carries no label trait, when the dependency is gone, or when\n * the dependency derives no path. A label that snapped to the origin because\n * its edge was deleted is worse than one that stayed where the author left it.\n */\nexport function labelDerivePose<TPose>(\n opts: LabelPoseOptions<TPose> = {},\n): (node: { pose: TPose; data: unknown }, deps: readonly (DerivedDep<TPose> | undefined)[]) => TPose | null {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>);\n\n return (node, deps) => {\n const label = diagramLabelOf(node);\n if (label === null) return null;\n const path = deps[0]?.path ?? null;\n if (path === null) return null;\n\n const t = typeof label.at === 'number' ? label.at : NAMED[label.at] ?? 0.5;\n const station = pointAlongPath(path, t);\n if (station === null) return null;\n\n const offset = label.offset ?? 0;\n // Left of travel: with y down, that is above an edge running rightward.\n const x = station.point.x + station.tangent.y * offset;\n const y = station.point.y - station.tangent.x * offset;\n\n const bounds = geometry.getBounds(node.pose);\n return translatePoseViaDescriptor(\n node.pose,\n x - (bounds.x + bounds.width / 2),\n y - (bounds.y + bounds.height / 2),\n geometry,\n );\n };\n}\n\n/** Registry key for {@link LABEL_DERIVE_POSE}. */\nexport const DIAGRAM_LABEL = 'diagram:label';\n\n/** The default label derivation, as one stable function reference so `toJSON`\n * can find its key. */\nexport const LABEL_DERIVE_POSE = labelDerivePose<unknown>();\n","/**\n * `DiagramEdge` — a connection between two participants.\n *\n * An edge is an ordinary leaf scene node with `dependsOn: [from, to]` and a\n * `derivePath` that runs a **router**. Making it a scene node rather than a\n * plugin-owned render layer is the load-bearing choice: it buys selection,\n * hit-testing, hover, styling, z-order, SVG export, undo and copy/paste\n * without implementing any of them. The cost is that an edge costs what a node\n * costs — right for diagrams of tens to hundreds of edges, wrong for a\n * 10k-edge force graph, which keeps its render layer.\n *\n * **Author-dragged waypoints are data on the edge and the router routes\n * through them.** Manual control never authors the path; it authors\n * constraints on the path. That is what keeps derived geometry and hand-tuning\n * compatible — a moved endpoint still re-routes, through the waypoints the\n * author put there.\n *\n * Arrowheads are not here. They are stroke markers, the same\n * `markerStart` / `markerEnd` any other stroke carries.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n polylineFromPoints,\n type DerivedDep,\n type Path,\n type PoseProjection,\n type SceneRegistry,\n type Vec2,\n} from '@weasel-js/core';\nimport { DIAGRAM_LABEL, LABEL_DERIVE_POSE } from './label';\nimport { portOf, portsOf, type PortsOptions } from './ports';\nimport type { Port } from './types';\n\n/** Where an edge attaches at one end. */\nexport interface EdgeEnd {\n /** The port to leave from, when the endpoint declares one. Falls back to\n * the nearest port, so an edge drawn before ports were thought about still\n * meets the shape. */\n port?: string;\n}\n\n/** The trait on an edge's `data`, under the same key participants use. */\nexport interface DiagramEdge {\n from: EdgeEnd;\n to: EdgeEnd;\n /** Registry key for the router. Resolved by whoever builds the edge's\n * `derivePath`; unknown keys fall back to `straight`. */\n router?: string;\n /** Points in world coordinates the route must pass through, in order. The\n * author owns these; the router owns everything between them. */\n waypoints?: readonly Vec2[];\n}\n\n/** What a router is given: the two resolved ends, and the author's waypoints\n * between them. */\nexport interface RouteRequest {\n from: Port;\n to: Port;\n waypoints: readonly Vec2[];\n}\n\n/** A router returns the points the edge runs through, `from.point` first and\n * `to.point` last. Turning those into a `Path` is `edgePath`'s job, so a\n * router never has to know about path encodings. */\nexport type Router = (req: RouteRequest) => readonly Vec2[];\n\n/** The straight run between the two ends, through any waypoints. */\nexport const straight: Router = (req) => [req.from.point, ...req.waypoints, req.to.point];\n\n/**\n * An axis-aligned route: leave along the departing end's normal and arrive\n * against the receiving one's.\n *\n * A leg is one elbow where the two ends face different axes and two where they\n * face the same one, turning at the midpoint of the axis they share. Arriving\n * along the port's own facing is what makes the arrowhead point *into* the\n * shape — a route that lands on a west-facing port from above puts its marker\n * across the corner, which reads as aimed at nothing.\n */\nexport const orthogonal: Router = (req) => {\n const stops = [req.from.point, ...req.waypoints, req.to.point];\n const out: Vec2[] = [stops[0]!];\n for (let i = 1; i < stops.length; i++) {\n const a = out[out.length - 1]!;\n const b = stops[i]!;\n if (a.x === b.x || a.y === b.y) {\n out.push(b);\n continue;\n }\n // Only the first leg has a port to leave along; later legs follow the\n // one before them so the route does not alternate for no reason.\n const leaveHorizontal = i === 1\n ? isHorizontal(req.from.normal)\n : out.length > 1 && out[out.length - 2]!.y === a.y;\n // Likewise only the last leg has a port to arrive against. Without a\n // facing there is nothing to satisfy, so it keeps the single elbow.\n const arriving = i === stops.length - 1 ? req.to.normal : null;\n const arriveHorizontal = arriving == null ? !leaveHorizontal : isHorizontal(arriving);\n if (leaveHorizontal !== arriveHorizontal) {\n out.push(leaveHorizontal ? { x: b.x, y: a.y } : { x: a.x, y: b.y });\n out.push(b);\n continue;\n }\n if (leaveHorizontal) {\n const mid = (a.x + b.x) / 2;\n out.push({ x: mid, y: a.y }, { x: mid, y: b.y }, b);\n } else {\n const mid = (a.y + b.y) / 2;\n out.push({ x: a.x, y: mid }, { x: b.x, y: mid }, b);\n }\n }\n return out;\n};\n\n/** Which axis a port faces. A port with no facing counts as horizontal, which\n * is the leave-rightward default the router has always taken. */\nfunction isHorizontal(normal: Vec2 | null | undefined): boolean {\n return Math.abs(normal?.x ?? 1) >= Math.abs(normal?.y ?? 0);\n}\n\n/** How far a bezier reaches along each end's normal, as a fraction of the\n * straight-line distance between the two points it joins. */\nconst BEZIER_REACH = 0.4;\n\n/**\n * A smooth route, sampled into points.\n *\n * Each leg is a cubic that leaves along the departing end's normal and arrives\n * against the receiving one's, which is what makes a bezier edge read as\n * plugged into its port rather than aimed at it. Sampled rather than emitted\n * as curve commands so every router returns the same thing; `edgePath` is free\n * to emit curves later without changing the contract.\n */\nexport const bezier: Router = (req) => {\n const stops = [req.from.point, ...req.waypoints, req.to.point];\n const out: Vec2[] = [stops[0]!];\n for (let i = 1; i < stops.length; i++) {\n const a = stops[i - 1]!;\n const b = stops[i]!;\n const reach = Math.hypot(b.x - a.x, b.y - a.y) * BEZIER_REACH;\n const outN = i === 1 ? req.from.normal : null;\n const inN = i === stops.length - 1 ? req.to.normal : null;\n const c1 = outN === null || outN === undefined\n ? { x: a.x + (b.x - a.x) * BEZIER_REACH, y: a.y + (b.y - a.y) * BEZIER_REACH }\n : { x: a.x + outN.x * reach, y: a.y + outN.y * reach };\n const c2 = inN === null || inN === undefined\n ? { x: b.x - (b.x - a.x) * BEZIER_REACH, y: b.y - (b.y - a.y) * BEZIER_REACH }\n : { x: b.x + inN.x * reach, y: b.y + inN.y * reach };\n for (let s = 1; s <= BEZIER_SAMPLES; s++) {\n out.push(cubicAt(a, c1, c2, b, s / BEZIER_SAMPLES));\n }\n }\n return out;\n};\n\nconst BEZIER_SAMPLES = 16;\n\nfunction cubicAt(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 {\n const u = 1 - t;\n const a = u * u * u;\n const b = 3 * u * u * t;\n const c = 3 * u * t * t;\n const d = t * t * t;\n return {\n x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,\n y: a * p0.y + b * p1.y + c * p2.y + d * p3.y,\n };\n}\n\n/** The routers this package ships. A consumer's own go in the same shape. */\nexport const ROUTERS: Readonly<Record<string, Router>> = Object.freeze({\n straight,\n orthogonal,\n bezier,\n});\n\n/** The edge trait on a node's data, or `null`. */\nexport function diagramEdgeOf(node: { data: unknown }): DiagramEdge | null {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const edge = (data as { diagram?: unknown }).diagram;\n if (edge === null || typeof edge !== 'object') return null;\n return 'from' in edge && 'to' in edge ? (edge as DiagramEdge) : null;\n}\n\n/**\n * The port an end resolves to: the one it named, else the port facing the\n * other end most directly.\n *\n * \"Facing\" rather than \"nearest\": a port on the far side of a wide node can be\n * closer in a straight line than the one pointing at the target, and an edge\n * that leaves through its own node reads as a bug however short it is.\n */\nexport function resolveEnd<TPose>(\n end: EdgeEnd,\n dep: DerivedDep<TPose>,\n toward: Vec2,\n opts: PortsOptions<TPose>,\n allPorts: (d: DerivedDep<TPose>) => Port[],\n): Port | undefined {\n if (end.port !== undefined) {\n const named = portOf(dep.node as never, dep.pose, end.port, opts);\n if (named !== undefined) return named;\n }\n let best: Port | undefined;\n let bestScore = -Infinity;\n for (const port of allPorts(dep)) {\n const dx = toward.x - port.point.x;\n const dy = toward.y - port.point.y;\n const len = Math.hypot(dx, dy) || 1;\n // Alignment with the port's own facing, tie-broken toward the closer port.\n const facing = port.normal === null\n ? 0\n : (port.normal.x * dx + port.normal.y * dy) / len;\n const score = facing - len / 1e6;\n if (score > bestScore) {\n bestScore = score;\n best = port;\n }\n }\n return best;\n}\n\nexport interface EdgeRouteOptions<TPose> extends PortsOptions<TPose> {\n /** Routers by key. Defaults to {@link ROUTERS}. */\n routers?: Readonly<Record<string, Router>>;\n}\n\n/**\n * A `derivePath` that routes an edge between its two dependencies.\n *\n * Returns `null` — nothing to draw — when the node is not an edge, when either\n * dependency is gone, or when an endpoint offers no ports at all. A dangling\n * edge painting a line to the origin is worse than a dangling edge painting\n * nothing.\n */\nexport function edgeDerivePath<TPose>(\n opts: EdgeRouteOptions<TPose> = {},\n): (node: { data: unknown }, deps: readonly (DerivedDep<TPose> | undefined)[]) => Path | null {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>);\n const portOpts: PortsOptions<TPose> = { geometry, ...(opts.read ? { read: opts.read } : {}) };\n const allPorts = (d: DerivedDep<TPose>): Port[] =>\n portsOf(d.node as never, d.pose, portOpts);\n const centerOf = (d: DerivedDep<TPose>): Vec2 => {\n const b = geometry.getBounds(d.pose);\n return { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n };\n\n return (node, deps) => {\n const edge = diagramEdgeOf(node);\n if (edge === null) return null;\n const [fromDep, toDep] = deps;\n if (fromDep === undefined || toDep === undefined) return null;\n\n // Each end aims at the other's center, which is stable while both are\n // being resolved — aiming at the other *port* would be circular.\n const from = resolveEnd(edge.from, fromDep, centerOf(toDep), portOpts, allPorts);\n const to = resolveEnd(edge.to, toDep, centerOf(fromDep), portOpts, allPorts);\n if (from === undefined || to === undefined) return null;\n\n const routers = opts.routers ?? ROUTERS;\n const router = (edge.router !== undefined && routers[edge.router]) || straight;\n const points = router({ from, to, waypoints: edge.waypoints ?? [] });\n return points.length < 2 ? null : polylineFromPoints(points as { x: number; y: number }[]);\n };\n}\n\n/** Registry key for {@link EDGE_DERIVE_PATH}. */\nexport const DIAGRAM_EDGE = 'diagram:edge';\n\n/** The default edge router, as one stable function reference so `toJSON` can\n * find its key. A consumer wanting different options registers their own\n * `edgeDerivePath(...)` under a key of their choosing. */\nexport const EDGE_DERIVE_PATH = edgeDerivePath<unknown>();\n\n/** Merge this package's registry entries under a consumer's, so an edge\n * round-trips through `toJSON` without the consumer wiring the key. */\nexport function withDiagramRegistry<TPose>(\n registry: SceneRegistry<TPose> = {},\n): SceneRegistry<TPose> {\n return {\n ...registry,\n derivePath: {\n [DIAGRAM_EDGE]: EDGE_DERIVE_PATH as NonNullable<SceneRegistry<TPose>['derivePath']>[string],\n ...registry.derivePath,\n },\n derivePose: {\n [DIAGRAM_LABEL]: LABEL_DERIVE_POSE as NonNullable<SceneRegistry<TPose>['derivePose']>[string],\n ...registry.derivePose,\n },\n };\n}\n","/**\n * Ports as affordances — what makes a painted port a grabbable one.\n *\n * A port is declared as an `AffordanceRegion`, so the kit's own region walk\n * supplies the hit-test, the screen-pixel hit radius, the cursor and the\n * exclusive claim that keeps a port drag out of the select tool's hands. That\n * is the \"visible chrome is always hittable\" rule doing the work: the walk runs\n * on every pointerdown before any tool sees the event, so a port answers\n * whatever tool happens to be active.\n *\n * Two things about this are easy to get wrong, and both fail silently.\n *\n * **`targetId` is `null`.** The framework composes a target's rotation about\n * its bounds center for any region naming one, and `portsOf` has already\n * rotated the port. Naming the participant here would rotate it twice.\n *\n * **`hitKind` is not set.** On the registered-layer route the discriminator is\n * the layer's own id — `<SceneCanvas>` stamps the hit `layer:<RenderLayer.id>`\n * and carries `initialScratch` through as `payload`. A `hitKind` declared here\n * would be dropped, and a binding written against it would never match.\n */\nimport type {\n Affordance,\n AffordanceRegion,\n ChromeState,\n CursorSpec,\n FillStyle,\n PoseProjection,\n Stroke,\n} from '@weasel-js/core';\nimport { portsOf } from './ports';\nimport type { DiagramNodeLike, DiagramNodeReader } from './trait';\nimport type { Port } from './types';\n\n/** The layer id this package composes its port regions into. */\nexport const PORT_LAYER_ID = 'diagram-ports';\n\n/** The affordance kind a press on a port reports — what a binding's\n * `target: 'affordance:...'` has to name. `<SceneCanvas>` builds it from\n * {@link PORT_LAYER_ID}, so the two cannot drift. */\nexport const PORT_AFFORDANCE_KIND = `layer:${PORT_LAYER_ID}` as const;\n\n/** A participant and the pose it is **painted** at. `effectivePose`, not\n * `node.pose` — a port that answers from the document pose while its node is\n * mid-drag sits somewhere the user can see the node is not. */\nexport interface ParticipantPose<TPose> {\n node: DiagramNodeLike;\n pose: TPose;\n}\n\n/** Where the affordance gets its participants. A thunk rather than a scene so\n * the geometry is testable without one, and so a consumer whose participants\n * come from somewhere else needs no adapter. */\nexport type ParticipantSource<TPose> = () => Iterable<ParticipantPose<TPose>>;\n\n/** What a press on a port hands the action that picks up the drag. Arrives as\n * `InvocationCtx.drag.affordance.payload`. */\nexport interface PortScratch {\n /** `CommonAffordanceScratch.targetId` — becomes `AffordanceHit.targetIds`. */\n targetId: string;\n nodeId: string;\n portId: string;\n /** The port resolved at press time: where it was and which way it faces. */\n port: Port;\n}\n\nexport interface PortAffordanceOptions<TPose> {\n /** Also the chrome-caps visibility id. Default {@link PORT_LAYER_ID}. */\n id?: string;\n read?: DiagramNodeReader;\n geometry?: PoseProjection<TPose>;\n /** Which participants show their ports. Default: all of them. Gate on\n * selection or hover by reading `state`. */\n shows?: (node: DiagramNodeLike, state: ChromeState) => boolean;\n /** Screen-pixel hit radius. Default 8, the kit's `HANDLE_BASE_PX`. */\n hitRadiusPx?: number;\n /** Screen-pixel side of the painted square. Default 7. Omit `paint` entirely\n * by passing 0 — a port the consumer draws itself is still hittable. */\n sizePx?: number;\n fill?: FillStyle;\n stroke?: Stroke;\n cursor?: CursorSpec;\n /** Default `'exclusive'` on pointer gestures: a drag from a port is a\n * connect, never a move of the node underneath it. */\n strength?: 'exclusive' | 'shared';\n}\n\nconst DEFAULT_HIT_PX = 8;\nconst DEFAULT_SIZE_PX = 7;\n\n/** Read a port press's scratch back off the hit an action was handed. */\nexport function portScratchOf(hit: { payload?: unknown } | null | undefined): PortScratch | null {\n const payload = hit?.payload as PortScratch | undefined;\n return payload !== undefined && typeof payload.portId === 'string' ? payload : null;\n}\n\n/**\n * The affordance. Compose it into a layer with `composeAffordanceLayer` and\n * attach that with `CanvasExtensionApi.registerLayer` — the only attach route\n * that is hit-tested. A `Contribution.overlay` is painted and never hit.\n */\nexport function createPortAffordance<TPose>(\n participants: ParticipantSource<TPose>,\n opts: PortAffordanceOptions<TPose> = {},\n): Affordance {\n const {\n id = PORT_LAYER_ID,\n hitRadiusPx = DEFAULT_HIT_PX,\n sizePx = DEFAULT_SIZE_PX,\n strength = 'exclusive',\n } = opts;\n const portOpts = {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n };\n const paint = sizePx <= 0\n ? undefined\n : {\n kind: 'square' as const,\n sizePx,\n ...(opts.fill ? { fill: opts.fill } : {}),\n ...(opts.stroke ? { stroke: opts.stroke } : {}),\n };\n\n return {\n id,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const { node, pose } of participants()) {\n if (opts.shows !== undefined && !opts.shows(node, state)) continue;\n for (const port of portsOf(node, pose, portOpts)) {\n out.push({\n id: `${node.id}:${port.id}`,\n targetId: null,\n shape: { kind: 'point', x: port.point.x, y: port.point.y, hitRadiusPx },\n ...(paint ? { paint } : {}),\n ...(opts.cursor !== undefined ? { cursor: opts.cursor } : {}),\n strength,\n claimedKinds: ['pointer'],\n bind: () => ({\n initialScratch: {\n targetId: node.id,\n nodeId: node.id,\n portId: port.id,\n port,\n } satisfies PortScratch,\n }),\n });\n }\n }\n return out;\n },\n };\n}\n","/**\n * The connect gesture — dragging one port onto another to author an edge.\n *\n * Connect is an ordinary drag binding, not a mode and not a tool of its own:\n * the binding is gated on a press landing on a port affordance, so a connect\n * starts from whatever tool happens to be active. The gate lives in the\n * binding's `target`, which is what lets a press that is *not* on a port fall\n * through to the tool that wants it instead of being swallowed here.\n *\n * **Where validity is decided.** The two halves are decided in different\n * places, and conflating them is the mistake this package is written to avoid:\n *\n * - *Which presses start a connect* is routing, and belongs to the binding\n * spec. `connectBinding` names the port layer's affordance kind; nothing in\n * the action body re-checks what was pressed.\n * - *Which ports a live connect may land on* cannot be routing — the\n * dispatcher never re-reads the affordance under a moving pointer, so a\n * spec has no vocabulary for it. It is decided by `canConnect` filtering\n * the **candidate set**: an illegal port is never a candidate, so the\n * preview will not snap to it and a release over it commits nothing. That\n * is a narrower thing than an action body that inspects a hit and bails.\n *\n * One resolver answers both the live preview and the commit, for the reason\n * `insertAction` does the same: a preview computed separately from the commit\n * is a preview that can lie about what releasing will do.\n */\nimport {\n polylineFromPoints,\n type Action,\n type DrawCommand,\n type GestureBinding,\n type InvocationCtx,\n type OngoingHandle,\n type OngoingOverlay,\n type PoseProjection,\n type Scene,\n type Stroke,\n type Vec2,\n} from '@weasel-js/core';\nimport { EDGE_DERIVE_PATH, ROUTERS, type DiagramEdge, type Router } from './edge';\nimport { PORT_AFFORDANCE_KIND, portScratchOf, type ParticipantSource } from './portAffordance';\nimport { portsOf } from './ports';\nimport type { DiagramNodeReader } from './trait';\nimport type { Port } from './types';\n\n/** The default action id, and what {@link connectBinding} points at. */\nexport const CONNECT_ACTION_ID = 'diagram.connect';\n\n/** Whether an edge may run from `from` to `to`. */\nexport type CanConnect = (from: Port, to: Port) => boolean;\n\n/** The edge a finished connect describes. Both ends are resolved ports, so a\n * consumer minting the node has nothing left to look up. */\nexport interface PendingEdge {\n from: Port;\n to: Port;\n /** Registry key for the router the new edge should name. */\n router: string;\n}\n\n/**\n * The shipped policy: a port may not join itself, and two ports that both\n * declare a `type` must declare the same one.\n *\n * A port with no type joins anything — `PortSpec.type` is uninterpreted by this\n * package, so an untyped diagram stays fully connectable without opting out.\n * Two ports on the *same node* may be joined: a self-edge between two different\n * ports is meaningful in a state machine, and refusing it here would be policy\n * masquerading as a rule.\n */\nexport const defaultCanConnect: CanConnect = (from, to) => {\n if (from.nodeId === to.nodeId && from.id === to.id) return false;\n if (from.type === undefined || to.type === undefined) return true;\n return from.type === to.type;\n};\n\nexport interface ConnectActionOptions<TPose> {\n /** Where the droppable ports come from. The same source the port affordance\n * reads, so what is grabbable and what is landable cannot disagree. */\n participants: ParticipantSource<TPose>;\n /** Default {@link CONNECT_ACTION_ID}. */\n id?: string;\n read?: DiagramNodeReader;\n geometry?: PoseProjection<TPose>;\n /** Default {@link defaultCanConnect}. */\n canConnect?: CanConnect;\n /** How near the pointer must come to a port, in world units, before the\n * edge snaps to it. Default 16. */\n snapRadius?: number;\n /** Registry key the new edge names, and the router the preview draws with.\n * Default `'straight'`. */\n router?: string;\n routers?: Readonly<Record<string, Router>>;\n /** How the in-flight edge is painted. */\n stroke?: Stroke;\n /**\n * Mints and commits the edge. Called once, on release over a valid port.\n *\n * Defaults to {@link commitEdgeToScene} against `deps.scene`, which is what\n * makes the gesture work with nothing wired. Override it the way a consumer\n * overrides the kit's `insert` dep — to choose the edge node's data, its\n * layer, or its stroke.\n */\n commit?: (edge: PendingEdge, ctx: InvocationCtx) => void;\n}\n\nconst DEFAULT_SNAP = 16;\n/** What a connect-authored edge is drawn with, when the consumer overrides\n * nothing. */\nexport const DEFAULT_EDGE_STROKE: Stroke = {\n paint: { color: '#7ba7c7' },\n width: 2,\n markerEnd: 'arrow',\n};\nconst DEFAULT_ROUTER = 'straight';\nconst PREVIEW_STROKE: Stroke = { paint: { color: '#7ba7c7' }, width: 2, dash: [4, 4] };\n\ninterface ConnectScratch {\n from: Port;\n current: Vec2;\n open: boolean;\n /** The deps bag as it was at `start`. The dispatcher builds it once, so\n * every later pump event carries `deps: {}` — an action that reads a dep at\n * commit time reads nothing and commits nothing, silently. */\n deps: InvocationCtx['deps'];\n}\n\n/**\n * The binding that starts a connect: a drag whose press landed on the port\n * layer's own chrome.\n *\n * The string form of `target` rather than a predicate, because it ranks higher\n * in specificity — a bare `{ kind: 'drag' }` on the select tool cannot outrank\n * it, so no tool needs a predicate of its own to keep out of the way.\n */\nexport function connectBinding(actionId: string = CONNECT_ACTION_ID): GestureBinding {\n return {\n spec: { kind: 'drag', target: `affordance:${PORT_AFFORDANCE_KIND}` },\n actionId,\n };\n}\n\n/** The action id that absorbs a press on a port. */\nexport const GRAB_PORT_ACTION_ID = 'diagram.grabPort';\n\n/**\n * Absorbs a press on a port, and does nothing else.\n *\n * A port claims the press **protocol**, not one gesture in it: `pointerDown`,\n * `click` and `drag` are a single claimable `'pointer'` token, and an exclusive\n * claim bars every binding whose target does not consult the affordance. So a\n * bundle that binds only `drag` leaves the pointerdown with nowhere to go, and\n * the dispatcher drops the press — the drag it would have grown into never\n * happens. Absorbing the press is also the behavior you want on its own: a\n * press on a port should not pick or deselect the node underneath it.\n */\nexport function grabPortAction(id: string = GRAB_PORT_ACTION_ID): Action {\n return {\n id,\n label: 'Grab port',\n group: 'diagram',\n invoker: { timing: 'immediate', run: () => {} },\n enabled: () => true as const,\n };\n}\n\n/** The two bindings that keep a port's claim from dropping the press. */\nexport function grabPortBindings(actionId: string = GRAB_PORT_ACTION_ID): GestureBinding[] {\n return [\n { spec: { kind: 'pointerDown', target: `affordance:${PORT_AFFORDANCE_KIND}` }, actionId },\n { spec: { kind: 'click', target: `affordance:${PORT_AFFORDANCE_KIND}` }, actionId },\n ];\n}\n\n/**\n * The default commit: one leaf node carrying the edge trait, added to\n * `deps.scene`. One `add` is one history entry, so the edge undoes in one.\n *\n * The edge lands on the **source node's** layer rather than the bottom one: an\n * edge between two nodes on a `wires` layer belongs on `wires`, and picking the\n * first layer in the stack would quietly move it somewhere the author did not\n * put its endpoints.\n */\nexport function commitEdgeToScene(edge: PendingEdge, ctx: InvocationCtx): void {\n const scene = ctx.deps['scene'] as Scene<unknown, string, unknown> | undefined;\n if (scene === undefined) return;\n const trait: DiagramEdge = {\n from: { port: edge.from.id },\n to: { port: edge.to.id },\n router: edge.router,\n };\n const source = scene.get(edge.from.nodeId as never);\n scene.add({\n kind: 'leaf',\n layer: source?.layer ?? scene.layers[0]!.id,\n pose: { x: 0, y: 0, width: 0, height: 0 } as never,\n // An edge runs *from* one node *to* another, and a plain line does not say\n // so. The arrowhead is an ordinary stroke marker, which is why nothing in\n // this package draws one.\n data: { diagram: trait, stroke: DEFAULT_EDGE_STROKE } as never,\n dependsOn: [edge.from.nodeId as never, edge.to.nodeId as never],\n // Without this the edge re-resolves on every dependency move and paints\n // nothing. `EDGE_DERIVE_PATH` rather than a fresh `edgeDerivePath()` so the\n // scene can find its registry key and the edge survives `toJSON`.\n derivePath: EDGE_DERIVE_PATH as never,\n });\n}\n\n/**\n * The `diagram.connect` action: an ongoing drag whose preview is an ephemeral\n * edge and whose commit is one op batch.\n *\n * A factory rather than a singleton because every input it needs — which nodes\n * are droppable, what counts as a legal pair, how an edge node is shaped — is\n * the consumer's, and this package has no scene at module scope. Same reason\n * `edgeDerivePath` and `diagramShape` are factories.\n */\nexport function createConnectAction<TPose>(opts: ConnectActionOptions<TPose>): Action {\n const {\n id = CONNECT_ACTION_ID,\n canConnect = defaultCanConnect,\n snapRadius = DEFAULT_SNAP,\n router: routerKey = DEFAULT_ROUTER,\n commit = commitEdgeToScene,\n stroke = PREVIEW_STROKE,\n } = opts;\n const routers = opts.routers ?? ROUTERS;\n const portOpts = {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n };\n const route: Router = routers[routerKey] ?? routers['straight'] ?? ROUTERS['straight']!;\n\n /** The port the pointer is over and may legally land on, or `null`.\n *\n * `canConnect` is applied here rather than at commit, so an illegal port is\n * not a candidate at all: the edge does not snap to it and releasing over it\n * does nothing. */\n function targetPort(from: Port, at: Vec2): Port | null {\n let best: Port | null = null;\n let bestD2 = snapRadius * snapRadius;\n for (const { node, pose } of opts.participants()) {\n for (const port of portsOf(node, pose, portOpts)) {\n if (!canConnect(from, port)) continue;\n const d2 = (port.point.x - at.x) ** 2 + (port.point.y - at.y) ** 2;\n if (d2 <= bestD2) {\n bestD2 = d2;\n best = port;\n }\n }\n }\n return best;\n }\n\n /** The end the edge currently runs to: a snapped port, or the bare pointer.\n * A free end is a port with no facing, so a router aims straight at it. */\n function endAt(from: Port, at: Vec2): { port: Port | null; end: Port } {\n const port = targetPort(from, at);\n return {\n port,\n end: port ?? { id: '', nodeId: '', point: at, normal: null },\n };\n }\n\n return {\n id,\n label: 'Connect',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const pressed = portScratchOf(ctx.drag?.affordance);\n // Not a port press. The binding spec already said only port presses\n // reach here, so this is the runtime backstop, not the gate — and an\n // empty handle is how the dispatcher is told to fall through.\n if (pressed === null) return {};\n const scratch: ConnectScratch = {\n from: pressed.port,\n current: { x: ctx.world.x, y: ctx.world.y },\n open: true,\n deps: ctx.deps,\n };\n\n return {\n kind: 'diagram-connect',\n onMove(moveCtx: InvocationCtx): void {\n scratch.current = { x: moveCtx.world.x, y: moveCtx.world.y };\n },\n overlay(): OngoingOverlay | null {\n if (!scratch.open) return null;\n const { end } = endAt(scratch.from, scratch.current);\n const points = route({ from: scratch.from, to: end, waypoints: [] });\n if (points.length < 2) return null;\n const cmd: DrawCommand = {\n kind: 'path',\n path: polylineFromPoints(points as { x: number; y: number }[]),\n stroke,\n };\n return { kind: 'commands', commands: [cmd], space: 'world' };\n },\n onEnd(endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n scratch.open = false;\n if (reason === 'cancel') return;\n const { port } = endAt(scratch.from, { x: endCtx.world.x, y: endCtx.world.y });\n if (port === null) return;\n // World and modifiers from the release; deps from the press.\n commit(\n { from: scratch.from, to: port, router: routerKey },\n { ...endCtx, deps: scratch.deps },\n );\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * The port affordance, composed into a layer and pointed at a scene.\n *\n * Two conveniences over {@link createPortAffordance}, both of which encode a\n * rule that is easy to get wrong rather than merely saving a line.\n */\nimport {\n composeAffordanceLayer,\n effectivePose,\n type RenderLayer,\n} from '@weasel-js/core';\nimport {\n PORT_LAYER_ID,\n createPortAffordance,\n type ParticipantSource,\n type PortAffordanceOptions,\n} from './portAffordance';\nimport type { GraphNodeLike, GraphSource } from './graph';\n\n/** The minimum a participant source needs from a scene. Narrower than `Scene`\n * so a consumer can pass anything that answers these two. */\nexport interface ParticipantScene<TPose> {\n renderOrderNodes(): readonly {\n id: string;\n kind: 'leaf' | 'container';\n data: unknown;\n pose: TPose;\n dependsOn?: readonly string[] | 'children';\n }[];\n readonly overrides: { get(id: string): { pose?: TPose } | undefined };\n get(id: string): unknown;\n childrenOf(id: string): readonly string[];\n}\n\n/**\n * Every node in `scene`, at the pose it is **painted** at.\n *\n * `effectivePose`, not `node.pose`: an override is what a gesture is currently\n * showing, and a port that answers from the document pose while its node is\n * mid-drag sits somewhere the user can see the node is not. Nodes that carry no\n * participant trait cost one reader call each and contribute no regions.\n *\n * One source answers both the ports and the graph — `GraphSource` is a\n * `ParticipantSource` that also carries `dependsOn`, which is where an edge's\n * two endpoints live.\n */\nexport function sceneParticipants<TPose>(\n scene: ParticipantScene<TPose>,\n): GraphSource<TPose> {\n return function* () {\n for (const node of scene.renderOrderNodes()) {\n yield {\n node: node as GraphNodeLike,\n pose: effectivePose(scene as never, node as never) as TPose,\n };\n }\n };\n}\n\n/**\n * The composed layer, ready for `CanvasExtensionApi.registerLayer` — the only\n * attach route that is hit-tested. Handing this to `SceneCanvas`'s `layers`\n * prop, or to a `Contribution.overlay`, paints the ports and makes none of them\n * grabbable.\n *\n * The cast is `composeAffordanceLayer` typing its data slot as `ChromeState`\n * while the layer registry takes `RenderLayer<unknown>`; both are handed the\n * same live `CanvasHelpers` envelope at runtime.\n */\nexport function portLayer<TPose>(\n participants: ParticipantSource<TPose>,\n opts: PortAffordanceOptions<TPose> = {},\n): RenderLayer<unknown> & { hitTest: NonNullable<RenderLayer<unknown>['hitTest']> } {\n return composeAffordanceLayer(\n opts.id ?? PORT_LAYER_ID,\n 'Diagram ports',\n [createPortAffordance(participants, opts)],\n ) as unknown as RenderLayer<unknown> & { hitTest: NonNullable<RenderLayer<unknown>['hitTest']> };\n}\n","/**\n * The plugin as a `Contribution` bundle — one object a consumer hands to\n * `<SceneCanvas ambient={…}>`.\n *\n * **Ambient, not a tool.** Connect is not a mode the author enters: a port is\n * grabbable whatever tool is active, which is the same reason `@weasel-js/hud`\n * ships `eligibility: { claimed: true }`. `claimed` is what makes the bundle\n * live for a press the port layer's affordance claimed, and dormant otherwise.\n *\n * **The layer is not in here, on purpose.** `Contribution.overlay` is painted\n * and never hit-tested — only `CanvasExtensionApi.registerLayer` gets a\n * `hitTest` call. Shipping the port layer as an overlay would paint every port\n * and make none of them grabbable, which is exactly the state this arc started\n * from. {@link diagramPorts} hands back the bundle and the layer together so\n * the two cannot be wired half-way.\n */\nimport type { Contribution, RenderLayer } from '@weasel-js/core';\nimport {\n CONNECT_ACTION_ID,\n connectBinding,\n createConnectAction,\n grabPortAction,\n grabPortBindings,\n type ConnectActionOptions,\n} from './connect';\nimport { portLayer } from './portLayer';\nimport type { PortAffordanceOptions } from './portAffordance';\n\nexport { CONNECT_ACTION_ID };\n\nexport interface DiagramContributionOptions<TPose>\n extends ConnectActionOptions<TPose>, PortAffordanceOptions<TPose> {}\n\n/** The bundle: the connect action and the one binding that reaches it. */\nexport function createDiagramContribution<TPose>(\n opts: DiagramContributionOptions<TPose>,\n): Contribution {\n const actionId = opts.id ?? CONNECT_ACTION_ID;\n return {\n id: 'weasel-diagram',\n eligibility: { claimed: true },\n actions: [createConnectAction({ ...opts, id: actionId }), grabPortAction()],\n bindings: [connectBinding(actionId), ...grabPortBindings()],\n };\n}\n\n/**\n * Both halves of the port affordance: the layer to `registerLayer`, and the\n * contribution to pass as `ambient`.\n *\n * They are returned together because attaching one without the other fails\n * quietly — the layer alone paints ports that start no gesture, and the\n * contribution alone binds an affordance kind nothing ever reports.\n */\nexport function diagramPorts<TPose>(opts: DiagramContributionOptions<TPose>): {\n layer: RenderLayer<unknown>;\n contribution: Contribution;\n} {\n return {\n layer: portLayer(opts.participants, opts),\n contribution: createDiagramContribution(opts),\n };\n}\n","/**\n * `Graph` — the adjacency index a layout runs over.\n *\n * The scene is the document, so there is no second graph kept in sync with it:\n * this one is built from the scene on demand, used, and thrown away. Rebuilding\n * per layout invocation is deliberate — a maintained index is a cache to\n * invalidate on every add, delete, reparent and `dependsOn` edit, and layout is\n * not on the hot path. Measure before changing that.\n *\n * A node's *identity* is its id and its *size* is its bounds; where it currently\n * sits is here too, because a re-layout that ignores where things already are\n * scrambles a diagram the author has arranged.\n */\nimport { AUTO_POSE_DESCRIPTOR, type PoseProjection } from '@weasel-js/core';\nimport { diagramEdgeOf } from './edge';\nimport type { Bounds } from './outline';\nimport { diagramNodeOf, type DiagramNodeLike, type DiagramNodeReader } from './trait';\n\n/** A scene node as the graph reads it. `dependsOn` is what an edge's two\n * endpoints are: the edge trait names *ports*, and the nodes those ports are\n * on are the dependencies the derivation already runs on. */\nexport interface GraphNodeLike extends DiagramNodeLike {\n dependsOn?: readonly string[] | 'children';\n}\n\n/** Where the graph gets its nodes. The same thunk shape the port affordance\n * takes, so one source answers both. */\nexport type GraphSource<TPose> = () => Iterable<{ node: GraphNodeLike; pose: TPose }>;\n\n/** One participant. */\nexport interface GraphNode {\n id: string;\n /** Where it is now, in world coordinates. */\n bounds: Bounds;\n /** Layout must not move it. */\n pinned: boolean;\n}\n\n/** One connection. `id` is the edge node's own id, so a caller can go back to\n * the scene for its trait. */\nexport interface GraphEdge {\n id: string;\n from: string;\n to: string;\n}\n\n/**\n * Nodes, edges, and the two adjacency reads a layout needs.\n *\n * Every list is in source order — render order, when the source is a scene —\n * which is what a layout's tiebreaks resolve against. There is no RNG anywhere\n * downstream of this, and this is where that starts.\n */\nexport interface Graph {\n readonly nodes: readonly GraphNode[];\n readonly edges: readonly GraphEdge[];\n node(id: string): GraphNode | undefined;\n /** Edges leaving `id`, in source order. */\n outgoing(id: string): readonly GraphEdge[];\n /** Edges arriving at `id`, in source order. */\n incoming(id: string): readonly GraphEdge[];\n}\n\nexport interface BuildGraphOptions<TPose> {\n read?: DiagramNodeReader;\n geometry?: PoseProjection<TPose>;\n}\n\n/**\n * Read a graph out of a source of scene nodes.\n *\n * A node is an edge if it carries the edge trait and names exactly two\n * dependencies; a participant if the reader hands back a `DiagramNode`;\n * neither, and it is not in the diagram at all. An edge whose endpoints are not\n * both participants is dropped — a dangling edge should not be ranking\n * anything.\n */\nexport function buildGraph<TPose>(\n source: GraphSource<TPose>,\n opts: BuildGraphOptions<TPose> = {},\n): Graph {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>);\n const nodes: GraphNode[] = [];\n const byId = new Map<string, GraphNode>();\n const candidates: GraphEdge[] = [];\n\n for (const { node, pose } of source()) {\n if (diagramEdgeOf(node) !== null) {\n const deps = node.dependsOn;\n if (Array.isArray(deps) && deps.length === 2) {\n candidates.push({ id: node.id, from: deps[0]!, to: deps[1]! });\n }\n continue;\n }\n const trait = diagramNodeOf(node, opts.read);\n if (trait === null) continue;\n const entry: GraphNode = {\n id: node.id,\n bounds: geometry.getBounds(pose),\n pinned: trait.pinned === true,\n };\n nodes.push(entry);\n byId.set(entry.id, entry);\n }\n\n const edges = candidates.filter((e) => byId.has(e.from) && byId.has(e.to));\n const out = new Map<string, GraphEdge[]>();\n const into = new Map<string, GraphEdge[]>();\n for (const edge of edges) {\n push(out, edge.from, edge);\n push(into, edge.to, edge);\n }\n\n const NONE: readonly GraphEdge[] = Object.freeze([]);\n return {\n nodes,\n edges,\n node: (id) => byId.get(id),\n outgoing: (id) => out.get(id) ?? NONE,\n incoming: (id) => into.get(id) ?? NONE,\n };\n}\n\nfunction push(index: Map<string, GraphEdge[]>, key: string, edge: GraphEdge): void {\n const list = index.get(key);\n if (list === undefined) index.set(key, [edge]);\n else list.push(edge);\n}\n","/**\n * Layout: where the participants go.\n *\n * A layout is a pure function of the graph — no scene, no ops, no history. It\n * hands back the new top-left for every node that **moves**, and a node already\n * standing where the layout wants it is simply absent from the answer. That is\n * what makes re-running a layout free rather than destructive, and it is the\n * property the idempotence test asserts.\n *\n * Three rules keep re-layout non-destructive, and all three live here rather\n * than in each algorithm:\n *\n * - **No RNG anywhere.** Every tiebreak falls back to the graph's own node\n * order, which is the source's order — render order, for a scene.\n * - **Within-rank order is seeded from where the nodes already are**, read\n * off the cross axis, rather than from crossing-minimization. An author who\n * dragged two boxes into an order gets that order back.\n * - **A pin set nothing moves.** Pinned nodes are never in the result, and\n * the rest of the layout is translated to sit around them.\n *\n * `layered` and `tree` are idempotent by construction: the second run reads the\n * order the first run produced and computes the same slots. `force` is an\n * iterative relaxation and makes no such claim — re-running it keeps relaxing.\n */\nimport type { Vec2 } from '@weasel-js/core';\nimport type { Graph, GraphNode } from './graph';\nimport type { Bounds } from './outline';\n\n/** Which way the ranks stack. `force` ignores it. */\nexport type LayoutDirection = 'down' | 'up' | 'right' | 'left';\n\nexport interface LayoutOptions {\n /** Default `'down'`. */\n direction?: LayoutDirection;\n /** Between neighbors within a rank, in world units. Default 48. */\n nodeGap?: number;\n /** Between one rank and the next. Default 96. */\n rankGap?: number;\n /** Ids layout must not move, on top of whatever carries `pinned: true`. */\n pin?: Iterable<string>;\n /** How far a node has to move to be worth moving, in world units. Default\n * `1e-6` — a float-noise floor, not a snapping quantum. Raise it to let a\n * `force` pass that has stopped doing anything useful commit nothing. */\n tolerance?: number;\n}\n\n/** The new top-left for each node that moves. A node that is already there is\n * absent, so an empty result means \"nothing to do\". */\nexport type LayoutResult = ReadonlyMap<string, Vec2>;\n\n/** Every layout in this package has this shape, and so does a consumer's. */\nexport type LayoutFn = (graph: Graph, opts?: LayoutOptions) => LayoutResult;\n\nexport const DEFAULT_NODE_GAP = 48;\nexport const DEFAULT_RANK_GAP = 96;\nconst DEFAULT_TOLERANCE = 1e-6;\n\n/** Which world axis carries ranks, which carries within-rank order, and\n * whether ranks grow toward positive world coordinates. */\nexport interface LayoutAxes {\n rank: 'x' | 'y';\n cross: 'x' | 'y';\n /** `-1` for `'up'` and `'left'`, where the canonical frame is mirrored. */\n sign: 1 | -1;\n}\n\nexport function axesFor(direction: LayoutDirection = 'down'): LayoutAxes {\n switch (direction) {\n case 'up':\n return { rank: 'y', cross: 'x', sign: -1 };\n case 'right':\n return { rank: 'x', cross: 'y', sign: 1 };\n case 'left':\n return { rank: 'x', cross: 'y', sign: -1 };\n default:\n return { rank: 'y', cross: 'x', sign: 1 };\n }\n}\n\n/** A node's extent along one axis. */\nexport function extent(bounds: Bounds, axis: 'x' | 'y'): number {\n return axis === 'x' ? bounds.width : bounds.height;\n}\n\n/** A node's center along one axis — what within-rank order is seeded from. */\nexport function center(bounds: Bounds, axis: 'x' | 'y'): number {\n return axis === 'x' ? bounds.x + bounds.width / 2 : bounds.y + bounds.height / 2;\n}\n\n/** Every id layout must leave alone. */\nexport function pinnedSet(graph: Graph, opts: LayoutOptions = {}): Set<string> {\n const pinned = new Set<string>(opts.pin ?? []);\n for (const node of graph.nodes) {\n if (node.pinned) pinned.add(node.id);\n }\n return pinned;\n}\n\n/**\n * A placement in the canonical `(cross, rank)` frame, before it is turned into\n * world coordinates. `cross` and `rank` are the node's low corner along each.\n */\nexport interface Slot {\n cross: number;\n rank: number;\n}\n\n/**\n * Turn canonical slots into the positions to write.\n *\n * Three steps, in order: map the canonical frame onto the world axes the\n * direction names; translate the whole layout so it lands where the graph\n * already is; drop everything that is pinned or that would not move.\n *\n * The translation is what makes the layout non-destructive, and it is chosen so\n * that a second run lands on the same answer. With a pin, it is whatever keeps\n * the first pinned node exactly where it is. Without one, it is whatever puts\n * the layout's own bounding box where the graph's bounding box already starts —\n * which the first run then makes true, so the second run computes the same\n * translation and writes nothing.\n */\nexport function settle(\n graph: Graph,\n slots: ReadonlyMap<string, Slot>,\n opts: LayoutOptions = {},\n): LayoutResult {\n const axes = axesFor(opts.direction);\n const pinned = pinnedSet(graph, opts);\n const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE;\n\n const placed = new Map<string, Vec2>();\n for (const node of graph.nodes) {\n const slot = slots.get(node.id);\n if (slot === undefined) continue;\n const along = axes.sign === 1 ? slot.rank : -(slot.rank + extent(node.bounds, axes.rank));\n placed.set(\n node.id,\n axes.rank === 'y' ? { x: slot.cross, y: along } : { x: along, y: slot.cross },\n );\n }\n\n return translated(graph, placed, pinned, tolerance);\n}\n\n/**\n * {@link settle}'s second half, for a layout that already works in world\n * coordinates — `force` does, since the integrator moves points around rather\n * than filling slots.\n */\nexport function translated(\n graph: Graph,\n placed: ReadonlyMap<string, Vec2>,\n pinned: ReadonlySet<string>,\n tolerance = DEFAULT_TOLERANCE,\n): LayoutResult {\n const anchor = anchorDelta(graph, placed, pinned);\n const out = new Map<string, Vec2>();\n for (const node of graph.nodes) {\n const at = placed.get(node.id);\n if (at === undefined || pinned.has(node.id)) continue;\n const x = at.x + anchor.x;\n const y = at.y + anchor.y;\n if (Math.abs(x - node.bounds.x) <= tolerance && Math.abs(y - node.bounds.y) <= tolerance) {\n continue;\n }\n out.set(node.id, { x, y });\n }\n return out;\n}\n\nfunction anchorDelta(\n graph: Graph,\n placed: ReadonlyMap<string, Vec2>,\n pinned: ReadonlySet<string>,\n): Vec2 {\n for (const node of graph.nodes) {\n if (!pinned.has(node.id)) continue;\n const at = placed.get(node.id);\n if (at !== undefined) return { x: node.bounds.x - at.x, y: node.bounds.y - at.y };\n }\n let minCurX = Infinity;\n let minCurY = Infinity;\n let minNewX = Infinity;\n let minNewY = Infinity;\n for (const node of graph.nodes) {\n const at = placed.get(node.id);\n if (at === undefined) continue;\n minCurX = Math.min(minCurX, node.bounds.x);\n minCurY = Math.min(minCurY, node.bounds.y);\n minNewX = Math.min(minNewX, at.x);\n minNewY = Math.min(minNewY, at.y);\n }\n if (!Number.isFinite(minCurX)) return { x: 0, y: 0 };\n return { x: minCurX - minNewX, y: minCurY - minNewY };\n}\n\n/**\n * Lay a list of nodes out along the cross axis, in the order given, and hand\n * back each one's low corner plus the total span.\n *\n * Shared by `layered`'s ranks and `tree`'s sibling rows, which pack a row the\n * same way and differ only in what decides the order.\n */\nexport function packAcross(\n nodes: readonly GraphNode[],\n axis: 'x' | 'y',\n gap: number,\n): { at: Map<string, number>; span: number } {\n const at = new Map<string, number>();\n let cursor = 0;\n for (const node of nodes) {\n at.set(node.id, cursor);\n cursor += extent(node.bounds, axis) + gap;\n }\n return { at, span: nodes.length === 0 ? 0 : cursor - gap };\n}\n\n/** Order within a rank: where the nodes already sit on the cross axis, with\n * graph order breaking a tie. Never a comparison that could reverse between\n * two runs on the same input. */\nexport function seededOrder(\n nodes: readonly GraphNode[],\n axis: 'x' | 'y',\n indexOf: (id: string) => number,\n): GraphNode[] {\n return [...nodes].sort((a, b) => {\n const d = center(a.bounds, axis) - center(b.bounds, axis);\n return d !== 0 ? d : indexOf(a.id) - indexOf(b.id);\n });\n}\n\n/** Each node's position in `graph.nodes`, for tiebreaks. */\nexport function graphOrder(graph: Graph): (id: string) => number {\n const index = new Map<string, number>();\n graph.nodes.forEach((node, i) => index.set(node.id, i));\n return (id) => index.get(id) ?? Number.MAX_SAFE_INTEGER;\n}\n","/**\n * `force` — relaxation, for a graph with no direction to read it in.\n *\n * Seeded from where the nodes already are rather than from a fresh random\n * scatter: an author who has arranged half a diagram gets that arrangement\n * relaxed, not replaced. There is no RNG in it at all — two coincident nodes\n * are separated along a golden-angle spiral keyed to their index, which is what\n * a random jiggle is for elsewhere.\n *\n * The integrator is the kit's own `createSimulation`, the same one\n * `useSimulation` runs a frame at a time. Only the forces are local, and they\n * are the naive O(n²) kind — right for the tens-to-hundreds of nodes an\n * edge-per-scene-node diagram is already sized for, wrong for a 10k-node graph,\n * which wants d3-force's Barnes–Hut through `useSimulation` and its own render\n * layer.\n *\n * **This is the one layout that is not idempotent.** A relaxation re-run from\n * its own output keeps relaxing; `direction` means nothing to it. Pins and the\n * `tolerance` option are what keep a second pass from scrambling a settled\n * diagram.\n */\nimport { createSimulation, type SimulationForce, type SimulationNode } from '@weasel-js/core';\nimport type { Graph } from './graph';\nimport {\n center,\n pinnedSet,\n translated,\n type LayoutFn,\n type LayoutOptions,\n type LayoutResult,\n} from './layout';\n\nexport interface ForceOptions extends LayoutOptions {\n /** Ticks to run. Default 300 — one full cooling schedule. */\n iterations?: number;\n /** Rest length of an edge, in world units. Default 160. */\n linkDistance?: number;\n /** How hard an edge pulls, 0..1. Default 0.35. */\n linkStrength?: number;\n /** Pairwise repulsion. Negative repels; default -3000. */\n charge?: number;\n /** How hard the graph is held around its own centroid. Default 0.02. */\n gravity?: number;\n /** Clear space kept between two boxes, in world units. Default 24. */\n padding?: number;\n}\n\ninterface Body extends SimulationNode {\n id: string;\n /** Half the node's box, so separation can work on the shape the author sees\n * rather than on a point. */\n hw: number;\n hh: number;\n}\n\nconst DEFAULTS = {\n iterations: 300,\n linkDistance: 160,\n linkStrength: 0.35,\n charge: -3000,\n gravity: 0.02,\n padding: 24,\n} as const;\n\n/** The golden angle. Coincident nodes fan out along it, which spreads any\n * number of them without two landing on the same heading. */\nconst GOLDEN = Math.PI * (3 - Math.sqrt(5));\n/** How far the first coincident node is pushed, in world units. Small enough\n * to be invisible, large enough that the repulsion term is finite. */\nconst NUDGE = 0.5;\n\n/** Pairwise repulsion, applied to every pair once. */\nfunction charge(bodies: readonly Body[], strength: number): SimulationForce<Body> {\n return (alpha) => {\n for (let i = 0; i < bodies.length; i++) {\n const a = bodies[i]!;\n for (let j = i + 1; j < bodies.length; j++) {\n const b = bodies[j]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const d2 = dx * dx + dy * dy;\n if (d2 === 0) continue;\n const w = (strength * alpha) / d2;\n a.vx! += dx * w;\n a.vy! += dy * w;\n b.vx! -= dx * w;\n b.vy! -= dy * w;\n }\n }\n };\n}\n\n/** A spring per edge, pulling both ends toward `distance`. */\nfunction links(\n bodies: ReadonlyMap<string, Body>,\n graph: Graph,\n distance: number,\n strength: number,\n): SimulationForce<Body> {\n return (alpha) => {\n for (const edge of graph.edges) {\n const a = bodies.get(edge.from);\n const b = bodies.get(edge.to);\n if (a === undefined || b === undefined || a === b) continue;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const d = Math.hypot(dx, dy);\n if (d === 0) continue;\n const pull = ((d - distance) / d) * alpha * strength;\n a.vx! += dx * pull;\n a.vy! += dy * pull;\n b.vx! -= dx * pull;\n b.vy! -= dy * pull;\n }\n };\n}\n\n/**\n * Push overlapping boxes apart along whichever axis they overlap least.\n *\n * Charge alone is not enough: it treats a node as a point, so two wide boxes\n * whose centers are a comfortable distance apart still cover each other. This\n * works on the box, and it is not scaled by alpha — an overlap at the end of\n * the run is exactly as wrong as one at the start.\n */\nfunction separateBoxes(bodies: readonly Body[], padding: number): SimulationForce<Body> {\n return () => {\n for (let i = 0; i < bodies.length; i++) {\n const a = bodies[i]!;\n for (let j = i + 1; j < bodies.length; j++) {\n const b = bodies[j]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const gapX = a.hw + b.hw + padding - Math.abs(dx);\n const gapY = a.hh + b.hh + padding - Math.abs(dy);\n if (gapX <= 0 || gapY <= 0) continue;\n if (gapX < gapY) {\n const push = (Math.sign(dx) || 1) * gapX * 0.5;\n a.vx! -= push;\n b.vx! += push;\n } else {\n const push = (Math.sign(dy) || 1) * gapY * 0.5;\n a.vy! -= push;\n b.vy! += push;\n }\n }\n }\n };\n}\n\n/** A pull toward the seed centroid, so a component with nothing to hold it\n * does not drift off under pure repulsion. */\nfunction gravity(bodies: readonly Body[], at: { x: number; y: number }, strength: number): SimulationForce<Body> {\n return (alpha) => {\n for (const body of bodies) {\n body.vx! += (at.x - body.x) * strength * alpha;\n body.vy! += (at.y - body.y) * strength * alpha;\n }\n };\n}\n\n/**\n * The bodies and the force list, wound up and ready to tick.\n *\n * Shared by the one-shot `force` below and the live relaxation in `live.ts`,\n * which ticks it a frame at a time. Two copies of a force list drift, and the\n * only thing that would say so is the arrangement they produce.\n */\nexport interface ForceRelaxation {\n bodies: Body[];\n byId: Map<string, Body>;\n /** Ids the caller must not move: declared pins, held as `fx`/`fy`. */\n pinned: ReadonlySet<string>;\n sim: ReturnType<typeof createSimulation<Body>>;\n /** Where a body's node's top-left sits, given the body's center. */\n placed(): Map<string, { x: number; y: number }>;\n}\n\nexport function forceRelaxation(graph: Graph, opts: ForceOptions = {}): ForceRelaxation {\n const {\n linkDistance = DEFAULTS.linkDistance,\n linkStrength = DEFAULTS.linkStrength,\n charge: chargeStrength = DEFAULTS.charge,\n gravity: gravityStrength = DEFAULTS.gravity,\n padding = DEFAULTS.padding,\n } = opts;\n\n const pinned = pinnedSet(graph, opts);\n const bodies: Body[] = graph.nodes.map((node) => {\n const body: Body = {\n id: node.id,\n x: center(node.bounds, 'x'),\n y: center(node.bounds, 'y'),\n hw: node.bounds.width / 2,\n hh: node.bounds.height / 2,\n };\n // A pin is the integrator's own `fx`/`fy`, not a filter applied after the\n // fact: a pinned node has to hold its neighbors while they relax, not be\n // put back once they have finished relaxing around where it wasn't.\n if (pinned.has(node.id)) {\n body.fx = body.x;\n body.fy = body.y;\n }\n return body;\n });\n separate(bodies);\n\n const byId = new Map(bodies.map((b) => [b.id, b]));\n const centroid = {\n x: bodies.reduce((sum, b) => sum + b.x, 0) / bodies.length,\n y: bodies.reduce((sum, b) => sum + b.y, 0) / bodies.length,\n };\n\n const sim = createSimulation<Body>({\n nodes: bodies,\n forces: [\n charge(bodies, chargeStrength),\n links(byId, graph, linkDistance, linkStrength),\n gravity(bodies, centroid, gravityStrength),\n separateBoxes(bodies, padding),\n ],\n });\n\n return {\n bodies,\n byId,\n pinned,\n sim,\n placed() {\n const placed = new Map<string, { x: number; y: number }>();\n for (const node of graph.nodes) {\n const body = byId.get(node.id)!;\n placed.set(node.id, {\n x: body.x - node.bounds.width / 2,\n y: body.y - node.bounds.height / 2,\n });\n }\n return placed;\n },\n };\n}\n\nexport const force = (graph: Graph, opts: ForceOptions = {}): LayoutResult => {\n if (graph.nodes.length === 0) return new Map();\n const relaxation = forceRelaxation(graph, opts);\n relaxation.sim.tick(opts.iterations ?? DEFAULTS.iterations);\n return translated(graph, relaxation.placed(), relaxation.pinned, opts.tolerance);\n};\n\n/** `ForceOptions` only widens `LayoutOptions`, so this is a `LayoutFn` — but\n * declaring it as one would hide the extra options from every caller. */\nforce satisfies LayoutFn;\n\n/** Push coincident bodies apart, deterministically. Two nodes at exactly the\n * same point feel no repulsion from each other and stay stacked forever. A\n * pinned body is counted but never moved — a pin outranks this. */\nfunction separate(bodies: Body[]): void {\n const seen = new Map<string, number>();\n bodies.forEach((body, i) => {\n const key = `${body.x},${body.y}`;\n const nth = seen.get(key) ?? 0;\n seen.set(key, nth + 1);\n if (nth === 0 || body.fx != null || body.fy != null) return;\n const angle = GOLDEN * i;\n const radius = NUDGE * nth;\n body.x += Math.cos(angle) * radius;\n body.y += Math.sin(angle) * radius;\n });\n}\n","/**\n * `layered` — ranks running one way, nodes running across.\n *\n * The flowchart / pipeline layout: an edge points from one rank to the next, so\n * reading down the page is reading the order things happen in. Ranks come from\n * longest-path layering, which puts every node as far along as its deepest\n * predecessor allows.\n *\n * Cycles do not disqualify a graph. A depth-first walk in graph order names the\n * edges that close a cycle, layering ignores those, and they draw as edges\n * running back up the page — which is what a reader expects a loop to look\n * like. Which edges get named depends only on the node order, so it is the same\n * every run.\n *\n * This is not crossing-minimization: within a rank, nodes keep the order they\n * already have on the cross axis. An author who dragged two branches into an\n * order gets that order back, and re-running the layout is free.\n */\nimport type { Graph, GraphNode } from './graph';\nimport {\n DEFAULT_NODE_GAP,\n DEFAULT_RANK_GAP,\n axesFor,\n extent,\n graphOrder,\n packAcross,\n seededOrder,\n settle,\n type LayoutFn,\n type Slot,\n} from './layout';\n\n/** Edge ids that close a cycle, found by a depth-first walk in graph order. */\nexport function backEdges(graph: Graph): Set<string> {\n const back = new Set<string>();\n const done = new Set<string>();\n const onStack = new Set<string>();\n\n const walk = (id: string): void => {\n if (done.has(id)) return;\n onStack.add(id);\n for (const edge of graph.outgoing(id)) {\n if (onStack.has(edge.to)) back.add(edge.id);\n else walk(edge.to);\n }\n onStack.delete(id);\n done.add(id);\n };\n\n for (const node of graph.nodes) walk(node.id);\n return back;\n}\n\n/** Longest-path rank per node: one past its deepest predecessor. */\nexport function ranksOf(graph: Graph, back: ReadonlySet<string>): Map<string, number> {\n const ranks = new Map<string, number>();\n const resolving = new Set<string>();\n\n const rankOf = (id: string): number => {\n const known = ranks.get(id);\n if (known !== undefined) return known;\n // Only reachable if `back` missed an edge; guarding here keeps a bad\n // cycle-breaker from recursing forever rather than reporting a wrong rank.\n if (resolving.has(id)) return 0;\n resolving.add(id);\n let rank = 0;\n for (const edge of graph.incoming(id)) {\n if (back.has(edge.id)) continue;\n rank = Math.max(rank, rankOf(edge.from) + 1);\n }\n resolving.delete(id);\n ranks.set(id, rank);\n return rank;\n };\n\n for (const node of graph.nodes) rankOf(node.id);\n return ranks;\n}\n\nexport const layered: LayoutFn = (graph, opts = {}) => {\n const axes = axesFor(opts.direction);\n const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;\n const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;\n const order = graphOrder(graph);\n\n const ranks = ranksOf(graph, backEdges(graph));\n const byRank = new Map<number, GraphNode[]>();\n for (const node of graph.nodes) {\n const rank = ranks.get(node.id) ?? 0;\n const list = byRank.get(rank);\n if (list === undefined) byRank.set(rank, [node]);\n else list.push(node);\n }\n\n const rows = [...byRank.keys()].sort((a, b) => a - b);\n const packed = new Map<number, ReturnType<typeof packAcross>>();\n let widest = 0;\n for (const rank of rows) {\n const row = seededOrder(byRank.get(rank)!, axes.cross, order);\n const p = packAcross(row, axes.cross, nodeGap);\n packed.set(rank, p);\n widest = Math.max(widest, p.span);\n }\n\n const slots = new Map<string, Slot>();\n let along = 0;\n for (const rank of rows) {\n const row = byRank.get(rank)!;\n const p = packed.get(rank)!;\n const indent = (widest - p.span) / 2;\n const depth = Math.max(0, ...row.map((n) => extent(n.bounds, axes.rank)));\n for (const node of row) {\n slots.set(node.id, {\n cross: indent + p.at.get(node.id)!,\n // Centered in its rank's band, so a tall node does not push its\n // neighbors' edges off the line they read along.\n rank: along + (depth - extent(node.bounds, axes.rank)) / 2,\n });\n }\n along += depth + rankGap;\n }\n\n return settle(graph, slots, opts);\n};\n","/**\n * `tree` — a parent centered over the block its children occupy.\n *\n * The hierarchy layout: org charts, file trees, decision trees. Depth is the\n * rank axis, so every child sits one band past its parent, and a subtree is\n * packed as a solid block so two siblings' descendants never interleave.\n *\n * A graph that is not a tree still lays out. Roots are the nodes nothing points\n * at, in graph order; a node reachable from two parents belongs to whichever\n * the depth-first walk reaches first; and anything the walk never reaches — a\n * disconnected part, or a pure cycle — becomes a root of its own. So the answer\n * is always a forest, and which forest depends only on the node order.\n *\n * The block packing is deliberately not Reingold–Tilford: it never slides a\n * deep subtree under a shallow neighbor's overhang. That costs horizontal\n * space and buys an invariant an author can rely on — a subtree's extent is a\n * rectangle, and dragging one never lands it inside another.\n */\nimport type { Graph, GraphNode } from './graph';\nimport {\n DEFAULT_NODE_GAP,\n DEFAULT_RANK_GAP,\n axesFor,\n extent,\n graphOrder,\n seededOrder,\n settle,\n type LayoutFn,\n type Slot,\n} from './layout';\n\ninterface Forest {\n roots: GraphNode[];\n children: Map<string, GraphNode[]>;\n depth: Map<string, number>;\n}\n\n/** The forest a depth-first walk in graph order finds. Exported because \"which\n * node ended up whose child\" is the question anyone debugging a tree layout\n * asks first. */\nexport function forestOf(graph: Graph, crossAxis: 'x' | 'y'): Forest {\n const order = graphOrder(graph);\n const children = new Map<string, GraphNode[]>();\n const depth = new Map<string, number>();\n const roots: GraphNode[] = [];\n\n const claim = (node: GraphNode, at: number): void => {\n depth.set(node.id, at);\n const kids: GraphNode[] = [];\n for (const edge of graph.outgoing(node.id)) {\n if (edge.to === node.id || depth.has(edge.to)) continue;\n const child = graph.node(edge.to);\n if (child === undefined) continue;\n // Claimed on sight rather than inside the recursion, so two siblings\n // sharing a descendant cannot both take it.\n depth.set(child.id, at + 1);\n kids.push(child);\n }\n const ordered = seededOrder(kids, crossAxis, order);\n children.set(node.id, ordered);\n for (const child of ordered) claim(child, at + 1);\n };\n\n const rootish = graph.nodes.filter((node) =>\n graph.incoming(node.id).every((edge) => edge.from === node.id));\n for (const node of seededOrder(rootish, crossAxis, order)) {\n if (depth.has(node.id)) continue;\n roots.push(node);\n claim(node, 0);\n }\n // Whatever the walk could not reach: a disconnected part, or a component\n // every node of which is inside a cycle.\n for (const node of graph.nodes) {\n if (depth.has(node.id)) continue;\n roots.push(node);\n claim(node, 0);\n }\n\n return { roots, children, depth };\n}\n\nexport const tree: LayoutFn = (graph, opts = {}) => {\n const axes = axesFor(opts.direction);\n const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;\n const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;\n const { roots, children, depth } = forestOf(graph, axes.cross);\n\n const bands = new Map<number, number>();\n for (const node of graph.nodes) {\n const at = depth.get(node.id) ?? 0;\n bands.set(at, Math.max(bands.get(at) ?? 0, extent(node.bounds, axes.rank)));\n }\n const bandStart = new Map<number, number>();\n let along = 0;\n for (const at of [...bands.keys()].sort((a, b) => a - b)) {\n bandStart.set(at, along);\n along += bands.get(at)! + rankGap;\n }\n\n const slots = new Map<string, Slot>();\n\n /** How wide `node`'s whole subtree is on the cross axis: its children's\n * blocks side by side, or the node itself when that is wider. */\n const measured = new Map<string, number>();\n const measure = (node: GraphNode): number => {\n const known = measured.get(node.id);\n if (known !== undefined) return known;\n const kids = children.get(node.id) ?? [];\n let width = 0;\n for (const child of kids) width += measure(child);\n if (kids.length > 0) width += nodeGap * (kids.length - 1);\n const block = Math.max(extent(node.bounds, axes.cross), width);\n measured.set(node.id, block);\n return block;\n };\n\n /** Place `node`'s subtree with its block starting at `from`. */\n const place = (node: GraphNode, from: number): void => {\n const kids = children.get(node.id) ?? [];\n const block = measure(node);\n const width = kids.reduce((sum, k) => sum + measure(k), 0)\n + Math.max(0, kids.length - 1) * nodeGap;\n\n let cursor = from + (block - width) / 2;\n for (const child of kids) {\n place(child, cursor);\n cursor += measure(child) + nodeGap;\n }\n\n const own = extent(node.bounds, axes.cross);\n const at = depth.get(node.id) ?? 0;\n slots.set(node.id, {\n cross: from + (block - own) / 2,\n rank: bandStart.get(at)! + (bands.get(at)! - extent(node.bounds, axes.rank)) / 2,\n });\n };\n\n let cursor = 0;\n for (const root of roots) {\n place(root, cursor);\n cursor += measure(root) + nodeGap;\n }\n\n return settle(graph, slots, opts);\n};\n","/**\n * Running a layout against a scene: `LAYOUTS`, one batch of pose writes, and\n * the action that reaches both.\n *\n * The split is the point. A layout is a pure function of the graph and is\n * tested as one; `applyLayout` is the only thing that touches a scene, and it\n * writes every move inside a single `scene.batch`, so a re-layout is one undo\n * entry rather than one per node.\n */\nimport {\n translatePoseViaDescriptor,\n AUTO_POSE_DESCRIPTOR,\n type Action,\n type PoseProjection,\n type Scene,\n} from '@weasel-js/core';\nimport { force } from './force';\nimport { buildGraph, type GraphSource } from './graph';\nimport { layered } from './layered';\nimport { tree } from './tree';\nimport type { LayoutFn, LayoutOptions, LayoutResult } from './layout';\nimport type { DiagramNodeReader } from './trait';\n\n/** The layouts this package ships. A consumer's own go in the same shape. */\nexport const LAYOUTS: Readonly<Record<string, LayoutFn>> = Object.freeze({\n layered,\n tree,\n force,\n});\n\nexport interface ApplyLayoutOptions<TPose> {\n geometry?: PoseProjection<TPose>;\n /** The undo entry's name. Default `'Layout'`. */\n label?: string;\n}\n\n/**\n * Write a layout's answer to the scene, as one undoable batch.\n *\n * Returns how many nodes moved, which is zero for a layout that had nothing to\n * do — nothing is written and no history entry is pushed.\n *\n * Nodes are **translated**, never re-posed from the layout's numbers: a node's\n * pose can be a path or anything else a consumer wired, and only its own\n * descriptor knows how to move one.\n *\n * A participant that is a container takes its whole subtree along. `setPose`\n * does not cascade — poses are absolute — so a built body would otherwise walk\n * out from under its own label rows with every test green.\n */\nexport function applyLayout<TPose>(\n scene: Scene<unknown, string, TPose>,\n result: LayoutResult,\n opts: ApplyLayoutOptions<TPose> = {},\n): number {\n const poses = layoutPoses(scene, result, opts.geometry);\n if (poses.size === 0) return 0;\n scene.batch(opts.label ?? 'Layout', () => {\n for (const [id, pose] of poses) scene.setPose(id as never, pose);\n });\n // Participants, not the descendants they carried along: a caller asking how\n // much a layout did means the nodes it placed.\n let moved = 0;\n for (const id of result.keys()) if (poses.has(id)) moved++;\n return moved;\n}\n\n/**\n * The poses a layout result implies, without writing any of them: each moved\n * node translated to its new top-left, and its subtree translated with it.\n *\n * Split out because a *live* layout needs the same answer every frame and must\n * not write it — it publishes to the override channel and commits once. The\n * translation is measured from the node's document pose, which a run in flight\n * never changes, so a frame's answer does not depend on the frame before it.\n */\nexport function layoutPoses<TPose>(\n scene: Scene<unknown, string, TPose>,\n result: LayoutResult,\n geometry: PoseProjection<TPose> = AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>,\n): Map<string, TPose> {\n const out = new Map<string, TPose>();\n for (const [id, at] of result) {\n const node = scene.get(id as never);\n if (node === undefined) continue;\n const bounds = geometry.getBounds(node.pose);\n const dx = at.x - bounds.x;\n const dy = at.y - bounds.y;\n if (dx === 0 && dy === 0) continue;\n out.set(id, translatePoseViaDescriptor(node.pose, dx, dy, geometry));\n for (const descendant of subtreeOf(scene, id)) {\n const child = scene.get(descendant as never);\n if (child === undefined) continue;\n out.set(descendant, translatePoseViaDescriptor(child.pose, dx, dy, geometry));\n }\n }\n return out;\n}\n\nfunction subtreeOf<TPose>(scene: Scene<unknown, string, TPose>, id: string): string[] {\n const out: string[] = [];\n const stack = [...scene.childrenOf(id as never)];\n while (stack.length > 0) {\n const next = stack.pop()!;\n out.push(next);\n stack.push(...scene.childrenOf(next));\n }\n return out;\n}\n\n/** The default action id. */\nexport const LAYOUT_ACTION_ID = 'diagram.layout';\n\nexport interface LayoutActionOptions<TPose> {\n /** Where the graph is read from. The same thunk the port affordance takes. */\n source: GraphSource<TPose>;\n /** Default {@link LAYOUT_ACTION_ID}. */\n id?: string;\n label?: string;\n /** Which `<ActionBar group>` it lands in. Default `'diagram'`, alongside\n * connect — give a bar of its own a group of its own. */\n group?: string;\n /** A key in {@link LAYOUTS}, or a layout of the consumer's own. Default\n * `'layered'`. */\n algorithm?: string | LayoutFn;\n layout?: LayoutOptions;\n read?: DiagramNodeReader;\n geometry?: PoseProjection<TPose>;\n}\n\n/**\n * `diagram.layout` — rebuild the graph, run a layout, write the result.\n *\n * A factory rather than a singleton for the reason every other entry point in\n * this package is one: which nodes are in the diagram is the consumer's, and\n * this package has no scene at module scope.\n */\nexport function createLayoutAction<TPose>(opts: LayoutActionOptions<TPose>): Action {\n const algorithm = typeof opts.algorithm === 'function'\n ? opts.algorithm\n : LAYOUTS[opts.algorithm ?? 'layered'] ?? layered;\n const build = {\n ...(opts.read ? { read: opts.read } : {}),\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n };\n\n return {\n id: opts.id ?? LAYOUT_ACTION_ID,\n label: opts.label ?? 'Lay out diagram',\n group: opts.group ?? 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const scene = deps['scene'] as Scene<unknown, string, TPose> | undefined;\n if (scene === undefined) return;\n const graph = buildGraph(opts.source, build);\n applyLayout(scene, algorithm(graph, opts.layout), {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.label ? { label: opts.label } : {}),\n });\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * Layout you can watch, and push against.\n *\n * A live layout is a producer on core's `usePoseRun`: each frame it hands back\n * where the participants are, the run publishes that to the scene's override\n * channel, and the whole thing commits as one batch when it settles. Nothing\n * here writes the document.\n *\n * Two producers, because the two kinds of layout are different processes.\n * `force` is a relaxation whose target changes every tick. `layered` and `tree`\n * know where they are going before they start, so they ease into it.\n *\n * **A node another gesture owns is a pin.** The run reports it, `force` holds\n * it with `fx`/`fy` and relaxes its neighbors around it, and an eased layout\n * simply leaves it alone. Dragging a body mid-run is therefore the consumer's\n * ordinary move tool — this package contributes no gesture for it.\n */\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport {\n AUTO_POSE_DESCRIPTOR,\n usePoseRun,\n type EasingFn,\n type NodeId,\n type PoseProjection,\n type PoseRunCtx,\n type PoseRunStep,\n type Scene,\n} from '@weasel-js/core';\nimport { forceRelaxation, type ForceOptions } from './force';\nimport { buildGraph, type Graph, type GraphSource } from './graph';\nimport { layered } from './layered';\nimport { LAYOUTS, layoutPoses } from './layoutAction';\nimport { center, type LayoutFn, type LayoutOptions, type LayoutResult } from './layout';\nimport { tree } from './tree';\nimport type { DiagramNodeReader } from './trait';\n\n/** What a live producer is told, and what it answers with. */\nexport interface LiveLayoutCtx<TPose> {\n /** Nodes another gesture is moving, and where each is drawn. */\n pinned: ReadonlyMap<NodeId, TPose>;\n /** Frames since this run heated, starting at 0. */\n frame: number;\n}\n\n/** A frame of a live layout: where the participants are, and whether it is\n * finished. Positions are top-lefts, the same as a `LayoutResult`. */\nexport interface LiveLayoutFrame {\n result: LayoutResult;\n done: boolean;\n}\n\nexport type LiveLayoutProducer<TPose> = (ctx: LiveLayoutCtx<TPose>) => LiveLayoutFrame;\n\n/** How long an eased layout takes to arrive, in frames. Frame-counted rather\n * than timed, so a background tab resumes where it paused rather than\n * arriving the instant it comes back. */\nconst EASE_FRAMES = 24;\n\n/** Smooth start and end. Inlined rather than pulled from the animator, which\n * is a registry of running tweens, not a curve library. */\nconst easeInOut: EasingFn = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);\n\nexport interface ForceProducerOptions<TPose> extends ForceOptions {\n geometry?: PoseProjection<TPose>;\n /** Alpha held while something is pinned, so the graph keeps answering a drag\n * instead of freezing under it. Default 0.3. */\n dragAlpha?: number;\n}\n\n/**\n * A relaxation, one tick a frame, done when the simulation settles.\n *\n * The forces are `forceRelaxation`'s — the same ones the one-shot `force`\n * runs, wound up once here and ticked rather than run to completion.\n *\n * It does **not** re-anchor the way the one-shot does. That translation exists\n * so a single 300-tick jump does not move the diagram off where the author left\n * it; a live run cannot jump, every frame being one step from the last, and\n * gravity holds the graph around the centroid it was seeded from. Re-anchoring\n * per frame would also fight a drag: the anchor is measured from where the\n * nodes were, and a pinned node is deliberately somewhere else.\n */\nexport function forceProducer<TPose>(\n graph: Graph,\n opts: ForceProducerOptions<TPose> = {},\n): LiveLayoutProducer<TPose> {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseProjection<TPose>);\n const relaxation = forceRelaxation(graph, opts);\n const dragAlpha = opts.dragAlpha ?? 0.3;\n\n return ({ pinned }) => {\n for (const node of graph.nodes) {\n const body = relaxation.byId.get(node.id);\n if (body === undefined) continue;\n const held = pinned.get(node.id as NodeId);\n if (held !== undefined) {\n // A dragged node holds its neighbors while they relax, which is `fx` /\n // `fy` on the integrator rather than a correction applied afterward.\n const bounds = geometry.getBounds(held);\n body.fx = center(bounds, 'x');\n body.fy = center(bounds, 'y');\n } else if (!relaxation.pinned.has(node.id)) {\n delete body.fx;\n delete body.fy;\n }\n }\n // A pin is a live edit, so the run keeps its temperature up until the\n // pointer lets go.\n relaxation.sim.alphaTarget(pinned.size > 0 ? dragAlpha : 0);\n relaxation.sim.tick();\n return { result: relaxation.placed(), done: relaxation.sim.isSettled() };\n };\n}\n\nexport interface EasedProducerOptions {\n layout?: LayoutOptions;\n /** Frames to arrive in. Default 24. */\n frames?: number;\n easing?: EasingFn;\n}\n\n/**\n * A layout that knows its destination, walked into place.\n *\n * The target is computed once, from the graph as it stood when the run heated;\n * each frame is that target scaled by the easing curve, measured from where the\n * nodes started. A pinned node is dropped from the target rather than fought\n * over.\n */\nexport function easedProducer<TPose>(\n graph: Graph,\n algorithm: LayoutFn,\n opts: EasedProducerOptions = {},\n): LiveLayoutProducer<TPose> {\n const frames = opts.frames ?? EASE_FRAMES;\n const easing = opts.easing ?? easeInOut;\n const target = algorithm(graph, opts.layout);\n const from = new Map<string, { x: number; y: number }>();\n for (const node of graph.nodes) from.set(node.id, { x: node.bounds.x, y: node.bounds.y });\n\n return ({ pinned, frame }) => {\n const t = Math.min((frame + 1) / frames, 1);\n const u = easing(t);\n const result = new Map<string, { x: number; y: number }>();\n for (const [id, to] of target) {\n if (pinned.has(id as NodeId)) continue;\n const start = from.get(id);\n if (start === undefined) continue;\n result.set(id, {\n x: start.x + (to.x - start.x) * u,\n y: start.y + (to.y - start.y) * u,\n });\n }\n return { result, done: t >= 1 };\n };\n}\n\nexport interface UseLiveLayoutOptions<TPose> {\n scene: Scene<unknown, string, TPose>;\n /** Where the graph is read from. The same thunk the port affordance takes. */\n source: GraphSource<TPose>;\n /** A key in `LAYOUTS`, or a layout of the consumer's own. `'force'` relaxes\n * continuously; anything else eases to its answer. Default `'force'`. */\n algorithm?: string | LayoutFn;\n layout?: LayoutOptions;\n force?: ForceOptions;\n /** Frames an eased layout takes to arrive. Default 24. */\n frames?: number;\n easing?: EasingFn;\n read?: DiagramNodeReader;\n geometry?: PoseProjection<TPose>;\n /** The undo entry's name. Default `'Layout'`. */\n label?: string;\n /** Fires once the run has settled or been stopped and its poses are in the\n * document, with how many participants moved. */\n onSettle?: (moved: number) => void;\n /** Whether a node or edge appearing or disappearing re-heats the run.\n * Default true — a diagram that ignores a new edge looks broken. */\n reheatOnGraphChange?: boolean;\n /** Clock injection, for tests. Defaults to `requestAnimationFrame`. */\n requestFrame?: (cb: (t: number) => void) => number;\n cancelFrame?: (handle: number) => void;\n}\n\nexport interface LiveLayout {\n /** Heat and run. Idempotent while running. */\n start(): void;\n /** Finish now: commit where the nodes stand. */\n stop(): void;\n /** Abandon: the document keeps the poses it had. */\n cancel(): void;\n /** Rebuild the graph and run again from where the nodes are now. */\n restart(): void;\n isRunning(): boolean;\n}\n\n/** The shape of a graph, as a string that changes when a node or edge does. */\nfunction shapeOf(graph: Graph): string {\n const nodes = graph.nodes.map((n) => n.id).sort().join(',');\n const edges = graph.edges.map((e) => `${e.from}>${e.to}`).sort().join(',');\n return `${nodes}|${edges}`;\n}\n\n/**\n * Run a layout live against a scene.\n *\n * The returned handle is stable. Dragging a participant while it runs needs no\n * wiring: the consumer's move tool publishes an override, and the run treats\n * that as a pin.\n */\nexport function useLiveLayout<TPose>(opts: UseLiveLayoutOptions<TPose>): LiveLayout {\n const optsRef = useRef(opts);\n optsRef.current = opts;\n\n const producer = useRef<LiveLayoutProducer<TPose> | null>(null);\n const producerFrame = useRef(0);\n const shape = useRef('');\n\n const build = useCallback((): void => {\n const o = optsRef.current;\n const graph = buildGraph(o.source, {\n ...(o.read ? { read: o.read } : {}),\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n shape.current = shapeOf(graph);\n producerFrame.current = 0;\n const algorithm = o.algorithm ?? 'force';\n if (algorithm === 'force') {\n producer.current = forceProducer<TPose>(graph, {\n ...o.layout, ...o.force,\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n return;\n }\n const fn = typeof algorithm === 'function' ? algorithm : LAYOUTS[algorithm] ?? layered;\n producer.current = easedProducer<TPose>(graph, fn, {\n ...(o.layout ? { layout: o.layout } : {}),\n ...(o.frames === undefined ? {} : { frames: o.frames }),\n ...(o.easing ? { easing: o.easing } : {}),\n });\n }, []);\n\n const step = useCallback((ctx: PoseRunCtx<TPose>): PoseRunStep<TPose> => {\n const o = optsRef.current;\n if (producer.current === null) return { poses: [], done: true };\n const { result, done } = producer.current({\n pinned: ctx.pinned,\n frame: producerFrame.current++,\n });\n // A pinned participant takes its subtree out of the frame with it. The run\n // skips the participant itself, but its rows and labels are ids of their\n // own — left in, they would be published from the pose the document still\n // holds while the gesture carries the box somewhere else.\n let placed = result;\n if (ctx.pinned.size > 0) {\n const held = new Map(result);\n for (const id of ctx.pinned.keys()) held.delete(id as string);\n placed = held;\n }\n const poses = layoutPoses(o.scene, placed, o.geometry);\n return { poses: [...poses] as [NodeId, TPose][], done };\n }, []);\n\n const run = usePoseRun<TPose>({\n scene: opts.scene,\n step,\n onCommit: (moved) => optsRef.current.onSettle?.(moved),\n ...(opts.label ? { label: opts.label } : {}),\n ...(opts.requestFrame ? { requestFrame: opts.requestFrame } : {}),\n ...(opts.cancelFrame ? { cancelFrame: opts.cancelFrame } : {}),\n });\n\n // A node or edge appearing or disappearing is a new problem, so the run\n // re-heats rather than finishing the one it started on.\n useEffect(() => {\n if (opts.reheatOnGraphChange === false) return;\n return opts.scene.subscribe(() => {\n if (!run.isRunning()) return;\n const o = optsRef.current;\n const graph = buildGraph(o.source, {\n ...(o.read ? { read: o.read } : {}),\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n if (shapeOf(graph) === shape.current) return;\n build();\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [opts.scene, opts.reheatOnGraphChange, run, build]);\n\n return useMemo<LiveLayout>(() => ({\n start() {\n if (run.isRunning()) return;\n build();\n run.start();\n },\n stop: () => { run.stop(); },\n cancel: () => { run.cancel(); },\n restart() {\n run.cancel();\n build();\n run.start();\n },\n isRunning: () => run.isRunning(),\n }), [run, build]);\n}\n\n/** The layouts that ease rather than relax, for a consumer choosing one. */\nexport const EASED_LAYOUTS: Readonly<Record<string, LayoutFn>> = Object.freeze({\n layered,\n tree,\n});\n","/**\n * The painter for a node whose trait names an `outline`.\n *\n * Registered the way every other trait's renderer is — a `NodeShapeEntry` with\n * a `matches` over the node's data — so a diagram body is picked, clipped and\n * area-selected by the same walk as everything else, and a participant that\n * already had a look of its own (a text block, an image, a path) keeps it by\n * naming no outline at all.\n *\n * Rows are **not** painted here. A built body's rows are ordinary scene nodes\n * under the container, so the kit's own text painter draws them and text\n * editing, selection and styling work on them without a special case.\n */\nimport {\n RECT_POSE_DESCRIPTOR,\n registerNodeShape,\n type FillStyle,\n type NodeShapeEntry,\n type PoseProjection,\n type Stroke,\n} from '@weasel-js/core';\nimport { outlinePath } from './outline';\nimport { diagramNodeOf, type DiagramNodeReader } from './trait';\n\nexport interface DiagramShapeOptions<TPose> {\n /** Distinguishes one registration from another, and is what the disposer\n * removes. Default `'diagram:outline'`. */\n id?: string;\n /** How the trait is read. Default: the node's own `data.diagram`. */\n read?: DiagramNodeReader;\n /** Reads the box the outline is built in. Default `RECT_POSE_DESCRIPTOR`. */\n geometry?: PoseProjection<TPose>;\n /** Painted when the node's data declares neither. */\n defaultFill?: FillStyle | null;\n defaultStroke?: Stroke | null;\n}\n\n/** The entry, for a consumer composing their own painter list. */\nexport function diagramShape<TPose>(\n opts: DiagramShapeOptions<TPose> = {},\n): NodeShapeEntry<unknown, TPose> {\n const geometry = opts.geometry ?? (RECT_POSE_DESCRIPTOR as PoseProjection<TPose>);\n const outlineOf = (node: { id: string; kind: 'leaf' | 'container'; data: unknown }) =>\n diagramNodeOf(node, opts.read)?.outline;\n\n return {\n id: opts.id ?? 'diagram:outline',\n matches: (node) => outlineOf(node) !== undefined,\n paint: (node, pose) => {\n const outline = outlineOf(node);\n if (outline === undefined) return [];\n const d = node.data as { fill?: FillStyle | null; stroke?: Stroke | null };\n const fill = d.fill === undefined ? opts.defaultFill : d.fill;\n const stroke = d.stroke === undefined ? opts.defaultStroke : d.stroke;\n return [{\n kind: 'path',\n path: outlinePath(outline, geometry.getBounds(pose)),\n ...(fill ? { fill } : {}),\n ...(stroke ? { stroke } : {}),\n }];\n },\n // The drawn boundary, so picking and clipping follow the diamond rather\n // than its bounding box.\n silhouette: (node, pose) => {\n const outline = outlineOf(node);\n return outline === undefined ? null : outlinePath(outline, geometry.getBounds(pose));\n },\n };\n}\n\n/**\n * Register {@link diagramShape}. Returns the disposer, and takes `'high'`\n * priority so a body outline wins over a `data.shape` or `data.path` the same\n * node may also carry.\n */\nexport function registerDiagramShape<TPose>(opts: DiagramShapeOptions<TPose> = {}): () => void {\n return registerNodeShape(diagramShape(opts), { priority: 'high' });\n}\n"]}
1
+ {"version":3,"sources":["../src/outline.ts","../src/onOutline.ts","../src/trait.ts","../src/ports.ts","../src/body.ts","../src/label.ts","../src/edge.ts","../src/portAffordance.ts","../src/connect.ts","../src/portLayer.ts","../src/contribution.ts","../src/graph.ts","../src/layout.ts","../src/force.ts","../src/layered.ts","../src/tree.ts","../src/layoutAction.ts","../src/live.ts","../src/shape.ts"],"names":["left","right","top","bottom","center","AUTO_POSE_DESCRIPTOR","push","cursor","translatePoseViaDescriptor"],"mappings":";;;;AAwBA,IAAM,IAAA,GAAO,GAAA;AAIb,IAAM,KAAA,GAAQ,kBAAA;AAIP,SAAS,WAAA,CAAY,SAAkB,MAAA,EAAsB;AAClE,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,EAAU,OAAO,OAAA;AACxC,EAAA,MAAM,EAAE,CAAA,EAAG,CAAA,EAAG,OAAO,CAAA,EAAG,MAAA,EAAQ,GAAE,GAAI,MAAA;AACtC,EAAA,IAAI,KAAK,CAAA,IAAK,CAAA,IAAK,CAAA,EAAG,OAAO,SAAS,CAAA,EAAG,CAAA,EAAG,IAAA,CAAK,GAAA,CAAI,GAAG,CAAC,CAAA,EAAG,KAAK,GAAA,CAAI,CAAA,EAAG,CAAC,CAAC,CAAA;AAE1E,EAAA,QAAQ,OAAA;AAAS,IACf,KAAK,MAAA;AACH,MAAA,OAAO,QAAA,CAAS,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC,CAAA;AAAA,IAE5B,KAAK,SAAA;AACH,MAAA,OAAO,iBAAA,CAAkB;AAAA,QACvB,EAAE,CAAA,EAAG,CAAA,GAAI,CAAA,GAAI,GAAG,C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,IACrF;AAAA,GACF;AACF;AAOO,SAAS,oBAAA,CAA4B,IAAA,GAAmC,EAAC,EAAe;AAC7F,EAAA,OAAO,kBAAkB,YAAA,CAAa,IAAI,GAAG,EAAE,QAAA,EAAU,QAAQ,CAAA;AACnE","file":"index.js","sourcesContent":["/**\n * The shapes a built body can wear, as paths in the node's bounds.\n *\n * These are the flowchart vocabulary — a decision is a diamond, an I/O step a\n * parallelogram, a terminator a stadium — plus `'rect'` for everything else and\n * a `Path` escape hatch for a shape the vocabulary does not have. The path is\n * built in world coordinates from the bounds it is given, the same way the\n * kit's own `clipFromPose` factories are.\n */\nimport { PathBuilder, polygonFromPoints, rectPath, type Path } from '@weasel-js/core';\n\n/** An axis-aligned box, in the shape `PoseDescriptor.getBounds` returns. */\nexport interface Bounds {\n x: number;\n y: number;\n width: number;\n height: number;\n}\n\n/** A named flowchart shape, or a path a consumer built themselves. */\nexport type Outline = 'rect' | 'diamond' | 'stadium' | 'parallelogram' | Path;\n\n/** How far a parallelogram's top edge leans past its bottom one, as a\n * fraction of the box's width. The flowchart convention. */\nconst LEAN = 0.2;\n\n/** Cubic approximation of a quarter circle. A stadium's ends are two of these\n * each, which is the same construction `ellipsePath` uses. */\nconst KAPPA = 0.5522847498307936;\n\n/** The path `outline` describes inside `bounds`. A zero-area box gives a\n * zero-area rect rather than a degenerate polygon. */\nexport function outlinePath(outline: Outline, bounds: Bounds): Path {\n if (typeof outline !== 'string') return outline;\n const { x, y, width: w, height: h } = bounds;\n if (w <= 0 || h <= 0) return rectPath(x, y, Math.max(w, 0), Math.max(h, 0));\n\n switch (outline) {\n case 'rect':\n return rectPath(x, y, w, h);\n\n case 'diamond':\n return polygonFromPoints([\n { x: x + w / 2, y },\n { x: x + w, y: y + h / 2 },\n { x: x + w / 2, y: y + h },\n { x, y: y + h / 2 },\n ]);\n\n case 'parallelogram': {\n // The lean is clamped so a narrow box cannot fold through itself.\n const lean = Math.min(w * LEAN, w / 2);\n return polygonFromPoints([\n { x: x + lean, y },\n { x: x + w, y },\n { x: x + w - lean, y: y + h },\n { x, y: y + h },\n ]);\n }\n\n case 'stadium':\n return stadiumPath(x, y, w, h);\n }\n}\n\n/** A rect with semicircular ends — the Minkowski sum of a segment and a disc,\n * which puts the flat edges along the box's *longer* axis. A tall box is a\n * pill standing up, not an ellipse. */\nfunction stadiumPath(x: number, y: number, w: number, h: number): Path {\n const r = Math.min(w, h) / 2;\n const k = r * KAPPA;\n const b = new PathBuilder();\n\n if (w >= h) {\n const left = x + r;\n const right = x + w - r;\n const top = y;\n const bottom = y + h;\n const midY = y + h / 2;\n return b\n .moveTo(left, top)\n .lineTo(right, top)\n .curveTo(right + k, top, x + w, midY - k, x + w, midY)\n .curveTo(x + w, midY + k, right + k, bottom, right, bottom)\n .lineTo(left, bottom)\n .curveTo(left - k, bottom, x, midY + k, x, midY)\n .curveTo(x, midY - k, left - k, top, left, top)\n .close()\n .build();\n }\n\n const top = y + r;\n const bottom = y + h - r;\n const left = x;\n const right = x + w;\n const midX = x + w / 2;\n return b\n .moveTo(right, top)\n .lineTo(right, bottom)\n .curveTo(right, bottom + k, midX + k, y + h, midX, y + h)\n .curveTo(midX - k, y + h, left, bottom + k, left, bottom)\n .lineTo(left, top)\n .curveTo(left, top - k, midX - k, y, midX, y)\n .curveTo(midX + k, y, right, top - k, right, top)\n .close()\n .build();\n}\n\n/**\n * The largest axis-aligned box a shape's content can occupy without leaving\n * the shape. Rows lay out in here, not in the bounds — a diamond's corners and\n * a parallelogram's lean are outside its own box, and a label placed against\n * the bounding box lands there and gets clipped away by the silhouette.\n *\n * Conservative rather than exact: the inscribed rect of a rhombus is exact,\n * and a stadium reports the flat span between its rounded ends, which gives up\n * a little height near them.\n */\nexport function contentBox(outline: Outline, bounds: Bounds): Bounds {\n if (typeof outline !== 'string') return bounds;\n const { x, y, width: w, height: h } = bounds;\n switch (outline) {\n case 'rect':\n return bounds;\n case 'diamond':\n // Half the width and half the height, centered — the inscribed rect.\n return { x: x + w / 4, y: y + h / 4, width: w / 2, height: h / 2 };\n case 'parallelogram': {\n const lean = Math.min(w * LEAN, w / 2);\n return { x: x + lean, y, width: Math.max(w - lean * 2, 0), height: h };\n }\n case 'stadium': {\n const r = Math.min(w, h) / 2;\n return w >= h\n ? { x: x + r, y, width: Math.max(w - r * 2, 0), height: h }\n : { x, y: y + r, width: w, height: Math.max(h - r * 2, 0) };\n }\n }\n}\n\n/**\n * The box whose {@link contentBox} is at least `content` — the inverse, for\n * sizing a node to what its rows measured.\n *\n * The stadium case is the only inexact one: its inset depends on the height it\n * is solving for, so it assumes the wide orientation and adds one height's\n * worth of end caps.\n */\nexport function boxForContent(\n outline: Outline,\n content: { width: number; height: number },\n): { width: number; height: number } {\n if (typeof outline !== 'string') return content;\n switch (outline) {\n case 'rect':\n return content;\n case 'diamond':\n return { width: content.width * 2, height: content.height * 2 };\n case 'parallelogram':\n return { width: content.width / (1 - LEAN * 2), height: content.height };\n case 'stadium':\n return { width: content.width + content.height, height: content.height };\n }\n}\n","/**\n * Moving a port from the node's bounding box onto the shape it is drawn as.\n *\n * A port is placed as a fraction of the node's bounds, which is what makes it\n * survive a resize. For a rect that is already on the outline; for anything\n * else it can be well outside the ink — a parallelogram's west port floats in\n * the gap beside its leaning edge, and an edge that ends there ends in empty\n * space. So the point is cast back onto the outline along the ray from the\n * node's center, which is the direction an edge leaves anyway.\n */\nimport { PATH_C, PATH_L, PATH_M, PATH_Q, PATH_Z, flattenCubic, type Path } from '@weasel-js/core';\nimport { outlinePath, type Bounds, type Outline } from './outline';\nimport type { Port } from './types';\n\n/** Curve flattening tolerance, in world units. Finer than a port is wide. */\nconst TOLERANCE = 0.25;\n\n/** The outline as a closed polyline: `[x0, y0, x1, y1, …]`. */\nexport function outlinePolyline(outline: Outline, bounds: Bounds): number[] {\n const path = outlinePath(outline, bounds);\n return flattenPath(path);\n}\n\nfunction flattenPath(path: Path): number[] {\n if (path.kind === 'rect') {\n const { x, y, width: w, height: h } = path;\n return [x, y, x + w, y, x + w, y + h, x, y + h, x, y];\n }\n const out: number[] = [];\n const { commands, coords } = path as { commands: Uint8Array; coords: Float32Array };\n let ci = 0;\n let cx = 0;\n let cy = 0;\n let sx = 0;\n let sy = 0;\n for (const cmd of commands) {\n if (cmd === PATH_M) {\n cx = coords[ci]!; cy = coords[ci + 1]!; ci += 2;\n sx = cx; sy = cy;\n out.push(cx, cy);\n } else if (cmd === PATH_L) {\n cx = coords[ci]!; cy = coords[ci + 1]!; ci += 2;\n out.push(cx, cy);\n } else if (cmd === PATH_C) {\n const x1 = coords[ci]!, y1 = coords[ci + 1]!;\n const x2 = coords[ci + 2]!, y2 = coords[ci + 3]!;\n const x3 = coords[ci + 4]!, y3 = coords[ci + 5]!;\n ci += 6;\n flattenCubic(cx, cy, x1, y1, x2, y2, x3, y3, TOLERANCE, out);\n cx = x3; cy = y3;\n } else if (cmd === PATH_Q) {\n // Elevated to a cubic rather than given its own flattener.\n const qx = coords[ci]!, qy = coords[ci + 1]!;\n const x3 = coords[ci + 2]!, y3 = coords[ci + 3]!;\n ci += 4;\n flattenCubic(\n cx, cy,\n cx + (2 / 3) * (qx - cx), cy + (2 / 3) * (qy - cy),\n x3 + (2 / 3) * (qx - x3), y3 + (2 / 3) * (qy - y3),\n x3, y3, TOLERANCE, out,\n );\n cx = x3; cy = y3;\n } else if (cmd === PATH_Z) {\n out.push(sx, sy);\n cx = sx; cy = sy;\n }\n }\n // Close it, so a ray leaving through the last edge still finds a crossing.\n if (out.length >= 2 && (out[0] !== out[out.length - 2] || out[1] !== out[out.length - 1])) {\n out.push(out[0]!, out[1]!);\n }\n return out;\n}\n\n/**\n * Where the ray from `center` through `point` last crosses `poly`, or `null`\n * when it never does.\n *\n * The *last* crossing rather than the first: a concave outline can be crossed\n * more than once, and the far side is the boundary an edge should attach to.\n */\nexport function rayHit(\n poly: readonly number[],\n center: { x: number; y: number },\n point: { x: number; y: number },\n): { x: number; y: number } | null {\n const dx = point.x - center.x;\n const dy = point.y - center.y;\n if (dx === 0 && dy === 0) return null;\n let bestT = -Infinity;\n let hit: { x: number; y: number } | null = null;\n for (let i = 0; i + 3 < poly.length; i += 2) {\n const ax = poly[i]!, ay = poly[i + 1]!;\n const bx = poly[i + 2]!, by = poly[i + 3]!;\n const ex = bx - ax;\n const ey = by - ay;\n const denom = dx * ey - dy * ex;\n if (denom === 0) continue;\n // t along the ray, u along the segment.\n const t = ((ax - center.x) * ey - (ay - center.y) * ex) / denom;\n const u = ((ax - center.x) * dy - (ay - center.y) * dx) / denom;\n if (t < 0 || u < 0 || u > 1) continue;\n if (t > bestT) {\n bestT = t;\n hit = { x: center.x + dx * t, y: center.y + dy * t };\n }\n }\n return hit;\n}\n\n/**\n * Every port moved onto `outline`. A port the ray misses — one at the node's\n * dead center, with no direction to cast along — is left where it was.\n */\nexport function portsOnOutline(\n ports: readonly Port[],\n outline: Outline,\n bounds: Bounds,\n): Port[] {\n if (bounds.width <= 0 || bounds.height <= 0) return [...ports];\n const poly = outlinePolyline(outline, bounds);\n const center = { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 };\n return ports.map((port) => {\n const hit = rayHit(poly, center, port.point);\n return hit === null ? port : { ...port, point: hit };\n });\n}\n","/**\n * Reading the `DiagramNode` trait off a scene node.\n *\n * Two ways to attach it, both of which this module's default reader answers:\n *\n * - **On the node.** `data.diagram` holds the trait. One node, one answer;\n * what a connect gesture writes when the author drags a new edge.\n * - **By kind.** A consumer declares once which data shapes take part, and\n * every matching node gets the trait without being stamped. This mirrors\n * `createNodeRouting` in the kit — a predicate over `data`, first match\n * wins — and is the shape to reach for when the participants are a class\n * of node rather than a hand-picked set.\n *\n * A reader is a plain function, so a consumer whose data lives somewhere else\n * entirely passes their own and never touches either form.\n */\nimport type { DiagramNode } from './types';\n\n/** The key on a node's `data` the default reader looks under. */\nexport const DIAGRAM_TRAIT_KEY = 'diagram';\n\n/** All a reader looks at. Deliberately not `SceneNode`: naming `TPose` there\n * would put it in a contravariant position for no gain, since nothing here\n * reads a pose. */\nexport interface DiagramNodeLike {\n id: string;\n kind: 'leaf' | 'container';\n data: unknown;\n}\n\n/** Answers \"is this node a diagram participant, and on what terms\" — `null`\n * for a node that takes no part. */\nexport type DiagramNodeReader = (node: DiagramNodeLike) => DiagramNode | null;\n\n/** One class of participant, declared once for every node whose data matches.\n * Mirrors `NodeRoutingEntry`. */\nexport interface DiagramNodeEntry {\n /** Unique within a reader; the same vocabulary as `NodeRoutingEntry.name`. */\n name: string;\n matches: (data: unknown) => boolean;\n /** The trait every matching node carries. A function when it varies with the\n * node's own data — a pipeline stage whose ports come from its rows. */\n trait: DiagramNode | ((data: unknown) => DiagramNode);\n}\n\n/** The trait on the node's own `data.diagram`, or `null`.\n *\n * An edge's trait lives under the same key, so `from` and `to` are what tells\n * the two apart. Without that test an edge reads as a participant declaring\n * no ports, and collects the four defaults on the degenerate pose an edge\n * carries — four grabbable ports in the middle of nowhere. */\nexport const dataKeyReader: DiagramNodeReader = (node) => {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const trait = (data as Record<string, unknown>)[DIAGRAM_TRAIT_KEY];\n if (trait === null || typeof trait !== 'object') return null;\n if ('from' in trait && 'to' in trait) return null;\n return trait as DiagramNode;\n};\n\n/**\n * A reader over declared kinds. A trait on the node's own data still wins, so\n * a single node can opt out of, or override, whatever its kind says.\n *\n * Throws on a duplicate `name`, for the reason `mergeContributions` does: a\n * class of node silently losing its ports is what this registry exists to make\n * loud.\n */\nexport function createDiagramNodes(entries: readonly DiagramNodeEntry[]): DiagramNodeReader {\n const seen = new Set<string>();\n for (const entry of entries) {\n if (seen.has(entry.name)) {\n throw new Error(`createDiagramNodes: duplicate entry name \"${entry.name}\"`);\n }\n seen.add(entry.name);\n }\n return (node) => {\n const own = dataKeyReader(node);\n if (own !== null) return own;\n for (const entry of entries) {\n if (!entry.matches(node.data)) continue;\n return typeof entry.trait === 'function' ? entry.trait(node.data) : entry.trait;\n }\n return null;\n };\n}\n\n/** The trait `node` carries, through `read` (default: its own `data.diagram`). */\nexport function diagramNodeOf(\n node: DiagramNodeLike,\n read: DiagramNodeReader = dataKeyReader,\n): DiagramNode | null {\n return read(node);\n}\n\n/** True when layout must leave this node where it is. */\nexport function isPinned(node: DiagramNodeLike, read?: DiagramNodeReader): boolean {\n return diagramNodeOf(node, read)?.pinned === true;\n}\n","/**\n * Where a node's ports are, in world coordinates.\n *\n * A port is placed in the node's **unrotated** bounds, then carried through\n * the pose's rotation — the same pivot every other kit reader uses, the AABB\n * center. Bounds come from the pose descriptor rather than from `pose.width`\n * and friends, so a node whose pose is a path, an ellipse or anything else a\n * consumer wired is connectable on the same terms as a rect.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n rotatePoint,\n type PoseDescriptor,\n type Vec2,\n} from '@weasel-js/core';\nimport { outlinePolyline, rayHit } from './onOutline';\nimport { diagramNodeOf, type DiagramNodeLike, type DiagramNodeReader } from './trait';\nimport type { Port, PortAnchor, PortSpec } from './types';\n\n/** The eight anchors almost everything wants, named the way a compass is. */\nexport const COMPASS = {\n nw: { u: 0, v: 0 },\n n: { u: 0.5, v: 0 },\n ne: { u: 1, v: 0 },\n e: { u: 1, v: 0.5 },\n se: { u: 1, v: 1 },\n s: { u: 0.5, v: 1 },\n sw: { u: 0, v: 1 },\n w: { u: 0, v: 0.5 },\n} as const satisfies Record<string, PortAnchor>;\n\n/**\n * What a node carrying no `ports` gets: the four edge midpoints of its own\n * bounds. Every node has bounds, so every node is connectable without saying\n * anything.\n */\nexport const DEFAULT_PORTS: readonly PortSpec[] = Object.freeze([\n { id: 'n', at: COMPASS.n },\n { id: 'e', at: COMPASS.e },\n { id: 's', at: COMPASS.s },\n { id: 'w', at: COMPASS.w },\n]);\n\nexport interface PortsOptions<TPose> {\n /** Reads the AABB a port is placed in, and the node's rotation. Defaults to\n * the kit's `AUTO_POSE_DESCRIPTOR`, which handles rect and path poses. */\n geometry?: PoseDescriptor<TPose>;\n /** How the `DiagramNode` trait is read off a node. */\n read?: DiagramNodeReader;\n}\n\n/**\n * The direction the anchor implies: away from the center of the bounds.\n *\n * `(2u-1, 2v-1)` is the anchor in a box that runs -1..1, which is exactly that\n * direction — an edge midpoint gets the axis-aligned normal, a corner gets the\n * diagonal. It is deliberately not scaled by the node's aspect: this is a\n * heading a router leaves along, not a point on the outline. A port at the\n * dead center has no direction, and says so.\n */\nfunction normalOf(at: PortAnchor): Vec2 | null {\n const x = at.u * 2 - 1;\n const y = at.v * 2 - 1;\n const len = Math.hypot(x, y);\n if (len === 0) return null;\n return { x: x / len, y: y / len };\n}\n\n/**\n * Every port on `node`, resolved against `pose`.\n *\n * Pass the pose the node is **painted** at — `effectivePose(scene, node)` —\n * not `node.pose`. A port that answers from the document pose while the node\n * is mid-drag puts an edge somewhere the user can see the node is not.\n */\nexport function portsOf<TPose>(\n node: DiagramNodeLike,\n pose: TPose,\n opts: PortsOptions<TPose> = {},\n): Port[] {\n const trait = diagramNodeOf(node, opts.read);\n if (trait === null) return [];\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const bounds = geometry.getBounds(pose);\n const rotation = geometry.getRotation?.(pose) ?? 0;\n const cx = bounds.x + bounds.width / 2;\n const cy = bounds.y + bounds.height / 2;\n // A port is anchored in the bounds so it survives a resize, but it has to\n // *sit* on the shape: a parallelogram's west anchor is in the gap beside its\n // leaning edge, and an edge ending there ends in empty space. Flattened once\n // per call, not once per port.\n const poly = trait.outline === undefined || bounds.width <= 0 || bounds.height <= 0\n ? null\n : outlinePolyline(trait.outline, bounds);\n\n return (trait.ports ?? DEFAULT_PORTS).map((spec) => {\n const anchored: Vec2 = {\n x: bounds.x + spec.at.u * bounds.width,\n y: bounds.y + spec.at.v * bounds.height,\n };\n const flat = (poly === null ? null : rayHit(poly, { x: cx, y: cy }, anchored)) ?? anchored;\n const normal = spec.normal === undefined ? normalOf(spec.at) : spec.normal;\n if (rotation === 0) {\n return { id: spec.id, nodeId: node.id, point: flat, normal, ...typeOf(spec) };\n }\n return {\n id: spec.id,\n nodeId: node.id,\n point: rotatePoint(flat.x, flat.y, cx, cy, rotation),\n // A direction rotates about the origin, not about the node's center.\n normal: normal === null ? null : rotatePoint(normal.x, normal.y, 0, 0, rotation),\n ...typeOf(spec),\n };\n });\n}\n\n/** One named port, or `undefined` when the node has no such port. */\nexport function portOf<TPose>(\n node: DiagramNodeLike,\n pose: TPose,\n portId: string,\n opts: PortsOptions<TPose> = {},\n): Port | undefined {\n return portsOf(node, pose, opts).find((p) => p.id === portId);\n}\n\n/** Spread rather than assigned, so a port with no type has no `type` key at\n * all — `exactOptionalPropertyTypes` rejects an explicit `undefined`. */\nfunction typeOf(spec: PortSpec): { type?: string } {\n return spec.type === undefined ? {} : { type: spec.type };\n}\n","/**\n * The optional body builder: what a node looks like when it should read as a\n * flowchart box or a visual-programming operator, rather than as whatever\n * scene node it already was.\n *\n * **The body measures a floor; the author sets the rest.** Rows measure to a\n * `{ minWidth, minHeight }` and the node's pose is the max of that and what\n * the author gave it. Adding a port row can grow a node; nothing here ever\n * shrinks one back. Because the pose stays authored data, resize, align,\n * distribute, guides, snapping and undo need no special case, and a node that\n * did not come from the builder just has whatever size it already had.\n *\n * Text measurement is a seam rather than an import: measuring needs a 2D\n * context, which a geometry module has no business owning. `canvasMeasure`\n * adapts the kit's own `measureText` for a caller that has one.\n */\nimport { boxForContent, contentBox, outlinePath, type Bounds, type Outline } from './outline';\nimport { COMPASS } from './ports';\nimport type { DiagramNode, PortSpec } from './types';\n\n/** One line of body content. */\nexport type Row =\n /** Text. `label` is the node's name; `field` is a named value. */\n | { kind: 'label'; text: string; style?: RowTextStyle }\n | { kind: 'field'; label: string; value: string; style?: RowTextStyle }\n /** A row that carries ports on its own left and right edges — the\n * visual-programming shape, where an operator's inputs line up with the\n * rows they feed. */\n | { kind: 'ports'; left?: readonly RowPort[]; right?: readonly RowPort[]; height?: number }\n /** Reserved space a consumer paints into. */\n | { kind: 'slot'; height: number; id?: string };\n\n/** A port declared on a row rather than on the node's perimeter. */\nexport interface RowPort {\n id: string;\n /** Label shown beside it, and what the row measures against. */\n label?: string;\n type?: string;\n}\n\n/** The subset of a text style the body measures against. Deliberately small:\n * a full `ResolvedTextStyle` belongs to whatever paints the row. */\nexport interface RowTextStyle {\n fontSize?: number;\n fontFamily?: string;\n bold?: boolean;\n}\n\n/** Measures one run of text. Returns its advance width and its line height. */\nexport type MeasureRowText = (text: string, style: RowTextStyle) => { width: number; height: number };\n\nexport interface BodySpec {\n outline: Outline;\n rows: readonly Row[];\n /** Space between the outline and its rows. Default 8. */\n padding?: number;\n /** Space between adjacent rows. Default 4. */\n gap?: number;\n}\n\n/** What {@link buildBody} emits: the `AddNodeSpec` fields it fills in. Named\n * structurally rather than imported so a consumer whose scene is typed\n * differently can still spread one. */\nexport interface BodyNodeSpec<TData, TLayer extends string, TPose> {\n kind: 'container' | 'leaf';\n layer: TLayer;\n pose: TPose;\n data: TData;\n id?: string;\n parent?: string;\n /** Set `false` on every leaf the builder emits: the innermost hit wins, so a\n * row that answers a press is a body that cannot be dragged. */\n pickable?: boolean;\n}\n\n/** The floor a body's content puts under its node's size. */\nexport interface BodyFloor {\n minWidth: number;\n minHeight: number;\n}\n\n/** Where one row landed, in the same frame as the bounds it was laid out in.\n * A `ports` row's own ports anchor to this box. */\nexport interface RowBox extends Bounds {\n row: Row;\n index: number;\n}\n\n/** Where one row port's label sits, in the same frame as the row box it was\n * laid out in. Its vertical center is also where the port itself attaches, so\n * a label and the port it names cannot drift apart. */\nexport interface RowPortBox extends Bounds {\n port: RowPort;\n side: 'left' | 'right';\n /** Position within its own side, top to bottom. */\n index: number;\n}\n\nconst DEFAULT_PADDING = 8;\nconst DEFAULT_GAP = 4;\n/** What a row is worth when nothing measures its text. Enough that a body\n * laid out headlessly is not zero-height — a zero-height body renders as an\n * empty page with every unit test still green. */\nconst FALLBACK_LINE = 16;\n\n/** Adapts the kit's `measureText` for a caller holding a 2D context. Pass the\n * same context the renderer measures with, or the floor will not match what\n * is painted. */\nexport function canvasMeasure(\n ctx: { measureText(text: string): { width: number } ; font: string },\n): MeasureRowText {\n return (text, style) => {\n const size = style.fontSize ?? FALLBACK_LINE;\n ctx.font = `${style.bold === true ? 'bold ' : ''}${size}px ${style.fontFamily ?? 'sans-serif'}`;\n return { width: ctx.measureText(text).width, height: Math.ceil(size * 1.2) };\n };\n}\n\n/** What each row is worth on its own, before padding and gaps. */\nfunction measureRow(row: Row, measure: MeasureRowText | undefined): { width: number; height: number } {\n const text = (s: string, style?: RowTextStyle): { width: number; height: number } =>\n measure === undefined\n ? { width: s.length * (((style?.fontSize ?? FALLBACK_LINE) * 0.6)), height: FALLBACK_LINE }\n : measure(s, style ?? {});\n\n switch (row.kind) {\n case 'label':\n return text(row.text, row.style);\n case 'field': {\n // Label and value sit on one line with a gap between them.\n const l = text(row.label, row.style);\n const v = text(row.value, row.style);\n return { width: l.width + DEFAULT_GAP * 2 + v.width, height: Math.max(l.height, v.height) };\n }\n case 'ports': {\n const side = (ports: readonly RowPort[] | undefined): number =>\n (ports ?? []).reduce((w, p) => Math.max(w, p.label === undefined ? 0 : text(p.label).width), 0);\n const rows = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);\n return {\n width: side(row.left) + DEFAULT_GAP * 2 + side(row.right),\n height: row.height ?? rows * FALLBACK_LINE,\n };\n }\n case 'slot':\n return { width: 0, height: row.height };\n }\n}\n\n/**\n * The smallest box `spec`'s rows fit in. A node's pose is maxed against this,\n * never set to it.\n */\nexport function measureBody(spec: BodySpec, measure?: MeasureRowText): BodyFloor {\n const padding = spec.padding ?? DEFAULT_PADDING;\n const gap = spec.gap ?? DEFAULT_GAP;\n let width = 0;\n let height = 0;\n for (const [i, row] of spec.rows.entries()) {\n const m = measureRow(row, measure);\n width = Math.max(width, m.width);\n height += m.height + (i > 0 ? gap : 0);\n }\n // The rows fit the *content* box; the node's own box has to be whatever\n // contains that, or a diamond's label lands outside the diamond.\n const box = boxForContent(spec.outline, {\n width: width + padding * 2,\n height: height + padding * 2,\n });\n return { minWidth: box.width, minHeight: box.height };\n}\n\n/**\n * The authored size, grown to fit the body. Never shrinks: a row removed\n * leaves the node the size the author last saw it at, which is the only\n * behavior that survives a resize the author did on purpose.\n */\nexport function sizeToBody<TPose extends Bounds>(pose: TPose, floor: BodyFloor): TPose {\n const width = Math.max(pose.width, floor.minWidth);\n const height = Math.max(pose.height, floor.minHeight);\n if (width === pose.width && height === pose.height) return pose;\n return { ...pose, width, height };\n}\n\n/** Where each row sits inside `bounds`, top to bottom. Rows keep their\n * measured heights; the leftover goes unclaimed at the bottom rather than\n * being distributed, so a row does not move when a sibling grows. */\nexport function layoutBody(\n spec: BodySpec,\n bounds: Bounds,\n measure?: MeasureRowText,\n): RowBox[] {\n const padding = spec.padding ?? DEFAULT_PADDING;\n const gap = spec.gap ?? DEFAULT_GAP;\n const inner = contentBox(spec.outline, bounds);\n const width = Math.max(inner.width - padding * 2, 0);\n let y = inner.y + padding;\n return spec.rows.map((row, index) => {\n const h = measureRow(row, measure).height;\n const box: RowBox = { row, index, x: inner.x + padding, y, width, height: h };\n y += h + gap;\n return box;\n });\n}\n\n/**\n * Where each of a `ports` row's ports goes inside `box`, on the same terms\n * `layoutBody` gives one box per row.\n *\n * Both sides are cut into the same number of slots — the longer side's count —\n * so the nth input faces the nth output whichever side has more. A label box\n * is as wide as its own text and pinned to its own edge of the row; an\n * unlabeled port gets a zero-width box there, which is still where it attaches.\n */\nexport function layoutRowPorts(\n row: Extract<Row, { kind: 'ports' }>,\n box: Bounds,\n measure?: MeasureRowText,\n): RowPortBox[] {\n const width = (label: string | undefined): number =>\n label === undefined ? 0 : measureRow({ kind: 'label', text: label }, measure).width;\n const slots = Math.max(row.left?.length ?? 0, row.right?.length ?? 0, 1);\n const slotHeight = box.height / slots;\n const out: RowPortBox[] = [];\n const side = (ports: readonly RowPort[] | undefined, which: 'left' | 'right'): void => {\n for (const [index, port] of (ports ?? []).entries()) {\n const w = width(port.label);\n out.push({\n port,\n side: which,\n index,\n x: which === 'left' ? box.x : box.x + box.width - w,\n y: box.y + index * slotHeight,\n width: w,\n height: slotHeight,\n });\n }\n };\n side(row.left, 'left');\n side(row.right, 'right');\n return out;\n}\n\n/**\n * The `DiagramNode` trait a built body implies: perimeter ports for the\n * outline, plus one port per `ports`-row entry, anchored to that row's own\n * left or right edge.\n *\n * Anchors are normalized against `bounds`, so they survive the node being\n * resized — which is the whole reason `PortAnchor` is normalized.\n *\n * **A row port on a side takes that side's compass default with it.** Both sit\n * on the same edge, and a row near the vertical middle puts one exactly on top\n * of `w` or `e` — where the later region wins the hit and the other is\n * grabbable nowhere. A body that declares where its inputs attach has said what\n * that side is for.\n */\nexport function bodyTrait(spec: BodySpec, bounds: Bounds, measure?: MeasureRowText): DiagramNode {\n const outline = spec.outline;\n const compass: PortSpec[] = [\n { id: 'n', at: COMPASS.n },\n { id: 'e', at: COMPASS.e },\n { id: 's', at: COMPASS.s },\n { id: 'w', at: COMPASS.w },\n ];\n if (bounds.height <= 0) return { outline, ports: compass };\n\n const rowPorts: PortSpec[] = [];\n let hasLeft = false;\n let hasRight = false;\n for (const box of layoutBody(spec, bounds, measure)) {\n if (box.row.kind !== 'ports') continue;\n for (const pb of layoutRowPorts(box.row, box, measure)) {\n if (pb.side === 'left') hasLeft = true;\n else hasRight = true;\n const v = (pb.y + pb.height / 2 - bounds.y) / bounds.height;\n rowPorts.push(withType(\n { id: pb.port.id, at: { u: pb.side === 'left' ? 0 : 1, v } },\n pb.port.type,\n ));\n }\n }\n const kept = compass.filter((p) =>\n !(p.id === 'w' && hasLeft) && !(p.id === 'e' && hasRight));\n return { outline, ports: [...kept, ...rowPorts] };\n}\n\nfunction withType(spec: PortSpec, type: string | undefined): PortSpec {\n return type === undefined ? spec : { ...spec, type };\n}\n\n/** The outline path for a built body at `bounds` — what paints it, and what a\n * perimeter-hugging port will eventually be placed on. */\nexport function bodyOutline(spec: BodySpec, bounds: Bounds) {\n return outlinePath(spec.outline, bounds);\n}\n\n/** What a built body's rows are handed to, one call per row.\n *\n * `text` is the row's content already formatted — a `label`'s own text, or a\n * `field`'s `\"label: value\"` — so the common case needs no discrimination.\n * Return `null` for a row the consumer paints itself; `ports` and `slot` rows\n * arrive with `text` empty and are the usual ones to decline. */\nexport type RowNodeData<TData> = (text: string, box: RowBox) => TData | null;\n\nexport interface BuildBodyOptions<TData, TLayer extends string, TPose extends Bounds> {\n layer: TLayer;\n /** The container's id. Edges name it, so pass one for anything an edge or a\n * layout `pin` will refer to. */\n id?: string;\n measure?: MeasureRowText;\n /** The container's own data, given the trait the builder computed and the\n * pose it was computed against. */\n body: (trait: DiagramNode, pose: TPose) => TData;\n /** One row's data, or `null` to leave that row undrawn. */\n row: RowNodeData<TData>;\n /** One row port's label, or `null` to leave it undrawn. Ports with no\n * `label` are never offered. Omit to draw none — a body whose ports are\n * named only for the width they claim needs nothing here. */\n portLabel?: (text: string, box: RowPortBox) => TData | null;\n}\n\n/**\n * The scene nodes a built body is: one container carrying the trait, and one\n * leaf per row that wants drawing.\n *\n * Rows are ordinary scene nodes rather than something this package paints, so\n * the kit's own text painter draws them and text editing, styling and\n * selection work on them unchanged. The walk that places them is\n * `layoutBody` — the same one `bodyTrait` anchors its row ports against, which\n * is why a label and its ports cannot drift apart.\n *\n * The pose is `sizeToBody(at, measureBody(spec))`: the body measures a floor\n * and the authored size is grown to clear it, never shrunk.\n */\nexport function buildBody<TData, TLayer extends string, TPose extends Bounds>(\n spec: BodySpec,\n at: TPose,\n opts: BuildBodyOptions<TData, TLayer, TPose>,\n): { pose: TPose; specs: BodyNodeSpec<TData, TLayer, TPose>[] } {\n const pose = sizeToBody(at, measureBody(spec, opts.measure));\n const specs: BodyNodeSpec<TData, TLayer, TPose>[] = [{\n kind: 'container',\n layer: opts.layer,\n pose,\n data: opts.body(bodyTrait(spec, pose, opts.measure), pose),\n ...(opts.id === undefined ? {} : { id: opts.id }),\n }];\n\n const leaf = (box: Bounds, data: TData): void => {\n specs.push({\n kind: 'leaf',\n layer: opts.layer,\n pose: { ...pose, x: box.x, y: box.y, width: box.width, height: box.height },\n data,\n pickable: false,\n ...(opts.id === undefined ? {} : { parent: opts.id }),\n });\n };\n\n const portLabel = opts.portLabel;\n for (const box of layoutBody(spec, pose, opts.measure)) {\n const data = opts.row(rowText(box.row), box);\n if (data !== null) leaf(box, data);\n if (portLabel === undefined || box.row.kind !== 'ports') continue;\n for (const pb of layoutRowPorts(box.row, box, opts.measure)) {\n if (pb.port.label === undefined) continue;\n const labelData = portLabel(pb.port.label, pb);\n if (labelData !== null) leaf(pb, labelData);\n }\n }\n return { pose, specs };\n}\n\n/** A row's content as one string: empty for a row that carries no text. */\nfunction rowText(row: Row): string {\n if (row.kind === 'label') return row.text;\n if (row.kind === 'field') return `${row.label}: ${row.value}`;\n return '';\n}\n","/**\n * A label on an edge: an ordinary leaf node that derives its *pose* from the\n * route it sits on.\n *\n * It reads the edge's resolved path off its dependency rather than routing\n * again, so the label and the arrowhead can never disagree about where the\n * edge went. Everything else about it is a normal scene node — its own size,\n * data, styling, z-order and selection.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n pointAlongPath,\n translatePoseViaDescriptor,\n type DerivedDep,\n type PoseDescriptor,\n} from '@weasel-js/core';\n\n/** Where along an edge a label sits. */\nexport interface DiagramLabel {\n /** `'start'`, `'mid'` and `'end'` are 0, 0.5 and 1; a number is that\n * fraction of the route's length. */\n at: 'start' | 'mid' | 'end' | number;\n /** World units perpendicular to the route, to the **left of the direction of\n * travel** — above a left-to-right edge. Default 0, which centers the label\n * on the line. */\n offset?: number;\n}\n\nconst NAMED = { start: 0, mid: 0.5, end: 1 } as const;\n\n/** The label trait on a node's data, or `null`. */\nexport function diagramLabelOf(node: { data: unknown }): DiagramLabel | null {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const trait = (data as { diagram?: unknown }).diagram;\n if (trait === null || typeof trait !== 'object') return null;\n const label = (trait as { label?: unknown }).label;\n if (label === null || typeof label !== 'object') return null;\n return 'at' in label ? (label as DiagramLabel) : null;\n}\n\nexport interface LabelPoseOptions<TPose> {\n geometry?: PoseDescriptor<TPose>;\n}\n\n/**\n * A `derivePose` that stations a label along its dependency's path.\n *\n * Returns `null` — nothing derived, so the node keeps its authored pose —\n * when the node carries no label trait, when the dependency is gone, or when\n * the dependency derives no path. A label that snapped to the origin because\n * its edge was deleted is worse than one that stayed where the author left it.\n */\nexport function labelDerivePose<TPose>(\n opts: LabelPoseOptions<TPose> = {},\n): (node: { pose: TPose; data: unknown }, deps: readonly (DerivedDep<TPose> | undefined)[]) => TPose | null {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n\n return (node, deps) => {\n const label = diagramLabelOf(node);\n if (label === null) return null;\n const path = deps[0]?.path ?? null;\n if (path === null) return null;\n\n const t = typeof label.at === 'number' ? label.at : NAMED[label.at] ?? 0.5;\n const station = pointAlongPath(path, t);\n if (station === null) return null;\n\n const offset = label.offset ?? 0;\n // Left of travel: with y down, that is above an edge running rightward.\n const x = station.point.x + station.tangent.y * offset;\n const y = station.point.y - station.tangent.x * offset;\n\n const bounds = geometry.getBounds(node.pose);\n return translatePoseViaDescriptor(\n node.pose,\n x - (bounds.x + bounds.width / 2),\n y - (bounds.y + bounds.height / 2),\n geometry,\n );\n };\n}\n\n/** Registry key for {@link LABEL_DERIVE_POSE}. */\nexport const DIAGRAM_LABEL = 'diagram:label';\n\n/** The default label derivation, as one stable function reference so `toJSON`\n * can find its key. */\nexport const LABEL_DERIVE_POSE = labelDerivePose<unknown>();\n","/**\n * `DiagramEdge` — a connection between two participants.\n *\n * An edge is an ordinary leaf scene node with `dependsOn: [from, to]` and a\n * `derivePath` that runs a **router**. Making it a scene node rather than a\n * plugin-owned render layer is the load-bearing choice: it buys selection,\n * hit-testing, hover, styling, z-order, SVG export, undo and copy/paste\n * without implementing any of them. The cost is that an edge costs what a node\n * costs — right for diagrams of tens to hundreds of edges, wrong for a\n * 10k-edge force graph, which keeps its render layer.\n *\n * **Author-dragged waypoints are data on the edge and the router routes\n * through them.** Manual control never authors the path; it authors\n * constraints on the path. That is what keeps derived geometry and hand-tuning\n * compatible — a moved endpoint still re-routes, through the waypoints the\n * author put there.\n *\n * Arrowheads are not here. They are stroke markers, the same\n * `markerStart` / `markerEnd` any other stroke carries.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n polylineFromPoints,\n type DerivedDep,\n type Path,\n type PoseDescriptor,\n type SceneRegistry,\n type Vec2,\n} from '@weasel-js/core';\nimport { DIAGRAM_LABEL, LABEL_DERIVE_POSE } from './label';\nimport { portOf, portsOf, type PortsOptions } from './ports';\nimport type { Port } from './types';\n\n/** Where an edge attaches at one end. */\nexport interface EdgeEnd {\n /** The port to leave from, when the endpoint declares one. Falls back to\n * the nearest port, so an edge drawn before ports were thought about still\n * meets the shape. */\n port?: string;\n}\n\n/** The trait on an edge's `data`, under the same key participants use. */\nexport interface DiagramEdge {\n from: EdgeEnd;\n to: EdgeEnd;\n /** Registry key for the router. Resolved by whoever builds the edge's\n * `derivePath`; unknown keys fall back to `straight`. */\n router?: string;\n /** Points in world coordinates the route must pass through, in order. The\n * author owns these; the router owns everything between them. */\n waypoints?: readonly Vec2[];\n}\n\n/** What a router is given: the two resolved ends, and the author's waypoints\n * between them. */\nexport interface RouteRequest {\n from: Port;\n to: Port;\n waypoints: readonly Vec2[];\n}\n\n/** A router returns the points the edge runs through, `from.point` first and\n * `to.point` last. Turning those into a `Path` is `edgePath`'s job, so a\n * router never has to know about path encodings. */\nexport type Router = (req: RouteRequest) => readonly Vec2[];\n\n/** The straight run between the two ends, through any waypoints. */\nexport const straight: Router = (req) => [req.from.point, ...req.waypoints, req.to.point];\n\n/**\n * An axis-aligned route: leave along the departing end's normal and arrive\n * against the receiving one's.\n *\n * A leg is one elbow where the two ends face different axes and two where they\n * face the same one, turning at the midpoint of the axis they share. Arriving\n * along the port's own facing is what makes the arrowhead point *into* the\n * shape — a route that lands on a west-facing port from above puts its marker\n * across the corner, which reads as aimed at nothing.\n */\nexport const orthogonal: Router = (req) => {\n const stops = [req.from.point, ...req.waypoints, req.to.point];\n const out: Vec2[] = [stops[0]!];\n for (let i = 1; i < stops.length; i++) {\n const a = out[out.length - 1]!;\n const b = stops[i]!;\n if (a.x === b.x || a.y === b.y) {\n out.push(b);\n continue;\n }\n // Only the first leg has a port to leave along; later legs follow the\n // one before them so the route does not alternate for no reason.\n const leaveHorizontal = i === 1\n ? isHorizontal(req.from.normal)\n : out.length > 1 && out[out.length - 2]!.y === a.y;\n // Likewise only the last leg has a port to arrive against. Without a\n // facing there is nothing to satisfy, so it keeps the single elbow.\n const arriving = i === stops.length - 1 ? req.to.normal : null;\n const arriveHorizontal = arriving == null ? !leaveHorizontal : isHorizontal(arriving);\n if (leaveHorizontal !== arriveHorizontal) {\n out.push(leaveHorizontal ? { x: b.x, y: a.y } : { x: a.x, y: b.y });\n out.push(b);\n continue;\n }\n if (leaveHorizontal) {\n const mid = (a.x + b.x) / 2;\n out.push({ x: mid, y: a.y }, { x: mid, y: b.y }, b);\n } else {\n const mid = (a.y + b.y) / 2;\n out.push({ x: a.x, y: mid }, { x: b.x, y: mid }, b);\n }\n }\n return out;\n};\n\n/** Which axis a port faces. A port with no facing counts as horizontal, which\n * is the leave-rightward default the router has always taken. */\nfunction isHorizontal(normal: Vec2 | null | undefined): boolean {\n return Math.abs(normal?.x ?? 1) >= Math.abs(normal?.y ?? 0);\n}\n\n/** How far a bezier reaches along each end's normal, as a fraction of the\n * straight-line distance between the two points it joins. */\nconst BEZIER_REACH = 0.4;\n\n/**\n * A smooth route, sampled into points.\n *\n * Each leg is a cubic that leaves along the departing end's normal and arrives\n * against the receiving one's, which is what makes a bezier edge read as\n * plugged into its port rather than aimed at it. Sampled rather than emitted\n * as curve commands so every router returns the same thing; `edgePath` is free\n * to emit curves later without changing the contract.\n */\nexport const bezier: Router = (req) => {\n const stops = [req.from.point, ...req.waypoints, req.to.point];\n const out: Vec2[] = [stops[0]!];\n for (let i = 1; i < stops.length; i++) {\n const a = stops[i - 1]!;\n const b = stops[i]!;\n const reach = Math.hypot(b.x - a.x, b.y - a.y) * BEZIER_REACH;\n const outN = i === 1 ? req.from.normal : null;\n const inN = i === stops.length - 1 ? req.to.normal : null;\n const c1 = outN === null || outN === undefined\n ? { x: a.x + (b.x - a.x) * BEZIER_REACH, y: a.y + (b.y - a.y) * BEZIER_REACH }\n : { x: a.x + outN.x * reach, y: a.y + outN.y * reach };\n const c2 = inN === null || inN === undefined\n ? { x: b.x - (b.x - a.x) * BEZIER_REACH, y: b.y - (b.y - a.y) * BEZIER_REACH }\n : { x: b.x + inN.x * reach, y: b.y + inN.y * reach };\n for (let s = 1; s <= BEZIER_SAMPLES; s++) {\n out.push(cubicAt(a, c1, c2, b, s / BEZIER_SAMPLES));\n }\n }\n return out;\n};\n\nconst BEZIER_SAMPLES = 16;\n\nfunction cubicAt(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, t: number): Vec2 {\n const u = 1 - t;\n const a = u * u * u;\n const b = 3 * u * u * t;\n const c = 3 * u * t * t;\n const d = t * t * t;\n return {\n x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,\n y: a * p0.y + b * p1.y + c * p2.y + d * p3.y,\n };\n}\n\n/** The routers this package ships. A consumer's own go in the same shape. */\nexport const ROUTERS: Readonly<Record<string, Router>> = Object.freeze({\n straight,\n orthogonal,\n bezier,\n});\n\n/** The edge trait on a node's data, or `null`. */\nexport function diagramEdgeOf(node: { data: unknown }): DiagramEdge | null {\n const data = node.data;\n if (data === null || typeof data !== 'object') return null;\n const edge = (data as { diagram?: unknown }).diagram;\n if (edge === null || typeof edge !== 'object') return null;\n return 'from' in edge && 'to' in edge ? (edge as DiagramEdge) : null;\n}\n\n/**\n * The port an end resolves to: the one it named, else the port facing the\n * other end most directly.\n *\n * \"Facing\" rather than \"nearest\": a port on the far side of a wide node can be\n * closer in a straight line than the one pointing at the target, and an edge\n * that leaves through its own node reads as a bug however short it is.\n */\nexport function resolveEnd<TPose>(\n end: EdgeEnd,\n dep: DerivedDep<TPose>,\n toward: Vec2,\n opts: PortsOptions<TPose>,\n allPorts: (d: DerivedDep<TPose>) => Port[],\n): Port | undefined {\n if (end.port !== undefined) {\n const named = portOf(dep.node as never, dep.pose, end.port, opts);\n if (named !== undefined) return named;\n }\n let best: Port | undefined;\n let bestScore = -Infinity;\n for (const port of allPorts(dep)) {\n const dx = toward.x - port.point.x;\n const dy = toward.y - port.point.y;\n const len = Math.hypot(dx, dy) || 1;\n // Alignment with the port's own facing, tie-broken toward the closer port.\n const facing = port.normal === null\n ? 0\n : (port.normal.x * dx + port.normal.y * dy) / len;\n const score = facing - len / 1e6;\n if (score > bestScore) {\n bestScore = score;\n best = port;\n }\n }\n return best;\n}\n\nexport interface EdgeRouteOptions<TPose> extends PortsOptions<TPose> {\n /** Routers by key. Defaults to {@link ROUTERS}. */\n routers?: Readonly<Record<string, Router>>;\n}\n\n/**\n * A `derivePath` that routes an edge between its two dependencies.\n *\n * Returns `null` — nothing to draw — when the node is not an edge, when either\n * dependency is gone, or when an endpoint offers no ports at all. A dangling\n * edge painting a line to the origin is worse than a dangling edge painting\n * nothing.\n */\nexport function edgeDerivePath<TPose>(\n opts: EdgeRouteOptions<TPose> = {},\n): (node: { data: unknown }, deps: readonly (DerivedDep<TPose> | undefined)[]) => Path | null {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const portOpts: PortsOptions<TPose> = { geometry, ...(opts.read ? { read: opts.read } : {}) };\n const allPorts = (d: DerivedDep<TPose>): Port[] =>\n portsOf(d.node as never, d.pose, portOpts);\n const centerOf = (d: DerivedDep<TPose>): Vec2 => {\n const b = geometry.getBounds(d.pose);\n return { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n };\n\n return (node, deps) => {\n const edge = diagramEdgeOf(node);\n if (edge === null) return null;\n const [fromDep, toDep] = deps;\n if (fromDep === undefined || toDep === undefined) return null;\n\n // Each end aims at the other's center, which is stable while both are\n // being resolved — aiming at the other *port* would be circular.\n const from = resolveEnd(edge.from, fromDep, centerOf(toDep), portOpts, allPorts);\n const to = resolveEnd(edge.to, toDep, centerOf(fromDep), portOpts, allPorts);\n if (from === undefined || to === undefined) return null;\n\n const routers = opts.routers ?? ROUTERS;\n const router = (edge.router !== undefined && routers[edge.router]) || straight;\n const points = router({ from, to, waypoints: edge.waypoints ?? [] });\n return points.length < 2 ? null : polylineFromPoints(points as { x: number; y: number }[]);\n };\n}\n\n/** Registry key for {@link EDGE_DERIVE_PATH}. */\nexport const DIAGRAM_EDGE = 'diagram:edge';\n\n/** The default edge router, as one stable function reference so `toJSON` can\n * find its key. A consumer wanting different options registers their own\n * `edgeDerivePath(...)` under a key of their choosing. */\nexport const EDGE_DERIVE_PATH = edgeDerivePath<unknown>();\n\n/** Merge this package's registry entries under a consumer's, so an edge\n * round-trips through `toJSON` without the consumer wiring the key. */\nexport function withDiagramRegistry<TPose>(\n registry: SceneRegistry<TPose> = {},\n): SceneRegistry<TPose> {\n return {\n ...registry,\n derivePath: {\n [DIAGRAM_EDGE]: EDGE_DERIVE_PATH as NonNullable<SceneRegistry<TPose>['derivePath']>[string],\n ...registry.derivePath,\n },\n derivePose: {\n [DIAGRAM_LABEL]: LABEL_DERIVE_POSE as NonNullable<SceneRegistry<TPose>['derivePose']>[string],\n ...registry.derivePose,\n },\n };\n}\n","/**\n * Ports as affordances — what makes a painted port a grabbable one.\n *\n * A port is declared as an `AffordanceRegion`, so the kit's own region walk\n * supplies the hit-test, the screen-pixel hit radius, the cursor and the\n * exclusive claim that keeps a port drag out of the select tool's hands. That\n * is the \"visible chrome is always hittable\" rule doing the work: the walk runs\n * on every pointerdown before any tool sees the event, so a port answers\n * whatever tool happens to be active.\n *\n * Two things about this are easy to get wrong, and both fail silently.\n *\n * **`targetId` is `null`.** The framework composes a target's rotation about\n * its bounds center for any region naming one, and `portsOf` has already\n * rotated the port. Naming the participant here would rotate it twice.\n *\n * **`hitKind` is not set.** On the registered-layer route the discriminator is\n * the layer's own id — `<SceneCanvas>` stamps the hit `layer:<RenderLayer.id>`\n * and carries `initialScratch` through as `payload`. A `hitKind` declared here\n * would be dropped, and a binding written against it would never match.\n */\nimport type {\n Affordance,\n AffordanceRegion,\n ChromeState,\n CursorSpec,\n FillStyle,\n PoseDescriptor,\n Stroke,\n} from '@weasel-js/core';\nimport { portsOf } from './ports';\nimport type { DiagramNodeLike, DiagramNodeReader } from './trait';\nimport type { Port } from './types';\n\n/** The layer id this package composes its port regions into. */\nexport const PORT_LAYER_ID = 'diagram-ports';\n\n/** The affordance kind a press on a port reports — what a binding's\n * `target: 'affordance:...'` has to name. `<SceneCanvas>` builds it from\n * {@link PORT_LAYER_ID}, so the two cannot drift. */\nexport const PORT_AFFORDANCE_KIND = `layer:${PORT_LAYER_ID}` as const;\n\n/** A participant and the pose it is **painted** at. `effectivePose`, not\n * `node.pose` — a port that answers from the document pose while its node is\n * mid-drag sits somewhere the user can see the node is not. */\nexport interface ParticipantPose<TPose> {\n node: DiagramNodeLike;\n pose: TPose;\n}\n\n/** Where the affordance gets its participants. A thunk rather than a scene so\n * the geometry is testable without one, and so a consumer whose participants\n * come from somewhere else needs no adapter. */\nexport type ParticipantSource<TPose> = () => Iterable<ParticipantPose<TPose>>;\n\n/** What a press on a port hands the action that picks up the drag. Arrives as\n * `InvocationCtx.drag.affordance.payload`. */\nexport interface PortScratch {\n /** `CommonAffordanceScratch.targetId` — becomes `AffordanceHit.targetIds`. */\n targetId: string;\n nodeId: string;\n portId: string;\n /** The port resolved at press time: where it was and which way it faces. */\n port: Port;\n}\n\nexport interface PortAffordanceOptions<TPose> {\n /** Also the chrome-caps visibility id. Default {@link PORT_LAYER_ID}. */\n id?: string;\n read?: DiagramNodeReader;\n geometry?: PoseDescriptor<TPose>;\n /** Which participants show their ports. Default: all of them. Gate on\n * selection or hover by reading `state`. */\n shows?: (node: DiagramNodeLike, state: ChromeState) => boolean;\n /** Screen-pixel hit radius. Default 8, the kit's `HANDLE_BASE_PX`. */\n hitRadiusPx?: number;\n /** Screen-pixel side of the painted square. Default 7. Omit `paint` entirely\n * by passing 0 — a port the consumer draws itself is still hittable. */\n sizePx?: number;\n fill?: FillStyle;\n stroke?: Stroke;\n cursor?: CursorSpec;\n /** Default `'exclusive'` on pointer gestures: a drag from a port is a\n * connect, never a move of the node underneath it. */\n strength?: 'exclusive' | 'shared';\n}\n\nconst DEFAULT_HIT_PX = 8;\nconst DEFAULT_SIZE_PX = 7;\n\n/** Read a port press's scratch back off the hit an action was handed. */\nexport function portScratchOf(hit: { payload?: unknown } | null | undefined): PortScratch | null {\n const payload = hit?.payload as PortScratch | undefined;\n return payload !== undefined && typeof payload.portId === 'string' ? payload : null;\n}\n\n/**\n * The affordance. Compose it into a layer with `composeAffordanceLayer` and\n * attach that with `CanvasExtensionApi.registerLayer` — the only attach route\n * that is hit-tested. A `Contribution.overlay` is painted and never hit.\n */\nexport function createPortAffordance<TPose>(\n participants: ParticipantSource<TPose>,\n opts: PortAffordanceOptions<TPose> = {},\n): Affordance {\n const {\n id = PORT_LAYER_ID,\n hitRadiusPx = DEFAULT_HIT_PX,\n sizePx = DEFAULT_SIZE_PX,\n strength = 'exclusive',\n } = opts;\n const portOpts = {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n };\n const paint = sizePx <= 0\n ? undefined\n : {\n kind: 'square' as const,\n sizePx,\n ...(opts.fill ? { fill: opts.fill } : {}),\n ...(opts.stroke ? { stroke: opts.stroke } : {}),\n };\n\n return {\n id,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const { node, pose } of participants()) {\n if (opts.shows !== undefined && !opts.shows(node, state)) continue;\n for (const port of portsOf(node, pose, portOpts)) {\n out.push({\n id: `${node.id}:${port.id}`,\n targetId: null,\n shape: { kind: 'point', x: port.point.x, y: port.point.y, hitRadiusPx },\n ...(paint ? { paint } : {}),\n ...(opts.cursor !== undefined ? { cursor: opts.cursor } : {}),\n strength,\n claimedKinds: ['pointer'],\n bind: () => ({\n initialScratch: {\n targetId: node.id,\n nodeId: node.id,\n portId: port.id,\n port,\n } satisfies PortScratch,\n }),\n });\n }\n }\n return out;\n },\n };\n}\n","/**\n * The connect gesture — dragging one port onto another to author an edge.\n *\n * Connect is an ordinary drag binding, not a mode and not a tool of its own:\n * the binding is gated on a press landing on a port affordance, so a connect\n * starts from whatever tool happens to be active. The gate lives in the\n * binding's `target`, which is what lets a press that is *not* on a port fall\n * through to the tool that wants it instead of being swallowed here.\n *\n * **Where validity is decided.** The two halves are decided in different\n * places, and conflating them is the mistake this package is written to avoid:\n *\n * - *Which presses start a connect* is routing, and belongs to the binding\n * spec. `connectBinding` names the port layer's affordance kind; nothing in\n * the action body re-checks what was pressed.\n * - *Which ports a live connect may land on* cannot be routing — the\n * dispatcher never re-reads the affordance under a moving pointer, so a\n * spec has no vocabulary for it. It is decided by `canConnect` filtering\n * the **candidate set**: an illegal port is never a candidate, so the\n * preview will not snap to it and a release over it commits nothing. That\n * is a narrower thing than an action body that inspects a hit and bails.\n *\n * One resolver answers both the live preview and the commit, for the reason\n * `insertAction` does the same: a preview computed separately from the commit\n * is a preview that can lie about what releasing will do.\n */\nimport {\n type Action,\n type GestureBinding,\n type InvocationCtx,\n type OngoingHandle,\n type OngoingOverlay,\n type PoseDescriptor,\n type Scene,\n type Stroke,\n type Vec2,\n} from '@weasel-js/core';\nimport { EDGE_DERIVE_PATH, ROUTERS, type DiagramEdge, type Router } from './edge';\nimport { PORT_AFFORDANCE_KIND, portScratchOf, type ParticipantSource } from './portAffordance';\nimport { portsOf } from './ports';\nimport type { DiagramNodeReader } from './trait';\nimport type { Port } from './types';\n\n/** The default action id, and what {@link connectBinding} points at. */\nexport const CONNECT_ACTION_ID = 'diagram.connect';\n\n/** Whether an edge may run from `from` to `to`. */\nexport type CanConnect = (from: Port, to: Port) => boolean;\n\n/** The edge a finished connect describes. Both ends are resolved ports, so a\n * consumer minting the node has nothing left to look up. */\nexport interface PendingEdge {\n from: Port;\n to: Port;\n /** Registry key for the router the new edge should name. */\n router: string;\n}\n\n/**\n * The shipped policy: a port may not join itself, and two ports that both\n * declare a `type` must declare the same one.\n *\n * A port with no type joins anything — `PortSpec.type` is uninterpreted by this\n * package, so an untyped diagram stays fully connectable without opting out.\n * Two ports on the *same node* may be joined: a self-edge between two different\n * ports is meaningful in a state machine, and refusing it here would be policy\n * masquerading as a rule.\n */\nexport const defaultCanConnect: CanConnect = (from, to) => {\n if (from.nodeId === to.nodeId && from.id === to.id) return false;\n if (from.type === undefined || to.type === undefined) return true;\n return from.type === to.type;\n};\n\nexport interface ConnectActionOptions<TPose> {\n /** Where the droppable ports come from. The same source the port affordance\n * reads, so what is grabbable and what is landable cannot disagree. */\n participants: ParticipantSource<TPose>;\n /** Default {@link CONNECT_ACTION_ID}. */\n id?: string;\n read?: DiagramNodeReader;\n geometry?: PoseDescriptor<TPose>;\n /** Default {@link defaultCanConnect}. */\n canConnect?: CanConnect;\n /** How near the pointer must come to a port, in world units, before the\n * edge snaps to it. Default 16. */\n snapRadius?: number;\n /** Registry key the new edge names, and the router the preview draws with.\n * Default `'straight'`. */\n router?: string;\n routers?: Readonly<Record<string, Router>>;\n /**\n * Mints and commits the edge. Called once, on release over a valid port.\n *\n * Defaults to {@link commitEdgeToScene} against `deps.scene`, which is what\n * makes the gesture work with nothing wired. Override it the way a consumer\n * overrides the kit's `insert` dep — to choose the edge node's data, its\n * layer, or its stroke.\n */\n commit?: (edge: PendingEdge, ctx: InvocationCtx) => void;\n}\n\nconst DEFAULT_SNAP = 16;\n/** What a connect-authored edge is drawn with, when the consumer overrides\n * nothing. */\nexport const DEFAULT_EDGE_STROKE: Stroke = {\n paint: { color: '#7ba7c7' },\n width: 2,\n markerEnd: 'arrow',\n};\nconst DEFAULT_ROUTER = 'straight';\n\ninterface ConnectScratch {\n from: Port;\n current: Vec2;\n open: boolean;\n /** The deps bag as it was at `start`. The dispatcher builds it once, so\n * every later pump event carries `deps: {}` — an action that reads a dep at\n * commit time reads nothing and commits nothing, silently. */\n deps: InvocationCtx['deps'];\n}\n\n/**\n * The binding that starts a connect: a drag whose press landed on the port\n * layer's own chrome.\n *\n * The string form of `target` rather than a predicate, because it ranks higher\n * in specificity — a bare `{ kind: 'drag' }` on the select tool cannot outrank\n * it, so no tool needs a predicate of its own to keep out of the way.\n */\nexport function connectBinding(actionId: string = CONNECT_ACTION_ID): GestureBinding {\n return {\n spec: { kind: 'drag', target: `affordance:${PORT_AFFORDANCE_KIND}` },\n actionId,\n };\n}\n\n/** The action id that absorbs a press on a port. */\nexport const GRAB_PORT_ACTION_ID = 'diagram.grabPort';\n\n/**\n * Absorbs a press on a port, and does nothing else.\n *\n * A port claims the press **protocol**, not one gesture in it: `pointerDown`,\n * `click` and `drag` are a single claimable `'pointer'` token, and an exclusive\n * claim bars every binding whose target does not consult the affordance. So a\n * bundle that binds only `drag` leaves the pointerdown with nowhere to go, and\n * the dispatcher drops the press — the drag it would have grown into never\n * happens. Absorbing the press is also the behavior you want on its own: a\n * press on a port should not pick or deselect the node underneath it.\n */\nexport function grabPortAction(id: string = GRAB_PORT_ACTION_ID): Action {\n return {\n id,\n label: 'Grab port',\n group: 'diagram',\n invoker: { timing: 'immediate', run: () => {} },\n enabled: () => true as const,\n };\n}\n\n/** The two bindings that keep a port's claim from dropping the press. */\nexport function grabPortBindings(actionId: string = GRAB_PORT_ACTION_ID): GestureBinding[] {\n return [\n { spec: { kind: 'pointerDown', target: `affordance:${PORT_AFFORDANCE_KIND}` }, actionId },\n { spec: { kind: 'click', target: `affordance:${PORT_AFFORDANCE_KIND}` }, actionId },\n ];\n}\n\n/**\n * The default commit: one leaf node carrying the edge trait, added to\n * `deps.scene`. One `add` is one history entry, so the edge undoes in one.\n *\n * The edge lands on the **source node's** layer rather than the bottom one: an\n * edge between two nodes on a `wires` layer belongs on `wires`, and picking the\n * first layer in the stack would quietly move it somewhere the author did not\n * put its endpoints.\n */\nexport function commitEdgeToScene(edge: PendingEdge, ctx: InvocationCtx): void {\n const scene = ctx.deps['scene'] as Scene<unknown, string, unknown> | undefined;\n if (scene === undefined) return;\n const trait: DiagramEdge = {\n from: { port: edge.from.id },\n to: { port: edge.to.id },\n router: edge.router,\n };\n const source = scene.get(edge.from.nodeId as never);\n scene.add({\n kind: 'leaf',\n layer: source?.layer ?? scene.layers[0]!.id,\n pose: { x: 0, y: 0, width: 0, height: 0 } as never,\n // An edge runs *from* one node *to* another, and a plain line does not say\n // so. The arrowhead is an ordinary stroke marker, which is why nothing in\n // this package draws one.\n data: { diagram: trait, stroke: DEFAULT_EDGE_STROKE } as never,\n dependsOn: [edge.from.nodeId as never, edge.to.nodeId as never],\n // Without this the edge re-resolves on every dependency move and paints\n // nothing. `EDGE_DERIVE_PATH` rather than a fresh `edgeDerivePath()` so the\n // scene can find its registry key and the edge survives `toJSON`.\n derivePath: EDGE_DERIVE_PATH as never,\n });\n}\n\n/**\n * The `diagram.connect` action: an ongoing drag whose preview is an ephemeral\n * edge and whose commit is one op batch.\n *\n * A factory rather than a singleton because every input it needs — which nodes\n * are droppable, what counts as a legal pair, how an edge node is shaped — is\n * the consumer's, and this package has no scene at module scope. Same reason\n * `edgeDerivePath` and `diagramShape` are factories.\n */\nexport function createConnectAction<TPose>(opts: ConnectActionOptions<TPose>): Action {\n const {\n id = CONNECT_ACTION_ID,\n canConnect = defaultCanConnect,\n snapRadius = DEFAULT_SNAP,\n router: routerKey = DEFAULT_ROUTER,\n commit = commitEdgeToScene,\n } = opts;\n const routers = opts.routers ?? ROUTERS;\n const portOpts = {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n };\n const route: Router = routers[routerKey] ?? routers['straight'] ?? ROUTERS['straight']!;\n\n /** The port the pointer is over and may legally land on, or `null`.\n *\n * `canConnect` is applied here rather than at commit, so an illegal port is\n * not a candidate at all: the edge does not snap to it and releasing over it\n * does nothing. */\n function targetPort(from: Port, at: Vec2): Port | null {\n let best: Port | null = null;\n let bestD2 = snapRadius * snapRadius;\n for (const { node, pose } of opts.participants()) {\n for (const port of portsOf(node, pose, portOpts)) {\n if (!canConnect(from, port)) continue;\n const d2 = (port.point.x - at.x) ** 2 + (port.point.y - at.y) ** 2;\n if (d2 <= bestD2) {\n bestD2 = d2;\n best = port;\n }\n }\n }\n return best;\n }\n\n /** The end the edge currently runs to: a snapped port, or the bare pointer.\n * A free end is a port with no facing, so a router aims straight at it. */\n function endAt(from: Port, at: Vec2): { port: Port | null; end: Port } {\n const port = targetPort(from, at);\n return {\n port,\n end: port ?? { id: '', nodeId: '', point: at, normal: null },\n };\n }\n\n return {\n id,\n label: 'Connect',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const pressed = portScratchOf(ctx.drag?.affordance);\n // Not a port press. The binding spec already said only port presses\n // reach here, so this is the runtime backstop, not the gate — and an\n // empty handle is how the dispatcher is told to fall through.\n if (pressed === null) return {};\n const scratch: ConnectScratch = {\n from: pressed.port,\n current: { x: ctx.world.x, y: ctx.world.y },\n open: true,\n deps: ctx.deps,\n };\n\n return {\n kind: 'diagram-connect',\n onMove(moveCtx: InvocationCtx): void {\n scratch.current = { x: moveCtx.world.x, y: moveCtx.world.y };\n },\n overlay(): OngoingOverlay | null {\n if (!scratch.open) return null;\n const { end } = endAt(scratch.from, scratch.current);\n const points = route({ from: scratch.from, to: end, waypoints: [] });\n if (points.length < 2) return null;\n // The route, and the word for what it is. How a connector reads —\n // color, weight, dash — belongs to whatever surface paints it;\n // core's own is `useDispatcherOverlayLayer`, whose\n // `DispatcherOverlayStyle.roles` is where a consumer restyles it.\n return { kind: 'polyline', points, role: 'connector' };\n },\n onEnd(endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n scratch.open = false;\n if (reason === 'cancel') return;\n const { port } = endAt(scratch.from, { x: endCtx.world.x, y: endCtx.world.y });\n if (port === null) return;\n // World and modifiers from the release; deps from the press.\n commit(\n { from: scratch.from, to: port, router: routerKey },\n { ...endCtx, deps: scratch.deps },\n );\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * The port affordance, composed into a layer and pointed at a scene.\n *\n * Two conveniences over {@link createPortAffordance}, both of which encode a\n * rule that is easy to get wrong rather than merely saving a line.\n */\nimport {\n composeAffordanceLayer,\n effectivePose,\n type RenderLayer,\n} from '@weasel-js/core';\nimport {\n PORT_LAYER_ID,\n createPortAffordance,\n type ParticipantSource,\n type PortAffordanceOptions,\n} from './portAffordance';\nimport type { GraphNodeLike, GraphSource } from './graph';\n\n/** The minimum a participant source needs from a scene. Narrower than `Scene`\n * so a consumer can pass anything that answers these two. */\nexport interface ParticipantScene<TPose> {\n renderOrderNodes(): readonly {\n id: string;\n kind: 'leaf' | 'container';\n data: unknown;\n pose: TPose;\n dependsOn?: readonly string[] | 'children';\n }[];\n readonly overrides: { get(id: string): { pose?: TPose } | undefined };\n get(id: string): unknown;\n childrenOf(id: string): readonly string[];\n}\n\n/**\n * Every node in `scene`, at the pose it is **painted** at.\n *\n * `effectivePose`, not `node.pose`: an override is what a gesture is currently\n * showing, and a port that answers from the document pose while its node is\n * mid-drag sits somewhere the user can see the node is not. Nodes that carry no\n * participant trait cost one reader call each and contribute no regions.\n *\n * One source answers both the ports and the graph — `GraphSource` is a\n * `ParticipantSource` that also carries `dependsOn`, which is where an edge's\n * two endpoints live.\n */\nexport function sceneParticipants<TPose>(\n scene: ParticipantScene<TPose>,\n): GraphSource<TPose> {\n return function* () {\n for (const node of scene.renderOrderNodes()) {\n yield {\n node: node as GraphNodeLike,\n pose: effectivePose(scene as never, node as never) as TPose,\n };\n }\n };\n}\n\n/**\n * The composed layer, ready for `CanvasExtensionApi.registerLayer` — the only\n * attach route that is hit-tested. Handing this to `SceneCanvas`'s `layers`\n * prop, or to a `Contribution.overlay`, paints the ports and makes none of them\n * grabbable.\n *\n * The cast is `composeAffordanceLayer` typing its data slot as `ChromeState`\n * while the layer registry takes `RenderLayer<unknown>`; both are handed the\n * same live `CanvasHelpers` envelope at runtime.\n */\nexport function portLayer<TPose>(\n participants: ParticipantSource<TPose>,\n opts: PortAffordanceOptions<TPose> = {},\n): RenderLayer<unknown> & { hitTest: NonNullable<RenderLayer<unknown>['hitTest']> } {\n return composeAffordanceLayer(\n opts.id ?? PORT_LAYER_ID,\n 'Diagram ports',\n [createPortAffordance(participants, opts)],\n ) as unknown as RenderLayer<unknown> & { hitTest: NonNullable<RenderLayer<unknown>['hitTest']> };\n}\n","/**\n * The plugin as a `Contribution` bundle — one object a consumer hands to\n * `<SceneCanvas ambient={…}>`.\n *\n * **Ambient, not a tool.** Connect is not a mode the author enters: a port is\n * grabbable whatever tool is active, which is the same reason `@weasel-js/hud`\n * ships `eligibility: { claimed: true }`. `claimed` is what makes the bundle\n * live for a press the port layer's affordance claimed, and dormant otherwise.\n *\n * **The layer is not in here, on purpose.** `Contribution.overlay` is painted\n * and never hit-tested — only `CanvasExtensionApi.registerLayer` gets a\n * `hitTest` call. Shipping the port layer as an overlay would paint every port\n * and make none of them grabbable, which is exactly the state this arc started\n * from. {@link diagramPorts} hands back the bundle and the layer together so\n * the two cannot be wired half-way.\n */\nimport type { Contribution, RenderLayer } from '@weasel-js/core';\nimport {\n CONNECT_ACTION_ID,\n connectBinding,\n createConnectAction,\n grabPortAction,\n grabPortBindings,\n type ConnectActionOptions,\n} from './connect';\nimport { portLayer } from './portLayer';\nimport type { PortAffordanceOptions } from './portAffordance';\n\nexport { CONNECT_ACTION_ID };\n\nexport interface DiagramContributionOptions<TPose>\n extends ConnectActionOptions<TPose>, PortAffordanceOptions<TPose> {}\n\n/** The bundle: the connect action and the one binding that reaches it. */\nexport function createDiagramContribution<TPose>(\n opts: DiagramContributionOptions<TPose>,\n): Contribution {\n const actionId = opts.id ?? CONNECT_ACTION_ID;\n return {\n id: 'weasel-diagram',\n eligibility: { claimed: true },\n actions: [createConnectAction({ ...opts, id: actionId }), grabPortAction()],\n bindings: [connectBinding(actionId), ...grabPortBindings()],\n };\n}\n\n/**\n * Both halves of the port affordance: the layer to `registerLayer`, and the\n * contribution to pass as `ambient`.\n *\n * They are returned together because attaching one without the other fails\n * quietly — the layer alone paints ports that start no gesture, and the\n * contribution alone binds an affordance kind nothing ever reports.\n */\nexport function diagramPorts<TPose>(opts: DiagramContributionOptions<TPose>): {\n layer: RenderLayer<unknown>;\n contribution: Contribution;\n} {\n return {\n layer: portLayer(opts.participants, opts),\n contribution: createDiagramContribution(opts),\n };\n}\n","/**\n * `Graph` — the adjacency index a layout runs over.\n *\n * The scene is the document, so there is no second graph kept in sync with it:\n * this one is built from the scene on demand, used, and thrown away. Rebuilding\n * per layout invocation is deliberate — a maintained index is a cache to\n * invalidate on every add, delete, reparent and `dependsOn` edit, and layout is\n * not on the hot path. Measure before changing that.\n *\n * A node's *identity* is its id and its *size* is its bounds; where it currently\n * sits is here too, because a re-layout that ignores where things already are\n * scrambles a diagram the author has arranged.\n */\nimport { AUTO_POSE_DESCRIPTOR, type PoseDescriptor } from '@weasel-js/core';\nimport { diagramEdgeOf } from './edge';\nimport type { Bounds } from './outline';\nimport { diagramNodeOf, type DiagramNodeLike, type DiagramNodeReader } from './trait';\n\n/** A scene node as the graph reads it. `dependsOn` is what an edge's two\n * endpoints are: the edge trait names *ports*, and the nodes those ports are\n * on are the dependencies the derivation already runs on. */\nexport interface GraphNodeLike extends DiagramNodeLike {\n dependsOn?: readonly string[] | 'children';\n}\n\n/** Where the graph gets its nodes. The same thunk shape the port affordance\n * takes, so one source answers both. */\nexport type GraphSource<TPose> = () => Iterable<{ node: GraphNodeLike; pose: TPose }>;\n\n/** One participant. */\nexport interface GraphNode {\n id: string;\n /** Where it is now, in world coordinates. */\n bounds: Bounds;\n /** Layout must not move it. */\n pinned: boolean;\n}\n\n/** One connection. `id` is the edge node's own id, so a caller can go back to\n * the scene for its trait. */\nexport interface GraphEdge {\n id: string;\n from: string;\n to: string;\n}\n\n/**\n * Nodes, edges, and the two adjacency reads a layout needs.\n *\n * Every list is in source order — render order, when the source is a scene —\n * which is what a layout's tiebreaks resolve against. There is no RNG anywhere\n * downstream of this, and this is where that starts.\n */\nexport interface Graph {\n readonly nodes: readonly GraphNode[];\n readonly edges: readonly GraphEdge[];\n node(id: string): GraphNode | undefined;\n /** Edges leaving `id`, in source order. */\n outgoing(id: string): readonly GraphEdge[];\n /** Edges arriving at `id`, in source order. */\n incoming(id: string): readonly GraphEdge[];\n}\n\nexport interface BuildGraphOptions<TPose> {\n read?: DiagramNodeReader;\n geometry?: PoseDescriptor<TPose>;\n}\n\n/**\n * Read a graph out of a source of scene nodes.\n *\n * A node is an edge if it carries the edge trait and names exactly two\n * dependencies; a participant if the reader hands back a `DiagramNode`;\n * neither, and it is not in the diagram at all. An edge whose endpoints are not\n * both participants is dropped — a dangling edge should not be ranking\n * anything.\n */\nexport function buildGraph<TPose>(\n source: GraphSource<TPose>,\n opts: BuildGraphOptions<TPose> = {},\n): Graph {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const nodes: GraphNode[] = [];\n const byId = new Map<string, GraphNode>();\n const candidates: GraphEdge[] = [];\n\n for (const { node, pose } of source()) {\n if (diagramEdgeOf(node) !== null) {\n const deps = node.dependsOn;\n if (Array.isArray(deps) && deps.length === 2) {\n candidates.push({ id: node.id, from: deps[0]!, to: deps[1]! });\n }\n continue;\n }\n const trait = diagramNodeOf(node, opts.read);\n if (trait === null) continue;\n const entry: GraphNode = {\n id: node.id,\n bounds: geometry.getBounds(pose),\n pinned: trait.pinned === true,\n };\n nodes.push(entry);\n byId.set(entry.id, entry);\n }\n\n const edges = candidates.filter((e) => byId.has(e.from) && byId.has(e.to));\n const out = new Map<string, GraphEdge[]>();\n const into = new Map<string, GraphEdge[]>();\n for (const edge of edges) {\n push(out, edge.from, edge);\n push(into, edge.to, edge);\n }\n\n const NONE: readonly GraphEdge[] = Object.freeze([]);\n return {\n nodes,\n edges,\n node: (id) => byId.get(id),\n outgoing: (id) => out.get(id) ?? NONE,\n incoming: (id) => into.get(id) ?? NONE,\n };\n}\n\nfunction push(index: Map<string, GraphEdge[]>, key: string, edge: GraphEdge): void {\n const list = index.get(key);\n if (list === undefined) index.set(key, [edge]);\n else list.push(edge);\n}\n","/**\n * Layout: where the participants go.\n *\n * A layout is a pure function of the graph — no scene, no ops, no history. It\n * hands back the new top-left for every node that **moves**, and a node already\n * standing where the layout wants it is simply absent from the answer. That is\n * what makes re-running a layout free rather than destructive, and it is the\n * property the idempotence test asserts.\n *\n * Three rules keep re-layout non-destructive, and all three live here rather\n * than in each algorithm:\n *\n * - **No RNG anywhere.** Every tiebreak falls back to the graph's own node\n * order, which is the source's order — render order, for a scene.\n * - **Within-rank order is seeded from where the nodes already are**, read\n * off the cross axis, rather than from crossing-minimization. An author who\n * dragged two boxes into an order gets that order back.\n * - **A pin set nothing moves.** Pinned nodes are never in the result, and\n * the rest of the layout is translated to sit around them.\n *\n * `layered` and `tree` are idempotent by construction: the second run reads the\n * order the first run produced and computes the same slots. `force` is an\n * iterative relaxation and makes no such claim — re-running it keeps relaxing.\n */\nimport type { Vec2 } from '@weasel-js/core';\nimport type { Graph, GraphNode } from './graph';\nimport type { Bounds } from './outline';\n\n/** Which way the ranks stack. `force` ignores it. */\nexport type LayoutDirection = 'down' | 'up' | 'right' | 'left';\n\nexport interface LayoutOptions {\n /** Default `'down'`. */\n direction?: LayoutDirection;\n /** Between neighbors within a rank, in world units. Default 48. */\n nodeGap?: number;\n /** Between one rank and the next. Default 96. */\n rankGap?: number;\n /** Ids layout must not move, on top of whatever carries `pinned: true`. */\n pin?: Iterable<string>;\n /** How far a node has to move to be worth moving, in world units. Default\n * `1e-6` — a float-noise floor, not a snapping quantum. Raise it to let a\n * `force` pass that has stopped doing anything useful commit nothing. */\n tolerance?: number;\n}\n\n/** The new top-left for each node that moves. A node that is already there is\n * absent, so an empty result means \"nothing to do\". */\nexport type LayoutResult = ReadonlyMap<string, Vec2>;\n\n/** Every layout in this package has this shape, and so does a consumer's. */\nexport type LayoutFn = (graph: Graph, opts?: LayoutOptions) => LayoutResult;\n\nexport const DEFAULT_NODE_GAP = 48;\nexport const DEFAULT_RANK_GAP = 96;\nconst DEFAULT_TOLERANCE = 1e-6;\n\n/** Which world axis carries ranks, which carries within-rank order, and\n * whether ranks grow toward positive world coordinates. */\nexport interface LayoutAxes {\n rank: 'x' | 'y';\n cross: 'x' | 'y';\n /** `-1` for `'up'` and `'left'`, where the canonical frame is mirrored. */\n sign: 1 | -1;\n}\n\nexport function axesFor(direction: LayoutDirection = 'down'): LayoutAxes {\n switch (direction) {\n case 'up':\n return { rank: 'y', cross: 'x', sign: -1 };\n case 'right':\n return { rank: 'x', cross: 'y', sign: 1 };\n case 'left':\n return { rank: 'x', cross: 'y', sign: -1 };\n default:\n return { rank: 'y', cross: 'x', sign: 1 };\n }\n}\n\n/** A node's extent along one axis. */\nexport function extent(bounds: Bounds, axis: 'x' | 'y'): number {\n return axis === 'x' ? bounds.width : bounds.height;\n}\n\n/** A node's center along one axis — what within-rank order is seeded from. */\nexport function center(bounds: Bounds, axis: 'x' | 'y'): number {\n return axis === 'x' ? bounds.x + bounds.width / 2 : bounds.y + bounds.height / 2;\n}\n\n/** Every id layout must leave alone. */\nexport function pinnedSet(graph: Graph, opts: LayoutOptions = {}): Set<string> {\n const pinned = new Set<string>(opts.pin ?? []);\n for (const node of graph.nodes) {\n if (node.pinned) pinned.add(node.id);\n }\n return pinned;\n}\n\n/**\n * A placement in the canonical `(cross, rank)` frame, before it is turned into\n * world coordinates. `cross` and `rank` are the node's low corner along each.\n */\nexport interface Slot {\n cross: number;\n rank: number;\n}\n\n/**\n * Turn canonical slots into the positions to write.\n *\n * Three steps, in order: map the canonical frame onto the world axes the\n * direction names; translate the whole layout so it lands where the graph\n * already is; drop everything that is pinned or that would not move.\n *\n * The translation is what makes the layout non-destructive, and it is chosen so\n * that a second run lands on the same answer. With a pin, it is whatever keeps\n * the first pinned node exactly where it is. Without one, it is whatever puts\n * the layout's own bounding box where the graph's bounding box already starts —\n * which the first run then makes true, so the second run computes the same\n * translation and writes nothing.\n */\nexport function settle(\n graph: Graph,\n slots: ReadonlyMap<string, Slot>,\n opts: LayoutOptions = {},\n): LayoutResult {\n const axes = axesFor(opts.direction);\n const pinned = pinnedSet(graph, opts);\n const tolerance = opts.tolerance ?? DEFAULT_TOLERANCE;\n\n const placed = new Map<string, Vec2>();\n for (const node of graph.nodes) {\n const slot = slots.get(node.id);\n if (slot === undefined) continue;\n const along = axes.sign === 1 ? slot.rank : -(slot.rank + extent(node.bounds, axes.rank));\n placed.set(\n node.id,\n axes.rank === 'y' ? { x: slot.cross, y: along } : { x: along, y: slot.cross },\n );\n }\n\n return translated(graph, placed, pinned, tolerance);\n}\n\n/**\n * {@link settle}'s second half, for a layout that already works in world\n * coordinates — `force` does, since the integrator moves points around rather\n * than filling slots.\n */\nexport function translated(\n graph: Graph,\n placed: ReadonlyMap<string, Vec2>,\n pinned: ReadonlySet<string>,\n tolerance = DEFAULT_TOLERANCE,\n): LayoutResult {\n const anchor = anchorDelta(graph, placed, pinned);\n const out = new Map<string, Vec2>();\n for (const node of graph.nodes) {\n const at = placed.get(node.id);\n if (at === undefined || pinned.has(node.id)) continue;\n const x = at.x + anchor.x;\n const y = at.y + anchor.y;\n if (Math.abs(x - node.bounds.x) <= tolerance && Math.abs(y - node.bounds.y) <= tolerance) {\n continue;\n }\n out.set(node.id, { x, y });\n }\n return out;\n}\n\nfunction anchorDelta(\n graph: Graph,\n placed: ReadonlyMap<string, Vec2>,\n pinned: ReadonlySet<string>,\n): Vec2 {\n for (const node of graph.nodes) {\n if (!pinned.has(node.id)) continue;\n const at = placed.get(node.id);\n if (at !== undefined) return { x: node.bounds.x - at.x, y: node.bounds.y - at.y };\n }\n let minCurX = Infinity;\n let minCurY = Infinity;\n let minNewX = Infinity;\n let minNewY = Infinity;\n for (const node of graph.nodes) {\n const at = placed.get(node.id);\n if (at === undefined) continue;\n minCurX = Math.min(minCurX, node.bounds.x);\n minCurY = Math.min(minCurY, node.bounds.y);\n minNewX = Math.min(minNewX, at.x);\n minNewY = Math.min(minNewY, at.y);\n }\n if (!Number.isFinite(minCurX)) return { x: 0, y: 0 };\n return { x: minCurX - minNewX, y: minCurY - minNewY };\n}\n\n/**\n * Lay a list of nodes out along the cross axis, in the order given, and hand\n * back each one's low corner plus the total span.\n *\n * Shared by `layered`'s ranks and `tree`'s sibling rows, which pack a row the\n * same way and differ only in what decides the order.\n */\nexport function packAcross(\n nodes: readonly GraphNode[],\n axis: 'x' | 'y',\n gap: number,\n): { at: Map<string, number>; span: number } {\n const at = new Map<string, number>();\n let cursor = 0;\n for (const node of nodes) {\n at.set(node.id, cursor);\n cursor += extent(node.bounds, axis) + gap;\n }\n return { at, span: nodes.length === 0 ? 0 : cursor - gap };\n}\n\n/** Order within a rank: where the nodes already sit on the cross axis, with\n * graph order breaking a tie. Never a comparison that could reverse between\n * two runs on the same input. */\nexport function seededOrder(\n nodes: readonly GraphNode[],\n axis: 'x' | 'y',\n indexOf: (id: string) => number,\n): GraphNode[] {\n return [...nodes].sort((a, b) => {\n const d = center(a.bounds, axis) - center(b.bounds, axis);\n return d !== 0 ? d : indexOf(a.id) - indexOf(b.id);\n });\n}\n\n/** Each node's position in `graph.nodes`, for tiebreaks. */\nexport function graphOrder(graph: Graph): (id: string) => number {\n const index = new Map<string, number>();\n graph.nodes.forEach((node, i) => index.set(node.id, i));\n return (id) => index.get(id) ?? Number.MAX_SAFE_INTEGER;\n}\n","/**\n * `force` — relaxation, for a graph with no direction to read it in.\n *\n * Seeded from where the nodes already are rather than from a fresh random\n * scatter: an author who has arranged half a diagram gets that arrangement\n * relaxed, not replaced. There is no RNG in it at all — two coincident nodes\n * are separated along a golden-angle spiral keyed to their index, which is what\n * a random jiggle is for elsewhere.\n *\n * The integrator is the kit's own `createSimulation`, the same one\n * `useSimulation` runs a frame at a time. Only the forces are local, and they\n * are the naive O(n²) kind — right for the tens-to-hundreds of nodes an\n * edge-per-scene-node diagram is already sized for, wrong for a 10k-node graph,\n * which wants d3-force's Barnes–Hut through `useSimulation` and its own render\n * layer.\n *\n * **This is the one layout that is not idempotent.** A relaxation re-run from\n * its own output keeps relaxing; `direction` means nothing to it. Pins and the\n * `tolerance` option are what keep a second pass from scrambling a settled\n * diagram.\n */\nimport { createSimulation, type SimulationForce, type SimulationNode } from '@weasel-js/core';\nimport type { Graph } from './graph';\nimport {\n center,\n pinnedSet,\n translated,\n type LayoutFn,\n type LayoutOptions,\n type LayoutResult,\n} from './layout';\n\nexport interface ForceOptions extends LayoutOptions {\n /** Ticks to run. Default 300 — one full cooling schedule. */\n iterations?: number;\n /** Rest length of an edge, in world units. Default 160. */\n linkDistance?: number;\n /** How hard an edge pulls, 0..1. Default 0.35. */\n linkStrength?: number;\n /** Pairwise repulsion. Negative repels; default -3000. */\n charge?: number;\n /** How hard the graph is held around its own centroid. Default 0.02. */\n gravity?: number;\n /** Clear space kept between two boxes, in world units. Default 24. */\n padding?: number;\n}\n\ninterface Body extends SimulationNode {\n id: string;\n /** Half the node's box, so separation can work on the shape the author sees\n * rather than on a point. */\n hw: number;\n hh: number;\n}\n\nconst DEFAULTS = {\n iterations: 300,\n linkDistance: 160,\n linkStrength: 0.35,\n charge: -3000,\n gravity: 0.02,\n padding: 24,\n} as const;\n\n/** The golden angle. Coincident nodes fan out along it, which spreads any\n * number of them without two landing on the same heading. */\nconst GOLDEN = Math.PI * (3 - Math.sqrt(5));\n/** How far the first coincident node is pushed, in world units. Small enough\n * to be invisible, large enough that the repulsion term is finite. */\nconst NUDGE = 0.5;\n\n/** Pairwise repulsion, applied to every pair once. */\nfunction charge(bodies: readonly Body[], strength: number): SimulationForce<Body> {\n return (alpha) => {\n for (let i = 0; i < bodies.length; i++) {\n const a = bodies[i]!;\n for (let j = i + 1; j < bodies.length; j++) {\n const b = bodies[j]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const d2 = dx * dx + dy * dy;\n if (d2 === 0) continue;\n const w = (strength * alpha) / d2;\n a.vx! += dx * w;\n a.vy! += dy * w;\n b.vx! -= dx * w;\n b.vy! -= dy * w;\n }\n }\n };\n}\n\n/** A spring per edge, pulling both ends toward `distance`. */\nfunction links(\n bodies: ReadonlyMap<string, Body>,\n graph: Graph,\n distance: number,\n strength: number,\n): SimulationForce<Body> {\n return (alpha) => {\n for (const edge of graph.edges) {\n const a = bodies.get(edge.from);\n const b = bodies.get(edge.to);\n if (a === undefined || b === undefined || a === b) continue;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const d = Math.hypot(dx, dy);\n if (d === 0) continue;\n const pull = ((d - distance) / d) * alpha * strength;\n a.vx! += dx * pull;\n a.vy! += dy * pull;\n b.vx! -= dx * pull;\n b.vy! -= dy * pull;\n }\n };\n}\n\n/**\n * Push overlapping boxes apart along whichever axis they overlap least.\n *\n * Charge alone is not enough: it treats a node as a point, so two wide boxes\n * whose centers are a comfortable distance apart still cover each other. This\n * works on the box, and it is not scaled by alpha — an overlap at the end of\n * the run is exactly as wrong as one at the start.\n */\nfunction separateBoxes(bodies: readonly Body[], padding: number): SimulationForce<Body> {\n return () => {\n for (let i = 0; i < bodies.length; i++) {\n const a = bodies[i]!;\n for (let j = i + 1; j < bodies.length; j++) {\n const b = bodies[j]!;\n const dx = b.x - a.x;\n const dy = b.y - a.y;\n const gapX = a.hw + b.hw + padding - Math.abs(dx);\n const gapY = a.hh + b.hh + padding - Math.abs(dy);\n if (gapX <= 0 || gapY <= 0) continue;\n if (gapX < gapY) {\n const push = (Math.sign(dx) || 1) * gapX * 0.5;\n a.vx! -= push;\n b.vx! += push;\n } else {\n const push = (Math.sign(dy) || 1) * gapY * 0.5;\n a.vy! -= push;\n b.vy! += push;\n }\n }\n }\n };\n}\n\n/** A pull toward the seed centroid, so a component with nothing to hold it\n * does not drift off under pure repulsion. */\nfunction gravity(bodies: readonly Body[], at: { x: number; y: number }, strength: number): SimulationForce<Body> {\n return (alpha) => {\n for (const body of bodies) {\n body.vx! += (at.x - body.x) * strength * alpha;\n body.vy! += (at.y - body.y) * strength * alpha;\n }\n };\n}\n\n/**\n * The bodies and the force list, wound up and ready to tick.\n *\n * Shared by the one-shot `force` below and the live relaxation in `live.ts`,\n * which ticks it a frame at a time. Two copies of a force list drift, and the\n * only thing that would say so is the arrangement they produce.\n */\nexport interface ForceRelaxation {\n bodies: Body[];\n byId: Map<string, Body>;\n /** Ids the caller must not move: declared pins, held as `fx`/`fy`. */\n pinned: ReadonlySet<string>;\n sim: ReturnType<typeof createSimulation<Body>>;\n /** Where a body's node's top-left sits, given the body's center. */\n placed(): Map<string, { x: number; y: number }>;\n}\n\nexport function forceRelaxation(graph: Graph, opts: ForceOptions = {}): ForceRelaxation {\n const {\n linkDistance = DEFAULTS.linkDistance,\n linkStrength = DEFAULTS.linkStrength,\n charge: chargeStrength = DEFAULTS.charge,\n gravity: gravityStrength = DEFAULTS.gravity,\n padding = DEFAULTS.padding,\n } = opts;\n\n const pinned = pinnedSet(graph, opts);\n const bodies: Body[] = graph.nodes.map((node) => {\n const body: Body = {\n id: node.id,\n x: center(node.bounds, 'x'),\n y: center(node.bounds, 'y'),\n hw: node.bounds.width / 2,\n hh: node.bounds.height / 2,\n };\n // A pin is the integrator's own `fx`/`fy`, not a filter applied after the\n // fact: a pinned node has to hold its neighbors while they relax, not be\n // put back once they have finished relaxing around where it wasn't.\n if (pinned.has(node.id)) {\n body.fx = body.x;\n body.fy = body.y;\n }\n return body;\n });\n separate(bodies);\n\n const byId = new Map(bodies.map((b) => [b.id, b]));\n const centroid = {\n x: bodies.reduce((sum, b) => sum + b.x, 0) / bodies.length,\n y: bodies.reduce((sum, b) => sum + b.y, 0) / bodies.length,\n };\n\n const sim = createSimulation<Body>({\n nodes: bodies,\n forces: [\n charge(bodies, chargeStrength),\n links(byId, graph, linkDistance, linkStrength),\n gravity(bodies, centroid, gravityStrength),\n separateBoxes(bodies, padding),\n ],\n });\n\n return {\n bodies,\n byId,\n pinned,\n sim,\n placed() {\n const placed = new Map<string, { x: number; y: number }>();\n for (const node of graph.nodes) {\n const body = byId.get(node.id)!;\n placed.set(node.id, {\n x: body.x - node.bounds.width / 2,\n y: body.y - node.bounds.height / 2,\n });\n }\n return placed;\n },\n };\n}\n\nexport const force = (graph: Graph, opts: ForceOptions = {}): LayoutResult => {\n if (graph.nodes.length === 0) return new Map();\n const relaxation = forceRelaxation(graph, opts);\n relaxation.sim.tick(opts.iterations ?? DEFAULTS.iterations);\n return translated(graph, relaxation.placed(), relaxation.pinned, opts.tolerance);\n};\n\n/** `ForceOptions` only widens `LayoutOptions`, so this is a `LayoutFn` — but\n * declaring it as one would hide the extra options from every caller. */\nforce satisfies LayoutFn;\n\n/** Push coincident bodies apart, deterministically. Two nodes at exactly the\n * same point feel no repulsion from each other and stay stacked forever. A\n * pinned body is counted but never moved — a pin outranks this. */\nfunction separate(bodies: Body[]): void {\n const seen = new Map<string, number>();\n bodies.forEach((body, i) => {\n const key = `${body.x},${body.y}`;\n const nth = seen.get(key) ?? 0;\n seen.set(key, nth + 1);\n if (nth === 0 || body.fx != null || body.fy != null) return;\n const angle = GOLDEN * i;\n const radius = NUDGE * nth;\n body.x += Math.cos(angle) * radius;\n body.y += Math.sin(angle) * radius;\n });\n}\n","/**\n * `layered` — ranks running one way, nodes running across.\n *\n * The flowchart / pipeline layout: an edge points from one rank to the next, so\n * reading down the page is reading the order things happen in. Ranks come from\n * longest-path layering, which puts every node as far along as its deepest\n * predecessor allows.\n *\n * Cycles do not disqualify a graph. A depth-first walk in graph order names the\n * edges that close a cycle, layering ignores those, and they draw as edges\n * running back up the page — which is what a reader expects a loop to look\n * like. Which edges get named depends only on the node order, so it is the same\n * every run.\n *\n * This is not crossing-minimization: within a rank, nodes keep the order they\n * already have on the cross axis. An author who dragged two branches into an\n * order gets that order back, and re-running the layout is free.\n */\nimport type { Graph, GraphNode } from './graph';\nimport {\n DEFAULT_NODE_GAP,\n DEFAULT_RANK_GAP,\n axesFor,\n extent,\n graphOrder,\n packAcross,\n seededOrder,\n settle,\n type LayoutFn,\n type Slot,\n} from './layout';\n\n/** Edge ids that close a cycle, found by a depth-first walk in graph order. */\nexport function backEdges(graph: Graph): Set<string> {\n const back = new Set<string>();\n const done = new Set<string>();\n const onStack = new Set<string>();\n\n const walk = (id: string): void => {\n if (done.has(id)) return;\n onStack.add(id);\n for (const edge of graph.outgoing(id)) {\n if (onStack.has(edge.to)) back.add(edge.id);\n else walk(edge.to);\n }\n onStack.delete(id);\n done.add(id);\n };\n\n for (const node of graph.nodes) walk(node.id);\n return back;\n}\n\n/** Longest-path rank per node: one past its deepest predecessor. */\nexport function ranksOf(graph: Graph, back: ReadonlySet<string>): Map<string, number> {\n const ranks = new Map<string, number>();\n const resolving = new Set<string>();\n\n const rankOf = (id: string): number => {\n const known = ranks.get(id);\n if (known !== undefined) return known;\n // Only reachable if `back` missed an edge; guarding here keeps a bad\n // cycle-breaker from recursing forever rather than reporting a wrong rank.\n if (resolving.has(id)) return 0;\n resolving.add(id);\n let rank = 0;\n for (const edge of graph.incoming(id)) {\n if (back.has(edge.id)) continue;\n rank = Math.max(rank, rankOf(edge.from) + 1);\n }\n resolving.delete(id);\n ranks.set(id, rank);\n return rank;\n };\n\n for (const node of graph.nodes) rankOf(node.id);\n return ranks;\n}\n\nexport const layered: LayoutFn = (graph, opts = {}) => {\n const axes = axesFor(opts.direction);\n const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;\n const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;\n const order = graphOrder(graph);\n\n const ranks = ranksOf(graph, backEdges(graph));\n const byRank = new Map<number, GraphNode[]>();\n for (const node of graph.nodes) {\n const rank = ranks.get(node.id) ?? 0;\n const list = byRank.get(rank);\n if (list === undefined) byRank.set(rank, [node]);\n else list.push(node);\n }\n\n const rows = [...byRank.keys()].sort((a, b) => a - b);\n const packed = new Map<number, ReturnType<typeof packAcross>>();\n let widest = 0;\n for (const rank of rows) {\n const row = seededOrder(byRank.get(rank)!, axes.cross, order);\n const p = packAcross(row, axes.cross, nodeGap);\n packed.set(rank, p);\n widest = Math.max(widest, p.span);\n }\n\n const slots = new Map<string, Slot>();\n let along = 0;\n for (const rank of rows) {\n const row = byRank.get(rank)!;\n const p = packed.get(rank)!;\n const indent = (widest - p.span) / 2;\n const depth = Math.max(0, ...row.map((n) => extent(n.bounds, axes.rank)));\n for (const node of row) {\n slots.set(node.id, {\n cross: indent + p.at.get(node.id)!,\n // Centered in its rank's band, so a tall node does not push its\n // neighbors' edges off the line they read along.\n rank: along + (depth - extent(node.bounds, axes.rank)) / 2,\n });\n }\n along += depth + rankGap;\n }\n\n return settle(graph, slots, opts);\n};\n","/**\n * `tree` — a parent centered over the block its children occupy.\n *\n * The hierarchy layout: org charts, file trees, decision trees. Depth is the\n * rank axis, so every child sits one band past its parent, and a subtree is\n * packed as a solid block so two siblings' descendants never interleave.\n *\n * A graph that is not a tree still lays out. Roots are the nodes nothing points\n * at, in graph order; a node reachable from two parents belongs to whichever\n * the depth-first walk reaches first; and anything the walk never reaches — a\n * disconnected part, or a pure cycle — becomes a root of its own. So the answer\n * is always a forest, and which forest depends only on the node order.\n *\n * The block packing is deliberately not Reingold–Tilford: it never slides a\n * deep subtree under a shallow neighbor's overhang. That costs horizontal\n * space and buys an invariant an author can rely on — a subtree's extent is a\n * rectangle, and dragging one never lands it inside another.\n */\nimport type { Graph, GraphNode } from './graph';\nimport {\n DEFAULT_NODE_GAP,\n DEFAULT_RANK_GAP,\n axesFor,\n extent,\n graphOrder,\n seededOrder,\n settle,\n type LayoutFn,\n type Slot,\n} from './layout';\n\ninterface Forest {\n roots: GraphNode[];\n children: Map<string, GraphNode[]>;\n depth: Map<string, number>;\n}\n\n/** The forest a depth-first walk in graph order finds. Exported because \"which\n * node ended up whose child\" is the question anyone debugging a tree layout\n * asks first. */\nexport function forestOf(graph: Graph, crossAxis: 'x' | 'y'): Forest {\n const order = graphOrder(graph);\n const children = new Map<string, GraphNode[]>();\n const depth = new Map<string, number>();\n const roots: GraphNode[] = [];\n\n const claim = (node: GraphNode, at: number): void => {\n depth.set(node.id, at);\n const kids: GraphNode[] = [];\n for (const edge of graph.outgoing(node.id)) {\n if (edge.to === node.id || depth.has(edge.to)) continue;\n const child = graph.node(edge.to);\n if (child === undefined) continue;\n // Claimed on sight rather than inside the recursion, so two siblings\n // sharing a descendant cannot both take it.\n depth.set(child.id, at + 1);\n kids.push(child);\n }\n const ordered = seededOrder(kids, crossAxis, order);\n children.set(node.id, ordered);\n for (const child of ordered) claim(child, at + 1);\n };\n\n const rootish = graph.nodes.filter((node) =>\n graph.incoming(node.id).every((edge) => edge.from === node.id));\n for (const node of seededOrder(rootish, crossAxis, order)) {\n if (depth.has(node.id)) continue;\n roots.push(node);\n claim(node, 0);\n }\n // Whatever the walk could not reach: a disconnected part, or a component\n // every node of which is inside a cycle.\n for (const node of graph.nodes) {\n if (depth.has(node.id)) continue;\n roots.push(node);\n claim(node, 0);\n }\n\n return { roots, children, depth };\n}\n\nexport const tree: LayoutFn = (graph, opts = {}) => {\n const axes = axesFor(opts.direction);\n const nodeGap = opts.nodeGap ?? DEFAULT_NODE_GAP;\n const rankGap = opts.rankGap ?? DEFAULT_RANK_GAP;\n const { roots, children, depth } = forestOf(graph, axes.cross);\n\n const bands = new Map<number, number>();\n for (const node of graph.nodes) {\n const at = depth.get(node.id) ?? 0;\n bands.set(at, Math.max(bands.get(at) ?? 0, extent(node.bounds, axes.rank)));\n }\n const bandStart = new Map<number, number>();\n let along = 0;\n for (const at of [...bands.keys()].sort((a, b) => a - b)) {\n bandStart.set(at, along);\n along += bands.get(at)! + rankGap;\n }\n\n const slots = new Map<string, Slot>();\n\n /** How wide `node`'s whole subtree is on the cross axis: its children's\n * blocks side by side, or the node itself when that is wider. */\n const measured = new Map<string, number>();\n const measure = (node: GraphNode): number => {\n const known = measured.get(node.id);\n if (known !== undefined) return known;\n const kids = children.get(node.id) ?? [];\n let width = 0;\n for (const child of kids) width += measure(child);\n if (kids.length > 0) width += nodeGap * (kids.length - 1);\n const block = Math.max(extent(node.bounds, axes.cross), width);\n measured.set(node.id, block);\n return block;\n };\n\n /** Place `node`'s subtree with its block starting at `from`. */\n const place = (node: GraphNode, from: number): void => {\n const kids = children.get(node.id) ?? [];\n const block = measure(node);\n const width = kids.reduce((sum, k) => sum + measure(k), 0)\n + Math.max(0, kids.length - 1) * nodeGap;\n\n let cursor = from + (block - width) / 2;\n for (const child of kids) {\n place(child, cursor);\n cursor += measure(child) + nodeGap;\n }\n\n const own = extent(node.bounds, axes.cross);\n const at = depth.get(node.id) ?? 0;\n slots.set(node.id, {\n cross: from + (block - own) / 2,\n rank: bandStart.get(at)! + (bands.get(at)! - extent(node.bounds, axes.rank)) / 2,\n });\n };\n\n let cursor = 0;\n for (const root of roots) {\n place(root, cursor);\n cursor += measure(root) + nodeGap;\n }\n\n return settle(graph, slots, opts);\n};\n","/**\n * Running a layout against a scene: `LAYOUTS`, one batch of pose writes, and\n * the action that reaches both.\n *\n * The split is the point. A layout is a pure function of the graph and is\n * tested as one; `applyLayout` is the only thing that touches a scene, and it\n * writes every move inside a single `scene.batch`, so a re-layout is one undo\n * entry rather than one per node.\n */\nimport {\n translatePoseViaDescriptor,\n AUTO_POSE_DESCRIPTOR,\n type Action,\n type PoseDescriptor,\n type Scene,\n} from '@weasel-js/core';\nimport { force } from './force';\nimport { buildGraph, type GraphSource } from './graph';\nimport { layered } from './layered';\nimport { tree } from './tree';\nimport type { LayoutFn, LayoutOptions, LayoutResult } from './layout';\nimport type { DiagramNodeReader } from './trait';\n\n/** The layouts this package ships. A consumer's own go in the same shape. */\nexport const LAYOUTS: Readonly<Record<string, LayoutFn>> = Object.freeze({\n layered,\n tree,\n force,\n});\n\nexport interface ApplyLayoutOptions<TPose> {\n geometry?: PoseDescriptor<TPose>;\n /** The undo entry's name. Default `'Layout'`. */\n label?: string;\n}\n\n/**\n * Write a layout's answer to the scene, as one undoable batch.\n *\n * Returns how many nodes moved, which is zero for a layout that had nothing to\n * do — nothing is written and no history entry is pushed.\n *\n * Nodes are **translated**, never re-posed from the layout's numbers: a node's\n * pose can be a path or anything else a consumer wired, and only its own\n * descriptor knows how to move one.\n *\n * A participant that is a container takes its whole subtree along. `setPose`\n * does not cascade — poses are absolute — so a built body would otherwise walk\n * out from under its own label rows with every test green.\n */\nexport function applyLayout<TPose>(\n scene: Scene<unknown, string, TPose>,\n result: LayoutResult,\n opts: ApplyLayoutOptions<TPose> = {},\n): number {\n const poses = layoutPoses(scene, result, opts.geometry);\n if (poses.size === 0) return 0;\n scene.batch(opts.label ?? 'Layout', () => {\n for (const [id, pose] of poses) scene.setPose(id as never, pose);\n });\n // Participants, not the descendants they carried along: a caller asking how\n // much a layout did means the nodes it placed.\n let moved = 0;\n for (const id of result.keys()) if (poses.has(id)) moved++;\n return moved;\n}\n\n/**\n * The poses a layout result implies, without writing any of them: each moved\n * node translated to its new top-left, and its subtree translated with it.\n *\n * Split out because a *live* layout needs the same answer every frame and must\n * not write it — it publishes to the override channel and commits once. The\n * translation is measured from the node's document pose, which a run in flight\n * never changes, so a frame's answer does not depend on the frame before it.\n */\nexport function layoutPoses<TPose>(\n scene: Scene<unknown, string, TPose>,\n result: LayoutResult,\n geometry: PoseDescriptor<TPose> = AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>,\n): Map<string, TPose> {\n const out = new Map<string, TPose>();\n for (const [id, at] of result) {\n const node = scene.get(id as never);\n if (node === undefined) continue;\n const bounds = geometry.getBounds(node.pose);\n const dx = at.x - bounds.x;\n const dy = at.y - bounds.y;\n if (dx === 0 && dy === 0) continue;\n out.set(id, translatePoseViaDescriptor(node.pose, dx, dy, geometry));\n for (const descendant of subtreeOf(scene, id)) {\n const child = scene.get(descendant as never);\n if (child === undefined) continue;\n out.set(descendant, translatePoseViaDescriptor(child.pose, dx, dy, geometry));\n }\n }\n return out;\n}\n\nfunction subtreeOf<TPose>(scene: Scene<unknown, string, TPose>, id: string): string[] {\n const out: string[] = [];\n const stack = [...scene.childrenOf(id as never)];\n while (stack.length > 0) {\n const next = stack.pop()!;\n out.push(next);\n stack.push(...scene.childrenOf(next));\n }\n return out;\n}\n\n/** The default action id. */\nexport const LAYOUT_ACTION_ID = 'diagram.layout';\n\nexport interface LayoutActionOptions<TPose> {\n /** Where the graph is read from. The same thunk the port affordance takes. */\n source: GraphSource<TPose>;\n /** Default {@link LAYOUT_ACTION_ID}. */\n id?: string;\n label?: string;\n /** Which `<ActionBar group>` it lands in. Default `'diagram'`, alongside\n * connect — give a bar of its own a group of its own. */\n group?: string;\n /** A key in {@link LAYOUTS}, or a layout of the consumer's own. Default\n * `'layered'`. */\n algorithm?: string | LayoutFn;\n layout?: LayoutOptions;\n read?: DiagramNodeReader;\n geometry?: PoseDescriptor<TPose>;\n}\n\n/**\n * `diagram.layout` — rebuild the graph, run a layout, write the result.\n *\n * A factory rather than a singleton for the reason every other entry point in\n * this package is one: which nodes are in the diagram is the consumer's, and\n * this package has no scene at module scope.\n */\nexport function createLayoutAction<TPose>(opts: LayoutActionOptions<TPose>): Action {\n const algorithm = typeof opts.algorithm === 'function'\n ? opts.algorithm\n : LAYOUTS[opts.algorithm ?? 'layered'] ?? layered;\n const build = {\n ...(opts.read ? { read: opts.read } : {}),\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n };\n\n return {\n id: opts.id ?? LAYOUT_ACTION_ID,\n label: opts.label ?? 'Lay out diagram',\n group: opts.group ?? 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run: (deps) => {\n const scene = deps['scene'] as Scene<unknown, string, TPose> | undefined;\n if (scene === undefined) return;\n const graph = buildGraph(opts.source, build);\n applyLayout(scene, algorithm(graph, opts.layout), {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.label ? { label: opts.label } : {}),\n });\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * Layout you can watch, and push against.\n *\n * A live layout is a producer on core's `usePoseRun`: each frame it hands back\n * where the participants are, the run publishes that to the scene's override\n * channel, and the whole thing commits as one batch when it settles. Nothing\n * here writes the document.\n *\n * Two producers, because the two kinds of layout are different processes.\n * `force` is a relaxation whose target changes every tick. `layered` and `tree`\n * know where they are going before they start, so they ease into it.\n *\n * **A node another gesture owns is a pin.** The run reports it, `force` holds\n * it with `fx`/`fy` and relaxes its neighbors around it, and an eased layout\n * simply leaves it alone. Dragging a body mid-run is therefore the consumer's\n * ordinary move tool — this package contributes no gesture for it.\n */\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport {\n AUTO_POSE_DESCRIPTOR,\n usePoseRun,\n type EasingFn,\n type NodeId,\n type PoseDescriptor,\n type PoseRunCtx,\n type PoseRunStep,\n type Scene,\n} from '@weasel-js/core';\nimport { forceRelaxation, type ForceOptions } from './force';\nimport { buildGraph, type Graph, type GraphSource } from './graph';\nimport { layered } from './layered';\nimport { LAYOUTS, layoutPoses } from './layoutAction';\nimport { center, type LayoutFn, type LayoutOptions, type LayoutResult } from './layout';\nimport { tree } from './tree';\nimport type { DiagramNodeReader } from './trait';\n\n/** What a live producer is told, and what it answers with. */\nexport interface LiveLayoutCtx<TPose> {\n /** Nodes another gesture is moving, and where each is drawn. */\n pinned: ReadonlyMap<NodeId, TPose>;\n /** Frames since this run heated, starting at 0. */\n frame: number;\n}\n\n/** A frame of a live layout: where the participants are, and whether it is\n * finished. Positions are top-lefts, the same as a `LayoutResult`. */\nexport interface LiveLayoutFrame {\n result: LayoutResult;\n done: boolean;\n}\n\nexport type LiveLayoutProducer<TPose> = (ctx: LiveLayoutCtx<TPose>) => LiveLayoutFrame;\n\n/** How long an eased layout takes to arrive, in frames. Frame-counted rather\n * than timed, so a background tab resumes where it paused rather than\n * arriving the instant it comes back. */\nconst EASE_FRAMES = 24;\n\n/** Smooth start and end. Inlined rather than pulled from the animator, which\n * is a registry of running tweens, not a curve library. */\nconst easeInOut: EasingFn = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);\n\nexport interface ForceProducerOptions<TPose> extends ForceOptions {\n geometry?: PoseDescriptor<TPose>;\n /** Alpha held while something is pinned, so the graph keeps answering a drag\n * instead of freezing under it. Default 0.3. */\n dragAlpha?: number;\n}\n\n/**\n * A relaxation, one tick a frame, done when the simulation settles.\n *\n * The forces are `forceRelaxation`'s — the same ones the one-shot `force`\n * runs, wound up once here and ticked rather than run to completion.\n *\n * It does **not** re-anchor the way the one-shot does. That translation exists\n * so a single 300-tick jump does not move the diagram off where the author left\n * it; a live run cannot jump, every frame being one step from the last, and\n * gravity holds the graph around the centroid it was seeded from. Re-anchoring\n * per frame would also fight a drag: the anchor is measured from where the\n * nodes were, and a pinned node is deliberately somewhere else.\n */\nexport function forceProducer<TPose>(\n graph: Graph,\n opts: ForceProducerOptions<TPose> = {},\n): LiveLayoutProducer<TPose> {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const relaxation = forceRelaxation(graph, opts);\n const dragAlpha = opts.dragAlpha ?? 0.3;\n\n return ({ pinned }) => {\n for (const node of graph.nodes) {\n const body = relaxation.byId.get(node.id);\n if (body === undefined) continue;\n const held = pinned.get(node.id as NodeId);\n if (held !== undefined) {\n // A dragged node holds its neighbors while they relax, which is `fx` /\n // `fy` on the integrator rather than a correction applied afterward.\n const bounds = geometry.getBounds(held);\n body.fx = center(bounds, 'x');\n body.fy = center(bounds, 'y');\n } else if (!relaxation.pinned.has(node.id)) {\n delete body.fx;\n delete body.fy;\n }\n }\n // A pin is a live edit, so the run keeps its temperature up until the\n // pointer lets go.\n relaxation.sim.alphaTarget(pinned.size > 0 ? dragAlpha : 0);\n relaxation.sim.tick();\n return { result: relaxation.placed(), done: relaxation.sim.isSettled() };\n };\n}\n\nexport interface EasedProducerOptions {\n layout?: LayoutOptions;\n /** Frames to arrive in. Default 24. */\n frames?: number;\n easing?: EasingFn;\n}\n\n/**\n * A layout that knows its destination, walked into place.\n *\n * The target is computed once, from the graph as it stood when the run heated;\n * each frame is that target scaled by the easing curve, measured from where the\n * nodes started. A pinned node is dropped from the target rather than fought\n * over.\n */\nexport function easedProducer<TPose>(\n graph: Graph,\n algorithm: LayoutFn,\n opts: EasedProducerOptions = {},\n): LiveLayoutProducer<TPose> {\n const frames = opts.frames ?? EASE_FRAMES;\n const easing = opts.easing ?? easeInOut;\n const target = algorithm(graph, opts.layout);\n const from = new Map<string, { x: number; y: number }>();\n for (const node of graph.nodes) from.set(node.id, { x: node.bounds.x, y: node.bounds.y });\n\n return ({ pinned, frame }) => {\n const t = Math.min((frame + 1) / frames, 1);\n const u = easing(t);\n const result = new Map<string, { x: number; y: number }>();\n for (const [id, to] of target) {\n if (pinned.has(id as NodeId)) continue;\n const start = from.get(id);\n if (start === undefined) continue;\n result.set(id, {\n x: start.x + (to.x - start.x) * u,\n y: start.y + (to.y - start.y) * u,\n });\n }\n return { result, done: t >= 1 };\n };\n}\n\nexport interface UseLiveLayoutOptions<TPose> {\n scene: Scene<unknown, string, TPose>;\n /** Where the graph is read from. The same thunk the port affordance takes. */\n source: GraphSource<TPose>;\n /** A key in `LAYOUTS`, or a layout of the consumer's own. `'force'` relaxes\n * continuously; anything else eases to its answer. Default `'force'`. */\n algorithm?: string | LayoutFn;\n layout?: LayoutOptions;\n force?: ForceOptions;\n /** Frames an eased layout takes to arrive. Default 24. */\n frames?: number;\n easing?: EasingFn;\n read?: DiagramNodeReader;\n geometry?: PoseDescriptor<TPose>;\n /** The undo entry's name. Default `'Layout'`. */\n label?: string;\n /** Fires once the run has settled or been stopped and its poses are in the\n * document, with how many participants moved. */\n onSettle?: (moved: number) => void;\n /** Whether a node or edge appearing or disappearing re-heats the run.\n * Default true — a diagram that ignores a new edge looks broken. */\n reheatOnGraphChange?: boolean;\n /** Clock injection, for tests. Defaults to `requestAnimationFrame`. */\n requestFrame?: (cb: (t: number) => void) => number;\n cancelFrame?: (handle: number) => void;\n}\n\nexport interface LiveLayout {\n /** Heat and run. Idempotent while running. */\n start(): void;\n /** Finish now: commit where the nodes stand. */\n stop(): void;\n /** Abandon: the document keeps the poses it had. */\n cancel(): void;\n /** Rebuild the graph and run again from where the nodes are now. */\n restart(): void;\n isRunning(): boolean;\n}\n\n/** The shape of a graph, as a string that changes when a node or edge does. */\nfunction shapeOf(graph: Graph): string {\n const nodes = graph.nodes.map((n) => n.id).sort().join(',');\n const edges = graph.edges.map((e) => `${e.from}>${e.to}`).sort().join(',');\n return `${nodes}|${edges}`;\n}\n\n/**\n * Run a layout live against a scene.\n *\n * The returned handle is stable. Dragging a participant while it runs needs no\n * wiring: the consumer's move tool publishes an override, and the run treats\n * that as a pin.\n */\nexport function useLiveLayout<TPose>(opts: UseLiveLayoutOptions<TPose>): LiveLayout {\n const optsRef = useRef(opts);\n optsRef.current = opts;\n\n const producer = useRef<LiveLayoutProducer<TPose> | null>(null);\n const producerFrame = useRef(0);\n const shape = useRef('');\n\n const build = useCallback((): void => {\n const o = optsRef.current;\n const graph = buildGraph(o.source, {\n ...(o.read ? { read: o.read } : {}),\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n shape.current = shapeOf(graph);\n producerFrame.current = 0;\n const algorithm = o.algorithm ?? 'force';\n if (algorithm === 'force') {\n producer.current = forceProducer<TPose>(graph, {\n ...o.layout, ...o.force,\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n return;\n }\n const fn = typeof algorithm === 'function' ? algorithm : LAYOUTS[algorithm] ?? layered;\n producer.current = easedProducer<TPose>(graph, fn, {\n ...(o.layout ? { layout: o.layout } : {}),\n ...(o.frames === undefined ? {} : { frames: o.frames }),\n ...(o.easing ? { easing: o.easing } : {}),\n });\n }, []);\n\n const step = useCallback((ctx: PoseRunCtx<TPose>): PoseRunStep<TPose> => {\n const o = optsRef.current;\n if (producer.current === null) return { poses: [], done: true };\n const { result, done } = producer.current({\n pinned: ctx.pinned,\n frame: producerFrame.current++,\n });\n // A pinned participant takes its subtree out of the frame with it. The run\n // skips the participant itself, but its rows and labels are ids of their\n // own — left in, they would be published from the pose the document still\n // holds while the gesture carries the box somewhere else.\n let placed = result;\n if (ctx.pinned.size > 0) {\n const held = new Map(result);\n for (const id of ctx.pinned.keys()) held.delete(id as string);\n placed = held;\n }\n const poses = layoutPoses(o.scene, placed, o.geometry);\n return { poses: [...poses] as [NodeId, TPose][], done };\n }, []);\n\n const run = usePoseRun<TPose>({\n scene: opts.scene,\n step,\n onCommit: (moved) => optsRef.current.onSettle?.(moved),\n ...(opts.label ? { label: opts.label } : {}),\n ...(opts.requestFrame ? { requestFrame: opts.requestFrame } : {}),\n ...(opts.cancelFrame ? { cancelFrame: opts.cancelFrame } : {}),\n });\n\n // A node or edge appearing or disappearing is a new problem, so the run\n // re-heats rather than finishing the one it started on.\n useEffect(() => {\n if (opts.reheatOnGraphChange === false) return;\n return opts.scene.subscribe(() => {\n if (!run.isRunning()) return;\n const o = optsRef.current;\n const graph = buildGraph(o.source, {\n ...(o.read ? { read: o.read } : {}),\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n if (shapeOf(graph) === shape.current) return;\n build();\n });\n }, [opts.scene, opts.reheatOnGraphChange, run, build]);\n\n return useMemo<LiveLayout>(() => ({\n start() {\n if (run.isRunning()) return;\n build();\n run.start();\n },\n stop: () => { run.stop(); },\n cancel: () => { run.cancel(); },\n restart() {\n run.cancel();\n build();\n run.start();\n },\n isRunning: () => run.isRunning(),\n }), [run, build]);\n}\n\n/** The layouts that ease rather than relax, for a consumer choosing one. */\nexport const EASED_LAYOUTS: Readonly<Record<string, LayoutFn>> = Object.freeze({\n layered,\n tree,\n});\n","/**\n * The painter for a node whose trait names an `outline`.\n *\n * Registered the way every other trait's renderer is — a `NodeShapeEntry` with\n * a `matches` over the node's data — so a diagram body is picked, clipped and\n * area-selected by the same walk as everything else, and a participant that\n * already had a look of its own (a text block, an image, a path) keeps it by\n * naming no outline at all.\n *\n * Rows are **not** painted here. A built body's rows are ordinary scene nodes\n * under the container, so the kit's own text painter draws them and text\n * editing, selection and styling work on them without a special case.\n */\nimport {\n RECT_POSE_DESCRIPTOR,\n registerNodeShape,\n type FillStyle,\n type NodeShapeEntry,\n type PoseDescriptor,\n type Stroke,\n} from '@weasel-js/core';\nimport { outlinePath } from './outline';\nimport { diagramNodeOf, type DiagramNodeReader } from './trait';\n\nexport interface DiagramShapeOptions<TPose> {\n /** Distinguishes one registration from another, and is what the disposer\n * removes. Default `'diagram:outline'`. */\n id?: string;\n /** How the trait is read. Default: the node's own `data.diagram`. */\n read?: DiagramNodeReader;\n /** Reads the box the outline is built in. Default `RECT_POSE_DESCRIPTOR`. */\n geometry?: PoseDescriptor<TPose>;\n /** Painted when the node's data declares neither. */\n defaultFill?: FillStyle | null;\n defaultStroke?: Stroke | null;\n}\n\n/** The entry, for a consumer composing their own painter list. */\nexport function diagramShape<TPose>(\n opts: DiagramShapeOptions<TPose> = {},\n): NodeShapeEntry<unknown, TPose> {\n const geometry = opts.geometry ?? (RECT_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const outlineOf = (node: { id: string; kind: 'leaf' | 'container'; data: unknown }) =>\n diagramNodeOf(node, opts.read)?.outline;\n\n return {\n id: opts.id ?? 'diagram:outline',\n matches: (node) => outlineOf(node) !== undefined,\n paint: (node, pose) => {\n const outline = outlineOf(node);\n if (outline === undefined) return [];\n const d = node.data as { fill?: FillStyle | null; stroke?: Stroke | null };\n const fill = d.fill === undefined ? opts.defaultFill : d.fill;\n const stroke = d.stroke === undefined ? opts.defaultStroke : d.stroke;\n return [{\n kind: 'path',\n path: outlinePath(outline, geometry.getBounds(pose)),\n ...(fill ? { fill } : {}),\n ...(stroke ? { stroke } : {}),\n }];\n },\n // The drawn boundary, so picking and clipping follow the diamond rather\n // than its bounding box.\n silhouette: (node, pose) => {\n const outline = outlineOf(node);\n return outline === undefined ? null : outlinePath(outline, geometry.getBounds(pose));\n },\n };\n}\n\n/**\n * Register {@link diagramShape}. Returns the disposer, and takes `'high'`\n * priority so a body outline wins over a `data.shape` or `data.path` the same\n * node may also carry.\n */\nexport function registerDiagramShape<TPose>(opts: DiagramShapeOptions<TPose> = {}): () => void {\n return registerNodeShape(diagramShape(opts), { priority: 'high' });\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weasel-js/diagram",
3
- "version": "1.4.4",
3
+ "version": "1.5.0",
4
4
  "description": "Node-link diagramming for weasel: any scene node becomes a diagram participant, with ports on its perimeter and an optional body builder for flowchart-shaped boxes.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -17,7 +17,7 @@
17
17
  },
18
18
  "peerDependencies": {
19
19
  "react": ">=18",
20
- "@weasel-js/core": "1.4.4"
20
+ "@weasel-js/core": "1.5.0"
21
21
  },
22
22
  "author": "orochi235",
23
23
  "homepage": "https://orochi235.github.io/weasel/",