@weasel-js/diagram 1.7.2 → 1.8.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
@@ -621,7 +621,7 @@ interface ParticipantScene<TPose> {
621
621
  dependsOn?: readonly string[] | 'children';
622
622
  }[];
623
623
  readonly overrides: {
624
- get(id: string): {
624
+ read(id: string): {
625
625
  pose?: TPose;
626
626
  } | undefined;
627
627
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/label.ts","../src/edge.ts","../src/portAffordance.ts","../src/connect.ts","../src/portLayer.ts","../src/contribution.ts","../src/graph.ts","../src/layoutAction.ts","../src/live.ts","../src/shape.ts"],"names":["AUTO_POSE_DESCRIPTOR","translatePoseViaDescriptor"],"mappings":";;;;;;;AA4BA,IAAM,QAAQ,EAAE,KAAA,EAAO,GAAG,GAAA,EAAK,GAAA,EAAK,KAAK,CAAA,EAAE;AAGpC,SAAS,eAAe,IAAA,EAA8C;AAC3E,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA;AAClB,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,UAAU,OAAO,IAAA;AACtD,EAAA,MAAM,QAAS,IAAA,CAA+B,OAAA;AAC9C,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,UAAU,OAAO,IAAA;AACxD,EAAA,MAAM,QAAS,KAAA,CAA8B,KAAA;AAC7C,EAAA,IAAI,KAAA,KAAU,IAAA,IAAQ,OAAO,KAAA,KAAU,UAAU,OAAO,IAAA;AACxD,EAAA,OAAO,IAAA,IAAQ,QAAS,KAAA,GAAyB,IAAA;AACnD;AAgBO,SAAS,eAAA,CACd,IAAA,GAAgC,EAAC,EACyE;AAC1G,EAAA,MAAM,QAAA,GAAW,KAAK,QAAA,IAAa,oBAAA;AAEnC,EAAA,OAAO,CAAC,MAAM,IAAA,KAAS;AACrB,I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MAAM,SAAS,CAAA,CAAE,MAAA,KAAW,MAAA,GAAY,IAAA,CAAK,gBAAgB,CAAA,CAAE,MAAA;AAC/D,MAAA,OAAO,CAAC;AAAA,QACN,IAAA,EAAM,MAAA;AAAA,QACN,MAAM,WAAA,CAAY,OAAA,EAAS,QAAA,CAAS,SAAA,CAAU,IAAI,CAAC,CAAA;AAAA,QACnD,GAAI,IAAA,GAAO,EAAE,IAAA,KAAS,EAAC;AAAA,QACvB,GAAI,MAAA,GAAS,EAAE,MAAA,KAAW;AAAC,OAC5B,CAAA;AAAA,IACH,CAAA;AAAA;AAAA;AAAA,IAGA,UAAA,EAAY,CAAC,IAAA,EAAM,IAAA,KAAS;AAC1B,MAAA,MAAM,OAAA,GAAU,UAAU,IAAI,CAAA;AAC9B,MAAA,OAAO,OAAA,KAAY,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 * 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\n/** Options for {@link labelDerivePose}. `geometry` defaults to the kit's\n * `AUTO_POSE_DESCRIPTOR`. */\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 { portCurvePoints } from '@weasel-js/geom';\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. */\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. The rule is `portCurvePoints`\n * in `@weasel-js/geom`, which states it over loose components so the 3D kernel\n * can route by the same one. Sampled rather than emitted as curve commands so\n * every router returns the same thing; `edgePath` is free to emit curves later\n * 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 outN = i === 1 ? req.from.normal : null;\n const inN = i === stops.length - 1 ? req.to.normal : null;\n const leg = portCurvePoints(\n a.x, a.y, b.x, b.y,\n outN == null ? null : [outN.x, outN.y],\n inN == null ? null : [inN.x, inN.y],\n BEZIER_SAMPLES,\n );\n for (const [x, y] of leg) out.push({ x, y });\n }\n return out;\n};\n\nconst BEZIER_SAMPLES = 16;\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\n/** Options for {@link edgeDerivePath}. */\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\n/** Options for {@link createPortAffordance}: which ports show, and how they\n * are painted and hit. */\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\n/** Options for {@link createConnectAction}. Only `participants` is required. */\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\n/** The connect action's options and the port affordance's, in one bag. */\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/math';\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\n/** Options for {@link buildGraph}: how the trait is read, and how a pose\n * yields bounds. Both default to the kit's own. */\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 * 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\n/** Options for {@link applyLayout}. */\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\n/** Options for {@link createLayoutAction}. Only `source` is required. */\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 useLatest,\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\n/** One frame of a live layout, called once per frame until it reports `done`. */\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\n/** Options for {@link forceProducer}. */\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 /** The run is at rest once no node moves this far in a tick, in world units.\n * Default 0.1. `0` never rests, leaving the run to the cooling schedule. */\n restDistance?: number;\n /** Consecutive ticks at rest before the run finishes. Default 5. */\n restTicks?: number;\n}\n\nconst REST_DISTANCE = 0.1;\nconst REST_TICKS = 5;\n\n/**\n * A relaxation, one tick a frame, done when the graph stops moving.\n *\n * Motion ends long before alpha cools — a few dozen ticks against three\n * hundred — so a run that waited for alpha would sit visibly still for\n * seconds while still reporting itself running. It finishes on whichever\n * comes first: `restTicks` ticks in a row with no node moving `restDistance`,\n * or the cooling schedule running out. Nothing rests while a node is held.\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 const restDistance = opts.restDistance ?? REST_DISTANCE;\n const restTicks = opts.restTicks ?? REST_TICKS;\n const was = relaxation.bodies.map((b) => ({ x: b.x, y: b.y }));\n let still = 0;\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\n let moved = 0;\n relaxation.bodies.forEach((body, i) => {\n const at = was[i]!;\n moved = Math.max(moved, Math.hypot(body.x - at.x, body.y - at.y));\n at.x = body.x;\n at.y = body.y;\n });\n still = pinned.size === 0 && moved < restDistance ? still + 1 : 0;\n\n const done = still >= restTicks || relaxation.sim.isSettled();\n return { result: relaxation.placed(), done };\n };\n}\n\n/** Options for {@link easedProducer}. */\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\n/** Options for {@link useLiveLayout}. Only `scene` and `source` are required. */\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 /** The relaxation's forces, and when a live run of it counts as at rest. */\n force?: Omit<ForceProducerOptions<TPose>, 'geometry'>;\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\n/** Controls for a live layout run, from {@link useLiveLayout}. */\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 = useLatest(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 }, [optsRef]);\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 }, [optsRef]);\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, optsRef]);\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\n/** Options for {@link diagramShape} and {@link registerDiagramShape}. */\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"]}
1
+ {"version":3,"sources":["../src/label.ts","../src/edge.ts","../src/portAffordance.ts","../src/connect.ts","../src/portLayer.ts","../src/contribution.ts","../src/graph.ts","../src/layoutAction.ts","../src/live.ts","../src/shape.ts"],"names":["AUTO_POSE_DESCRIPTOR","translatePoseViaDescriptor"],"mappings":";;;;;;;AA4BA,IAAM,QAAQ,EAAE,KAAA,EAAO,GAAG,GAAA,EAAK,GAAA,EAAK,KAAK,CAAA,EAAE;AAGpC,SAAS,eAAe,IAAA,EAA8C;AAC3E,EAAA,MAAM,OAAO,IAAA,CAAK,IAAA;AAClB,EAAA,IAAI,IAAA,KAAS,IAAA,IAAQ,OAAO,IAAA,KAAS,UAAU,OAAO,IAAA;AACtD,EAAA,MAAM,QA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ge: 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\n/** Options for {@link labelDerivePose}. `geometry` defaults to the kit's\n * `AUTO_POSE_DESCRIPTOR`. */\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 { portCurvePoints } from '@weasel-js/geom';\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. */\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. The rule is `portCurvePoints`\n * in `@weasel-js/geom`, which states it over loose components so the 3D kernel\n * can route by the same one. Sampled rather than emitted as curve commands so\n * every router returns the same thing; `edgePath` is free to emit curves later\n * 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 outN = i === 1 ? req.from.normal : null;\n const inN = i === stops.length - 1 ? req.to.normal : null;\n const leg = portCurvePoints(\n a.x, a.y, b.x, b.y,\n outN == null ? null : [outN.x, outN.y],\n inN == null ? null : [inN.x, inN.y],\n BEZIER_SAMPLES,\n );\n for (const [x, y] of leg) out.push({ x, y });\n }\n return out;\n};\n\nconst BEZIER_SAMPLES = 16;\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\n/** Options for {@link edgeDerivePath}. */\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\n/** Options for {@link createPortAffordance}: which ports show, and how they\n * are painted and hit. */\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\n/** Options for {@link createConnectAction}. Only `participants` is required. */\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: { read(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\n/** The connect action's options and the port affordance's, in one bag. */\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/math';\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\n/** Options for {@link buildGraph}: how the trait is read, and how a pose\n * yields bounds. Both default to the kit's own. */\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 * 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\n/** Options for {@link applyLayout}. */\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\n/** Options for {@link createLayoutAction}. Only `source` is required. */\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 useLatest,\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\n/** One frame of a live layout, called once per frame until it reports `done`. */\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\n/** Options for {@link forceProducer}. */\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 /** The run is at rest once no node moves this far in a tick, in world units.\n * Default 0.1. `0` never rests, leaving the run to the cooling schedule. */\n restDistance?: number;\n /** Consecutive ticks at rest before the run finishes. Default 5. */\n restTicks?: number;\n}\n\nconst REST_DISTANCE = 0.1;\nconst REST_TICKS = 5;\n\n/**\n * A relaxation, one tick a frame, done when the graph stops moving.\n *\n * Motion ends long before alpha cools — a few dozen ticks against three\n * hundred — so a run that waited for alpha would sit visibly still for\n * seconds while still reporting itself running. It finishes on whichever\n * comes first: `restTicks` ticks in a row with no node moving `restDistance`,\n * or the cooling schedule running out. Nothing rests while a node is held.\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 const restDistance = opts.restDistance ?? REST_DISTANCE;\n const restTicks = opts.restTicks ?? REST_TICKS;\n const was = relaxation.bodies.map((b) => ({ x: b.x, y: b.y }));\n let still = 0;\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\n let moved = 0;\n relaxation.bodies.forEach((body, i) => {\n const at = was[i]!;\n moved = Math.max(moved, Math.hypot(body.x - at.x, body.y - at.y));\n at.x = body.x;\n at.y = body.y;\n });\n still = pinned.size === 0 && moved < restDistance ? still + 1 : 0;\n\n const done = still >= restTicks || relaxation.sim.isSettled();\n return { result: relaxation.placed(), done };\n };\n}\n\n/** Options for {@link easedProducer}. */\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\n/** Options for {@link useLiveLayout}. Only `scene` and `source` are required. */\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 /** The relaxation's forces, and when a live run of it counts as at rest. */\n force?: Omit<ForceProducerOptions<TPose>, 'geometry'>;\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\n/** Controls for a live layout run, from {@link useLiveLayout}. */\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 = useLatest(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 }, [optsRef]);\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 }, [optsRef]);\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, optsRef]);\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\n/** Options for {@link diagramShape} and {@link registerDiagramShape}. */\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.7.2",
3
+ "version": "1.8.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",
@@ -21,8 +21,8 @@
21
21
  },
22
22
  "peerDependencies": {
23
23
  "react": ">=18",
24
- "@weasel-js/core": "1.7.2",
25
- "@weasel-js/geom": "1.7.2"
24
+ "@weasel-js/core": "1.8.0",
25
+ "@weasel-js/geom": "1.8.0"
26
26
  },
27
27
  "author": "orochi235",
28
28
  "homepage": "https://orochi235.github.io/weasel/",