@weasel-js/diagram 1.10.1 → 1.11.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/portAffordance.ts","../src/connectTargets.ts","../src/connect.ts","../src/containers/canDropInto.ts","../src/theme/themeWrites.ts","../src/containers/containerStencils.ts","../src/containers/laneBoundaryLayer.ts","../src/containers/containerActions.ts","../src/containers/containerTitle.ts","../src/hops/hopsAction.ts","../src/labelDragAction.ts","../src/labelCommands.ts","../src/portLayer.ts","../src/edgeEndLayer.ts","../src/waypoints.ts","../src/waypointLayer.ts","../src/routeSnapSource.ts","../src/waypointAction.ts","../src/routeCommands.ts","../src/routerCommands.ts","../src/contribution.ts","../src/avoid/sceneInput.ts","../src/avoid/specRoutes.ts","../src/hops/sceneEdges.ts","../src/hops/specHops.ts","../src/reconnect.ts","../src/reorderSlide.ts","../src/reorder.ts","../src/overlays.tsx","../src/reorderModel.ts","../src/groupReorder.ts","../src/labels/specLabels.ts","../src/resizable.ts","../src/routeWrites.ts","../src/layoutAction.ts","../src/liveProducers.ts","../src/livePlan.ts","../src/liveRoutes.ts","../src/live.ts","../src/shape.ts","../src/mirrorSelection.ts","../src/regionSync.ts","../src/sceneSync.ts","../src/regionEditing.ts","../src/diagramEditing.ts","../src/usePagesView.ts","../src/DiagramView.tsx"],"names":["paintOf","AUTO_POSE_DESCRIPTOR","inside","toward","look","at","membersOf","members","viewToTransform","ellipsePath","paintsLayer","along","ActionDisabledReason","center","NO_MODIFIERS","effectivePose","composeAffordanceLayer","p","DEFAULT_HIT_PX","DEFAULT_SIZE_PX","out","DEFAULT_FILL","DEFAULT_STROKE","routeOf","documentPose","DEFAULT_SNAP","boxes","moveOf","bodyPredicate","useLatest","onBody","near","translatePoseViaDescriptor","useRef","useMemo","useEffect","useCallback","held","polylineFromPoints","portsOf","DiagramView","avoid"],"mappings":";;;;;;;;;;;AAmCO,IAAM,aAAA,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,CAAC,CAAC,CAAA;AAC3C,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,CAAA;AAAA,IACA,CAAA;AAAA,IACA,KAAA,EAAO,IAAA,CAAK,GAAA,CAAI,GAAG,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,CAAA,GAAI,CAAA,CAAE,KAAK,CAAC,CAAA,GAAI,CAAA;AAAA,IACtD,MAAA,EAAQ,IAAA,CAAK,GAAA,CAAI,GAAG,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,KAAM,CAAA,CAAE,CAAA,GAAI,CAAA,CAAE,MAAM,CAAC,CAAA,GAAI;AAAA,GAC1D;AACA,EAAA,OAAO,eAAA,CAAgB,MAAA,EAAQ,IAAA,EAAM,EAAE,GAAG,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,KAAA,EAAO,EAAE,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAA,IAAI,EAAG;AAAA,IAC1E,QAAA,EAAU,IAAI,QAAA,IAAY,CAAA;AAAA,IAC1B,GAAI,IAAI,QAAA,KAAa,MAAA,GAAY,EAAE,QAAA,EAAU,GAAA,CAAI,QAAA,EAAS,GAAI,EAAC;AAAA,IAC/D,GAAI,IAAI,MAAA,KAAW,MAAA,GAAY,EAAE,MAAA,EAAQ,GAAA,CAAI,MAAA,EAAO,GAAI,EAAC;AAAA,IACzD,GAAI,IAAI,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,GAAA,CAAI,OAAA,EAAQ,GAAI;AAAC,GAC7D,CAAA;AACH","file":"chunk-CI3I3I6T.js","sourcesContent":["/**\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. The\n * walk runs on every pointerdown before any tool sees the event, so a port\n * answers 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 CommandStroke,\n CursorSpec,\n PoseDescriptor,\n CommandFill,\n} from '@weasel-js/core';\nimport { ellipsePath, paintsLayer, viewToTransform } 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 /** Not drawn: on a hidden layer, or hidden on its own or by an ancestor.\n * `sceneParticipants` answers it from the scene's `nodeGates`. */\n hidden?: boolean;\n /** Out of reach: locked, or on a locked layer. */\n locked?: boolean;\n /** The scene layer the node is painted on, which the asking view may not\n * paint (`ChromeState.layerIsPainted`, `ViewApi.layerIsPainted`). */\n layer?: string;\n}\n\n/** Whether a participant's ports are drawn, grabbed and landed on. A hidden\n * or locked node gets none, as it gets no selection or hover chrome either,\n * and nor does one on a layer the asking view does not paint. */\nexport function offersPorts(\n p: { hidden?: boolean; locked?: boolean; layer?: string },\n view?: Parameters<typeof paintsLayer>[0],\n): boolean {\n return p.hidden !== true && p.locked !== true && paintsLayer(view, p.layer);\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 /** Which of a participant's ports show. Default: all of them. A port\n * this turns away is not painted or grabbable, and passed with the connect\n * options (as `diagramPorts` and `DiagramView` do), no connect lands on it. */\n showsPort?: (port: Port) => boolean;\n /** Screen-pixel hit radius. Default 8, the kit's `HANDLE_BASE_PX`. */\n hitRadiusPx?: number;\n /** Screen-pixel size of the painted mark: a square's side, or a circle's\n * diameter. Default 7. Omit `paint` entirely by passing 0 — a port the\n * consumer draws itself is still hittable. */\n sizePx?: number;\n /** One fill for every port, or a function of the port — its `type`, say. */\n fill?: CommandFill | ((port: Port) => CommandFill);\n stroke?: CommandStroke;\n /** Default `'square'`. */\n shape?: 'square' | 'circle';\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\nfunction withPaint(paint: AffordanceRegion['paint']): { paint?: NonNullable<AffordanceRegion['paint']> } {\n return paint === undefined ? {} : { paint };\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 paintOf = (port: Port): AffordanceRegion['paint'] => {\n if (sizePx <= 0) return undefined;\n const fill = typeof opts.fill === 'function' ? opts.fill(port) : opts.fill;\n const look = { ...(fill ? { fill } : {}), ...(opts.stroke ? { stroke: opts.stroke } : {}) };\n if (opts.shape !== 'circle') return { kind: 'square', sizePx, ...look };\n return {\n kind: 'custom',\n // An affordance layer paints in screen pixels, so the mark stays one size at any zoom.\n draw: ({ world, view }) => {\n const t = viewToTransform(view);\n const x = t.panX + world.x * t.zoom.x - sizePx / 2;\n const y = t.panY + world.y * t.zoom.y - sizePx / 2;\n return [{ kind: 'path', path: ellipsePath({ x, y, width: sizePx, height: sizePx }), ...look }];\n },\n };\n };\n\n return {\n id,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const participant of participants()) {\n if (!offersPorts(participant, state)) continue;\n const { node, pose } = participant;\n if (opts.shows !== undefined && !opts.shows(node, state)) continue;\n for (const port of portsOf(node, pose, portOpts)) {\n if (opts.showsPort !== undefined && !opts.showsPort(port)) continue;\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 ...withPaint(paintOf(port)),\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 * What a connect may run from and land on: a port, or a participant's body.\n *\n * A body end is Visio's dynamic glue. It names the shape and not a port, and\n * the edge resolves to whichever port faces the other end each time it is\n * routed (`resolveEnd`), so it follows the shape around as things move.\n */\nimport type { DerivedDep } from '@weasel-js/core';\nimport {\n AUTO_POSE_DESCRIPTOR,\n rotatePoint,\n type PoseDescriptor,\n type Vec2,\n} from '@weasel-js/core/math';\nimport { pathContainsPoint } from '@weasel-js/geom';\nimport { boxCenter, endAims, resolveEnd, type Router } from './edge';\nimport { diagramEdgeOf } from './edgeTrait';\nimport { diagramGroupOf } from './group';\nimport { diagramLabelOf } from './labelTrait';\nimport { outlinePath } from './outline';\nimport { offersPorts, type ParticipantPose, type ParticipantSource } from './portAffordance';\nimport { portsOf, type PortsOptions } from './ports';\nimport { diagramNodeOf } from './trait';\nimport type { Port } from './types';\n\n/** An end on a participant's body rather than on one of its ports. `point` is\n * where the pointer was, in world coordinates. */\nexport interface BodyEnd {\n kind: 'body';\n nodeId: string;\n point: Vec2;\n}\n\n/** Either end of a connect. */\nexport type ConnectEnd = Port | BodyEnd;\n\n/** Whether a connect end lands on a node's body rather than a port. */\nexport function isBodyEnd(end: ConnectEnd): end is BodyEnd {\n return (end as { kind?: unknown }).kind === 'body';\n}\n\n/** A body under the pointer, and the participant it belongs to. */\nexport interface BodyHit<TPose> {\n end: BodyEnd;\n participant: ParticipantPose<TPose>;\n}\n\n/** The view a connect started in, which decides what layers it may reach. */\nexport type ConnectView = Parameters<typeof offersPorts>[1];\n\n/**\n * The topmost participant whose body contains `at`, or `null`.\n *\n * Its outline when it declares one, else its bounds, both taken in the pose's\n * unrotated frame. Edges, edge labels and group boxes are not bodies, and nor\n * is anything the reader does not take as a participant or that `offersPorts`\n * turns away.\n */\nexport function bodyAt<TPose>(\n participants: ParticipantSource<TPose>,\n at: Vec2,\n opts: PortsOptions<TPose> & { view?: ConnectView } = {},\n): BodyHit<TPose> | null {\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n let hit: BodyHit<TPose> | null = null;\n // Render order, so the last match is the one drawn on top.\n for (const participant of participants()) {\n const { node } = participant;\n if (!offersPorts(participant, opts.view)) continue;\n if (diagramEdgeOf(node) !== null || diagramLabelOf(node) !== null || diagramGroupOf(node) !== null) continue;\n const trait = diagramNodeOf(node, opts.read);\n if (trait === null || trait.group !== undefined) continue;\n const bounds = geometry.getBounds(participant.pose);\n if (bounds.width <= 0 || bounds.height <= 0) continue;\n const rotation = geometry.getRotation?.(participant.pose) ?? 0;\n const local = rotation === 0\n ? at\n : rotatePoint(at.x, at.y, bounds.x + bounds.width / 2, bounds.y + bounds.height / 2, -rotation);\n const inside = trait.outline === undefined\n ? local.x >= bounds.x && local.x <= bounds.x + bounds.width\n && local.y >= bounds.y && local.y <= bounds.y + bounds.height\n : pathContainsPoint(outlinePath(trait.outline, bounds), local.x, local.y);\n if (inside) hit = { end: { kind: 'body', nodeId: node.id, point: { x: at.x, y: at.y } }, participant };\n }\n return hit;\n}\n\n/** What {@link createTargets} needs from the connect action's options. */\nexport interface TargetOptions<TPose> extends PortsOptions<TPose> {\n participants: ParticipantSource<TPose>;\n /** Asked with the end that stays put first, and the candidate second. */\n canConnect: (fixed: ConnectEnd, candidate: ConnectEnd) => boolean;\n showsPort?: (port: Port) => boolean;\n snapRadius: number;\n bodies: boolean;\n}\n\n/** One resolver for what a connect lands on, and the port each end is drawn\n * to, shared by the preview and the commit. */\nexport function createTargets<TPose>(opts: TargetOptions<TPose>) {\n const portOpts: PortsOptions<TPose> = {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n };\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n\n /** The port the pointer is over and may legally land on, or `null`. */\n function portTarget(from: ConnectEnd, at: Vec2, view: ConnectView): Port | null {\n let best: Port | null = null;\n let bestD2 = opts.snapRadius * opts.snapRadius;\n for (const participant of opts.participants()) {\n if (!offersPorts(participant, view)) continue;\n for (const port of portsOf(participant.node, participant.pose, portOpts)) {\n if (opts.showsPort !== undefined && !opts.showsPort(port)) continue;\n if (!opts.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 /** What a release at `at` lands on: a port in reach beats the body under it.\n * A body with no ports is no target, since an edge glued to it has nothing\n * to route to. */\n function target(from: ConnectEnd, at: Vec2, view: ConnectView): ConnectEnd | null {\n const port = portTarget(from, at, view);\n if (port !== null || !opts.bodies) return port;\n const body = bodyAt(opts.participants, at, { ...portOpts, view });\n if (body === null || portsOf(body.participant.node, body.participant.pose, portOpts).length === 0) return null;\n return opts.canConnect(from, body.end) ? body.end : null;\n }\n\n function participantOf(nodeId: string): ParticipantPose<TPose> | undefined {\n for (const participant of opts.participants()) {\n if (participant.node.id === nodeId) return participant;\n }\n return undefined;\n }\n\n /** The center an end is aimed by, as the edge router takes it: its node's,\n * else its own point. */\n function centerOf(end: ConnectEnd): Vec2 {\n const participant = participantOf(end.nodeId);\n return participant === undefined ? end.point : boxCenter(geometry, participant.pose);\n }\n\n /** The port an end is drawn to: itself, or for a body, the port facing\n * `toward` — the one the committed edge will resolve to. */\n function portFor(end: ConnectEnd, toward: Vec2): Port | null {\n if (!isBodyEnd(end)) return end;\n const participant = participantOf(end.nodeId);\n if (participant === undefined) return null;\n const dep = { node: participant.node, pose: participant.pose } as unknown as DerivedDep<TPose>;\n const all = (d: DerivedDep<TPose>): Port[] => portsOf(d.node as never, d.pose, portOpts);\n return resolveEnd({}, dep, toward, portOpts, all) ?? null;\n }\n\n /**\n * The run an edge would take with `fixed` at one end and the other released\n * at `at`: snapped to the target there, else to the bare point, which as a\n * port with no facing a router aims straight at. `moving` says which end of\n * the edge the pointer carries, so the run is routed in the edge's direction,\n * through `waypoints` in that direction, each end aimed as `endAims` aims a\n * committed edge's.\n */\n function preview(\n route: Router,\n fixed: ConnectEnd,\n at: Vec2,\n view: ConnectView,\n moving: 'from' | 'to' = 'to',\n waypoints: readonly Vec2[] = [],\n ): readonly Vec2[] {\n const landed = target(fixed, at, view);\n const [fixedCenter, landedCenter] = [centerOf(fixed), landed === null ? at : centerOf(landed)];\n const aims = moving === 'to'\n ? endAims(fixedCenter, landedCenter, waypoints)\n : endAims(landedCenter, fixedCenter, waypoints);\n const [fixedAim, landedAim] = moving === 'to' ? [aims.from, aims.to] : [aims.to, aims.from];\n const free = landed === null\n ? { id: '', nodeId: '', point: at, normal: null }\n : portFor(landed, landedAim);\n const anchored = portFor(fixed, fixedAim);\n if (free === null || anchored === null) return [];\n return moving === 'to'\n ? route({ from: anchored, to: free, waypoints })\n : route({ from: free, to: anchored, waypoints });\n }\n\n return { target, portFor, preview };\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, and a press that is *not* on\n * a port falls through to the tool that wants it.\n *\n * *Which presses start a connect* is routing, and belongs to the binding spec.\n * *Which ports a live connect may land on* cannot be routing — the dispatcher\n * never re-reads the affordance under a moving pointer — so `canConnect`\n * filters the candidate set: the preview will not snap to an illegal port and\n * a release over it commits nothing.\n *\n * One resolver answers both the live preview and the commit, so the preview\n * cannot lie about what releasing will do.\n *\n * With `bodies`, a release over a participant's body away from any port lands\n * on the body (`connectTargets`); with `startFrom: 'body'`, so can the press.\n */\nimport {\n type Action,\n type GestureBinding,\n type InvocationCtx,\n type OngoingHandle,\n type OngoingOverlay,\n type PoseDescriptor,\n type Stroke,\n type Vec2,\n} from '@weasel-js/core';\nimport { bodyAt, createTargets, isBodyEnd, type ConnectEnd } from './connectTargets';\nimport { EDGE_DERIVE_PATH, ROUTERS, type Router } from './edge';\nimport type { DiagramEdge, EdgeEnd } from './edgeTrait';\nimport { PORT_AFFORDANCE_KIND, portScratchOf, type ParticipantSource } from './portAffordance';\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/** The edge end a reconnect is carrying: the scene id of the edge, and which end. */\nexport interface MovingEnd {\n edge: string;\n end: 'from' | 'to';\n}\n\n/** Whether an edge may run from `from` to `to`. `moving` is the end being\n * dragged when the edge already exists, and absent for a new connect. */\nexport type CanConnect = (from: ConnectEnd, to: ConnectEnd, moving?: MovingEnd) => boolean;\n\n/** The edge a finished connect describes. Each end is a resolved port, or a\n * body whose port the edge picks each time it is routed. */\nexport interface PendingEdge {\n from: ConnectEnd;\n to: ConnectEnd;\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. Two different ports on the *same node*\n * may be joined: a self-edge is meaningful in a state machine. A body is\n * untyped, and never joins its own node.\n */\nexport const defaultCanConnect: CanConnect = (from, to) => {\n if (isBodyEnd(from) || isBodyEnd(to)) return from.nodeId !== to.nodeId;\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 /** Which ports a connect may land on: a port this turns away is never a\n * target. The port affordance's option of the same name, so a port that is\n * not shown cannot be dropped onto. Default: all of them. */\n showsPort?: (port: Port) => boolean;\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 /** A release over a participant's body, with no port in reach, lands on the\n * body. Default false. */\n bodies?: boolean;\n /** `'body'`: a press that is not on a port starts from the participant\n * under it. Default `'port'`, where such a press falls through. */\n startFrom?: 'port' | 'body';\n /**\n * Mints and commits the edge. Called once, on release over a valid target.\n *\n * Defaults to {@link commitEdgeToScene} against `deps.scene`. Override it to\n * choose the edge node's data, its layer, or its stroke.\n */\n commit?: (edge: PendingEdge, ctx: InvocationCtx) => void;\n /** What the default commit draws the edge with. Default {@link DEFAULT_EDGE_STROKE}.\n * Ignored when `commit` is given. */\n edgeStroke?: Stroke;\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: ConnectEnd;\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 it.\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.\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. `kind`\n * names another affordance that claims the press protocol the same way. */\nexport function grabPortBindings(\n actionId: string = GRAB_PORT_ACTION_ID,\n kind: string = PORT_AFFORDANCE_KIND,\n): GestureBinding[] {\n return [\n { spec: { kind: 'pointerDown', target: `affordance:${kind}` }, actionId },\n { spec: { kind: 'click', target: `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.\n */\nexport function commitEdgeToScene(\n edge: PendingEdge, ctx: InvocationCtx, opts: { stroke?: Stroke } = {},\n): void {\n const scene = ctx.deps.scene;\n if (scene === undefined) return;\n const trait: DiagramEdge = {\n from: edgeEndOf(edge.from),\n to: edgeEndOf(edge.to),\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 data: { diagram: trait, stroke: opts.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/** A body end names no port, so the edge resolves the facing one. */\nexport function edgeEndOf(end: ConnectEnd): EdgeEnd {\n return isBodyEnd(end) ? {} : { port: end.id };\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 */\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 } = opts;\n const stroke = opts.edgeStroke;\n const commit = opts.commit\n ?? ((edge: PendingEdge, ctx: InvocationCtx) => commitEdgeToScene(edge, ctx, stroke ? { stroke } : {}));\n const routers = opts.routers ?? ROUTERS;\n const route: Router = routers[routerKey] ?? routers['straight'] ?? ROUTERS['straight']!;\n const targets = createTargets({ ...opts, canConnect, snapRadius, bodies: opts.bodies ?? false });\n\n /** What the press starts from: the pressed port, else — with\n * `startFrom: 'body'` — the body under the pointer. */\n function startEnd(ctx: InvocationCtx): ConnectEnd | null {\n const pressed = portScratchOf(ctx.drag?.affordance);\n if (pressed !== null) return pressed.port;\n if (opts.startFrom !== 'body') return null;\n return bodyAt(opts.participants, ctx.world, { ...opts, view: ctx.deps.view })?.end ?? null;\n }\n\n return {\n id,\n label: 'Connect',\n group: 'diagram',\n requires: ['scene', 'view'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const from = startEnd(ctx);\n // Nothing to start from. The binding spec is the gate; this is the\n // backstop, and an empty handle is how the dispatcher is told to fall\n // through.\n if (from === null) return {};\n const scratch: ConnectScratch = {\n from,\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 points = targets.preview(route, scratch.from, scratch.current, scratch.deps.view);\n if (points.length < 2) return null;\n // How a connector reads belongs to whatever surface paints the role.\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 to = targets.target(scratch.from, { x: endCtx.world.x, y: endCtx.world.y }, scratch.deps.view);\n if (to === null) return;\n // World and modifiers from the release; deps from the press.\n commit(\n { from: scratch.from, to, router: routerKey },\n { ...endCtx, deps: scratch.deps },\n );\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n","import { diagramEdgeOf } from '../edgeTrait';\nimport { diagramLabelOf } from '../labelTrait';\nimport { dataKeyReader } from '../trait';\nimport { bodyBox, diagramContainerOf, type ContainerRole } from './trait';\n\ntype SceneLike = { get(id: never): { id: string; kind: 'leaf' | 'container'; data: unknown } | undefined };\n\n/**\n * The `canDropInto` dep for a diagram scene. A container or a lane takes\n * shapes and other containers, a pool takes only lanes, and a lane goes\n * nowhere but a pool. A stencil body, an edge, or a label takes nothing, and\n * edges and labels are never dropped in: they stay where they are, drawn from\n * what they are attached to. Any other container — a plain group — takes\n * anything but a lane.\n */\nexport function diagramCanDropInto(scene: SceneLike): (parent: string, ids: readonly string[]) => boolean {\n const nodeOf = (id: string) => scene.get(id as never);\n const roleOf = (id: string) => {\n const node = nodeOf(id);\n return node === undefined ? null : diagramContainerOf(node)?.role ?? null;\n };\n const attached = (id: string) => {\n const node = nodeOf(id);\n return node !== undefined && (diagramEdgeOf(node) !== null || diagramLabelOf(node) !== null);\n };\n return (parent, ids) => {\n const node = nodeOf(parent);\n if (node === undefined || ids.some(attached)) return false;\n const role = roleOf(parent);\n if (role === 'pool') return ids.every((id) => roleOf(id) === 'lane');\n if (ids.some((id) => roleOf(id) === 'lane')) return false;\n if (role !== null) return ids.every((id) => roleOf(id) !== 'pool');\n return !attached(parent) && dataKeyReader(node) === null;\n };\n}\n\n/** What {@link diagramDropParentAt} walks. */\nexport interface DropParentScene {\n readonly roots: readonly string[];\n childrenOf(id: never): readonly string[];\n get(id: never): { id: string; kind: 'leaf' | 'container'; data: unknown; pose: unknown } | undefined;\n}\n\n/**\n * The innermost container or lane whose body holds `point`, that would admit\n * a new node of `role` (`null` for a shape): where an insert at `point` goes.\n * Null for the top level — always so for a pool.\n */\nexport function diagramDropParentAt(\n scene: DropParentScene,\n point: { x: number; y: number },\n role: ContainerRole | null,\n): string | null {\n if (role === 'pool' || role === 'lane') return null;\n let best: string | null = null;\n const walk = (ids: readonly string[]): void => {\n for (const id of ids) {\n const node = scene.get(id as never);\n if (node === undefined || node.kind !== 'container') continue;\n const trait = diagramContainerOf(node);\n const b = bodyBox(node.pose as { x: number; y: number; width: number; height: number }, trait?.header);\n const inside = point.x >= b.x && point.x < b.x + b.width && point.y >= b.y && point.y < b.y + b.height;\n if (!inside) continue;\n if (trait?.role === 'container' || trait?.role === 'lane') best = id;\n walk(scene.childrenOf(id as never));\n }\n };\n walk(scene.roots);\n return best;\n}\n","/**\n * What applying a theme writes: every color the theme owns, on every box,\n * text row, connector, label, and off-page tag, as new node `data`. A color named in the\n * owner's `ownStyle` is the author's, and stays.\n */\nimport type { NodeStyle } from '../fromData';\nimport { roleEdgeStyle, roleStyle, themeLabelFamily, themeLabelFont } from './resolve';\nimport type { DiagramTheme, FontField, StyleField } from './types';\n\n/** A scene node as {@link themeWrites} reads it. */\nexport interface ThemedNode {\n id: string;\n parent: string | null;\n data: unknown;\n dependsOn?: readonly string[] | 'children';\n}\n\n/** A scene as {@link themeWrites} reads it. */\nexport interface ThemedScene {\n get(id: never): ThemedNode | undefined;\n renderOrderNodes(): readonly ThemedNode[];\n childrenOf(id: never): readonly string[];\n}\n\ntype Trait = Record<string, unknown> & { style?: string; ownStyle?: readonly StyleField[]; ownFont?: readonly FontField[] };\ntype Paint = { paint?: { color?: string } & Record<string, unknown> } & Record<string, unknown>;\ntype Data = Record<string, unknown> & { diagram?: Trait; fill?: Paint; stroke?: Paint; text?: unknown; style?: Record<string, unknown> };\n\n/** A box's colors, and the ones its author set, and whether the author set its text size. Its text\n * rows take `style.text`. */\ninterface Look { style: NodeStyle; own: ReadonlySet<StyleField>; ownSize: boolean }\n\nconst traitOf = (data: unknown): Trait | null => {\n const d = (data as Data | null)?.diagram;\n return d !== null && typeof d === 'object' ? d : null;\n};\n\nconst ownOf = (trait: Trait): ReadonlySet<StyleField> => new Set(trait.ownStyle ?? []);\nconst ownsSize = (trait: Trait): boolean => trait.ownFont?.includes('size') === true;\n\n/** A container's role, as the containers trait (`data.diagram.container`) names it. */\nfunction containerRole(trait: Trait): string | null {\n const c = trait.container as { role?: unknown } | undefined;\n return c !== null && typeof c === 'object' && typeof c.role === 'string' ? c.role : null;\n}\n\nfunction laneIndex(scene: ThemedScene, node: ThemedNode): number {\n if (node.parent === null) return 0;\n const lanes = scene.childrenOf(node.parent as never).filter((id) => {\n const t = traitOf(scene.get(id as never)?.data);\n return t !== null && containerRole(t) === 'lane';\n });\n return Math.max(0, lanes.indexOf(node.id));\n}\n\n/** The look a box takes from `theme`: a body its role's, a group or container the theme's\n * container, a pool its lane header, a lane the lane bodies in turn. `null` for no box. */\nfunction boxLook(scene: ThemedScene, node: ThemedNode, theme: DiagramTheme): Look | null {\n const trait = traitOf(node.data);\n if (trait === null || 'from' in trait || 'label' in trait || 'anchor' in trait || 'mark' in trait) return null;\n const own = ownOf(trait);\n const ownSize = ownsSize(trait);\n const role = containerRole(trait);\n if (role === 'pool') return { style: theme.lane.header, own, ownSize };\n if (role === 'lane') {\n const bodies = theme.lane.bodies;\n return { style: bodies[laneIndex(scene, node) % bodies.length] ?? theme.container, own, ownSize };\n }\n if (role !== null || 'group' in trait) return { style: theme.container, own, ownSize };\n return { style: roleStyle(theme, trait.style), own, ownSize };\n}\n\nconst recolored = (paint: Paint | undefined, color: string): Paint | undefined =>\n paint?.paint?.color === color ? undefined : { ...paint, paint: { ...paint?.paint, color } };\n\n/** `data` with its fill and stroke recolored where the author has not set them, or `null` when\n * nothing changes. */\nfunction paintBox(data: Data, look: Look): Data | null {\n const fill = look.own.has('fill') ? undefined : recolored(data.fill, look.style.fill);\n const stroke = look.own.has('stroke') || data.stroke === undefined ? undefined : recolored(data.stroke, look.style.stroke);\n if (fill === undefined && stroke === undefined) return null;\n return { ...data, ...(fill ? { fill } : {}), ...(stroke ? { stroke } : {}) };\n}\n\n/** `data`'s text recolored to `color` (unless `undefined`), set in `family`, and its size moved by\n * `step`, or `null` when nothing changes. */\nfunction paintText(data: Data, color: string | undefined, family: string, step: number): Data | null {\n const fill = color === undefined ? undefined : recolored(data.fill, color);\n const size = data.style?.fontSize;\n const resized = step !== 0 && typeof size === 'number' ? { fontSize: Math.max(1, size + step) } : {};\n const face = data.style !== undefined && (data.style.fontFamily !== family || 'fontSize' in resized)\n ? { ...data.style, fontFamily: family, ...resized } : undefined;\n if (fill === undefined && face === undefined) return null;\n return { ...data, ...(fill ? { fill } : {}), ...(face ? { style: face } : {}) };\n}\n\n/** An off-page tag's `data` in `theme`'s label color and face, on its page color, its size moved\n * by `step` as an edge label's is, or `null`. */\nfunction paintTag(data: Data, theme: DiagramTheme, step: number): Data | null {\n const text = paintText(data, theme.label.fill, themeLabelFamily(theme), step);\n const background = recolored(data.background as Paint | undefined, theme.page);\n if (text === null && background === undefined) return null;\n return { ...(text ?? data), ...(background ? { background } : {}) };\n}\n\n/** A connector's own colors, and its label's, under `theme`. */\nfunction edgeLook(trait: Trait, theme: DiagramTheme): { stroke: string; label: string; own: ReadonlySet<StyleField>; ownSize: boolean } {\n const style = roleEdgeStyle(theme, trait.style);\n return { stroke: style.stroke, label: style.label ?? style.stroke, own: ownOf(trait), ownSize: ownsSize(trait) };\n}\n\nconst ownerOf = (node: ThemedNode): string | null =>\n Array.isArray(node.dependsOn) && node.dependsOn.length === 1 ? node.dependsOn[0]! : node.parent;\n\n/**\n * The new `data` for every node `theme` recolors: shapes, their text rows,\n * groups and containers and their titles, connectors and their labels. Given\n * `ids`, only those boxes and connectors, and the text that belongs to them.\n * Given `from`, the theme the scene was in, text moves by the step between the\n * two themes' sizes, except where its owner's author set the size. A node\n * already as the theme draws it is left out.\n */\nexport function themeWrites(scene: ThemedScene, theme: DiagramTheme, ids?: ReadonlySet<string>, from?: DiagramTheme): Map<string, unknown> {\n const out = new Map<string, unknown>();\n const step = from === undefined ? 0 : theme.font.size - from.font.size;\n const labelStep = from === undefined ? 0 : themeLabelFont(theme).fontSize - themeLabelFont(from).fontSize;\n const looks = new Map<string, Look | null>();\n const lookOf = (id: string): Look | null => {\n if (!looks.has(id)) {\n const node = scene.get(id as never);\n looks.set(id, node === undefined ? null : boxLook(scene, node, theme));\n }\n return looks.get(id)!;\n };\n const write = (id: string, next: Data | null) => { if (next !== null) out.set(id, next); };\n for (const node of scene.renderOrderNodes()) {\n const data = node.data as Data | null;\n if (data === null || typeof data !== 'object') continue;\n const trait = traitOf(data);\n if (trait !== null && 'from' in trait && 'to' in trait) {\n if (ids !== undefined && !ids.has(node.id)) continue;\n const look = edgeLook(trait, theme);\n const stroke = look.own.has('stroke') || data.stroke === undefined ? undefined : recolored(data.stroke, look.stroke);\n if (stroke !== undefined) out.set(node.id, { ...data, stroke });\n continue;\n }\n if (trait !== null && 'label' in trait) {\n const edgeId = ownerOf(node);\n const edgeTrait = edgeId === null ? null : traitOf(scene.get(edgeId as never)?.data);\n if (edgeId === null || edgeTrait === null || (ids !== undefined && !ids.has(edgeId))) continue;\n const look = edgeLook(edgeTrait, theme);\n write(node.id, paintText(data, look.own.has('text') ? undefined : look.label, themeLabelFamily(theme), look.ownSize ? 0 : labelStep));\n continue;\n }\n if (trait !== null && 'offPageTag' in trait) {\n const edgeId = ownerOf(node);\n if (ids === undefined || (edgeId !== null && ids.has(edgeId))) write(node.id, paintTag(data, theme, labelStep));\n continue;\n }\n if (trait !== null && 'mark' in trait) continue;\n const look = lookOf(node.id);\n if (look !== null) {\n if (ids === undefined || ids.has(node.id)) write(node.id, paintBox(data, look));\n continue;\n }\n // A text row, a port label, or a group's title: colored as the box it belongs to.\n const owner = ownerOf(node);\n const ownerLook = owner === null ? null : lookOf(owner);\n if (ownerLook === null || typeof data.text !== 'string' || (ids !== undefined && !ids.has(owner!))) continue;\n write(node.id, paintText(data, ownerLook.own.has('text') ? undefined : ownerLook.style.text, theme.font.family, ownerLook.ownSize ? 0 : step));\n }\n return out;\n}\n","/**\n * The container stencils a palette offers, what one becomes when it is drawn,\n * and the edits on one: adding a lane to a pool, and releasing a container's\n * members.\n */\nimport { createInsertOp, type NodeId, type Op, type RectPose, type Scene } from '@weasel-js/core';\nimport type { IconRef } from '@weasel-js/icons';\nimport { icon } from '../icons.gen';\nimport type { NodeStyle } from '../dataTypes';\nimport { diagramThemeOf } from '../theme/resolve';\nimport { themeWrites, type ThemedScene } from '../theme/themeWrites';\nimport { DIAGRAM_THEME_KEY } from '../theme/types';\nimport { firstLanes, regionSpecs, type ContainerBuildOptions } from './regionSpecs';\nimport { diagramContainerOf, titleIdOf, type DiagramContainer } from './trait';\n\nexport type { ContainerBuildOptions };\n\n/** One container a palette offers. A pool stacks its lanes along `axis`. */\nexport interface ContainerStencil {\n id: string;\n label: string;\n role: 'container' | 'pool';\n axis?: 'x' | 'y';\n size: { width: number; height: number };\n /** The glyph a palette draws on its button. */\n icon?: IconRef;\n}\n\n/** A titled box, and pools of rows and of columns. */\nexport const CONTAINER_STENCILS: readonly ContainerStencil[] = [\n { id: 'container', label: 'Container', role: 'container', size: { width: 240, height: 160 }, icon: /* @icon */ 'diagram:container' },\n { id: 'pool-rows', label: 'Pool (rows)', role: 'pool', axis: 'y', size: { width: 480, height: 240 }, icon: /* @icon */ 'diagram:poolRows' },\n { id: 'pool-columns', label: 'Pool (columns)', role: 'pool', axis: 'x', size: { width: 480, height: 300 }, icon: /* @icon */ 'diagram:poolColumns' },\n];\n\n/** A lane added to a pool, along its stack. */\nconst NEW_LANE_SIZE = 120;\n\ntype Bounds = { x: number; y: number; width: number; height: number };\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** A zero-size box — a click rather than a drag — becomes the stencil's own size centered on it. */\nfunction placedBounds(stencil: ContainerStencil, b: Bounds): RectPose {\n if (b.width > 0 && b.height > 0) return { ...b };\n const { width, height } = stencil.size;\n return { x: b.x + b.width / 2 - width / 2, y: b.y + b.height / 2 - height / 2, width, height };\n}\n\n/** The ops that insert `stencil` at `bounds`: the region and its title, and a\n * pool's first lanes. Applied as one batch, they are one undo entry. */\nexport function containerBuild<TLayer extends string>(\n stencil: ContainerStencil,\n bounds: Bounds,\n opts: ContainerBuildOptions<TLayer>,\n): { id: string; ops: Op[] } {\n const id = opts.newId();\n const axis = stencil.axis ?? 'y';\n const at = placedBounds(stencil, bounds);\n const title = stencil.role === 'pool' ? 'Pool' : stencil.label;\n const style = stencil.role === 'pool' && opts.laneStyles ? opts.laneStyles.header : opts.style;\n const specs = [\n ...regionSpecs(stencil.role, axis, at, title, {\n id, layer: opts.layer, parent: opts.parent ?? null, ...(style ? { style } : {}),\n }),\n ...(stencil.role === 'pool' ? firstLanes(id, axis, at, opts) : []),\n ];\n const label = `Insert ${stencil.label}`;\n return { id, ops: specs.map((node) => createInsertOp({ node, label })) };\n}\n\n/** The axis a pool stacks its lanes along, read off its header. */\nexport const poolAxisOf = (pool: DiagramContainer): 'x' | 'y' => (pool.header?.side === 'top' ? 'x' : 'y');\n\n/** The lanes of `poolId`, in the order they stack. */\nexport function lanesOf(scene: AnyScene, poolId: string): NodeId[] {\n const pool = scene.get(poolId as NodeId);\n const trait = pool === undefined ? null : diagramContainerOf(pool);\n if (pool === undefined || trait?.role !== 'pool') return [];\n const axis = poolAxisOf(trait);\n const start = (id: NodeId) => {\n const p = scene.get(id)!.pose as RectPose;\n return axis === 'y' ? p.y : p.x;\n };\n return scene.childrenOf(pool.id)\n .filter((id) => diagramContainerOf(scene.get(id)!)?.role === 'lane')\n .sort((a, b) => start(a) - start(b));\n}\n\n/**\n * Add a lane to `poolId` before the lane at `index`, or at the end of the\n * stack, as one history entry. The pool grows to hold it. Returns the new\n * lane's id, or null when `poolId` is not a pool.\n */\nexport function addLane(scene: AnyScene, poolId: string, index?: number, style?: NodeStyle): string | null {\n const pool = scene.get(poolId as NodeId);\n const trait = pool === undefined ? null : diagramContainerOf(pool);\n if (pool === undefined || trait?.role !== 'pool') return null;\n const axis = poolAxisOf(trait);\n const lanes = lanesOf(scene, poolId);\n const b = pool.pose as RectPose;\n const at = index === undefined || index >= lanes.length ? null : scene.get(lanes[index]!)!.pose as RectPose;\n const boundary = at !== null ? (axis === 'y' ? at.y : at.x) : axis === 'y' ? b.y + b.height : b.x + b.width;\n // Centered on the boundary it goes in at: the stack orders lanes by where they sit.\n const start = boundary - NEW_LANE_SIZE / 2;\n const offset = trait.header?.size ?? 0;\n const pose: RectPose = axis === 'y'\n ? { x: b.x + offset, y: start, width: b.width - offset, height: NEW_LANE_SIZE }\n : { x: start, y: b.y + offset, width: NEW_LANE_SIZE, height: b.height - offset };\n const id = scene.mintId() as string;\n const specs = regionSpecs('lane', axis, pose, `Lane ${lanes.length + 1}`, {\n id, layer: pool.layer, parent: poolId, ...(style ? { style } : {}),\n });\n scene.batch('Add lane', () => {\n for (const spec of specs) scene.add(spec as never);\n // A themed scene colors the lane as a theme change would, by its place in the stack.\n if (style === undefined && scene.doc.get(DIAGRAM_THEME_KEY) !== undefined) {\n const writes = themeWrites(scene as unknown as ThemedScene, diagramThemeOf(scene), new Set([id]));\n for (const [at, data] of writes) scene.update(at as never, { data } as never);\n }\n });\n return id;\n}\n\n/** The node a release lands members beside: `id`, or the pool around a lane. */\nfunction releasedFrom(scene: AnyScene, id: NodeId): NodeId {\n const parent = scene.get(id)!.parent;\n const around = parent === null ? undefined : scene.get(parent);\n return around !== undefined && diagramContainerOf(around)?.role === 'pool' ? around.id : id;\n}\n\n/**\n * Remove container `id` and keep its members, which take its place in its\n * parent, as one history entry. A pool's members are its lanes' members, and\n * a lane's go past its pool. Connectors on what is removed go with it.\n */\nexport function releaseMembers(scene: AnyScene, id: string): void {\n const node = scene.get(id as NodeId);\n const trait = node === undefined ? null : diagramContainerOf(node);\n if (node === undefined || trait === null) return;\n const membersOf = (c: NodeId) => scene.childrenOf(c).filter((m) => m !== titleIdOf(c as string));\n const members = trait.role === 'pool' ? membersOf(node.id).flatMap(membersOf) : membersOf(node.id);\n const beside = releasedFrom(scene, node.id);\n const parent = scene.get(beside)!.parent;\n const index = (parent === null ? scene.roots : scene.childrenOf(parent)).indexOf(beside);\n scene.batch('Release members', () => {\n members.forEach((m, k) => scene.move(m, parent, index + k));\n scene.remove(node.id);\n });\n}\n","/**\n * The lane affordances on every pool: the boundary after each lane, which a\n * drag moves to resize that lane, and the add-lane button past the end of the\n * stack. Built the way the edge-end handles are: regions with a `null`\n * `targetId`, composed into a layer whose id is the kind a press reports.\n */\nimport {\n composeAffordanceLayer,\n ellipsePath,\n paintsLayer,\n PathBuilder,\n polylineFromPoints,\n viewToTransform,\n type Affordance,\n type AffordanceRegion,\n type ChromeState,\n type CommandFill,\n type CommandStroke,\n type NodeId,\n type RectPose,\n type RenderLayer,\n type Scene,\n} from '@weasel-js/core';\nimport { lanesOf, poolAxisOf } from './containerStencils';\nimport { diagramContainerOf } from './trait';\n\n/** The layer id the lane affordances are composed into. */\nexport const LANE_LAYER_ID = 'diagram-lanes';\n/** The affordance kind a press on a lane affordance reports. */\nexport const LANE_AFFORDANCE_KIND = `layer:${LANE_LAYER_ID}` as const;\n\n/** What a press on a lane affordance hands the action: the boundary after\n * `laneId`, or, with no lane, the add-lane button. */\nexport interface LaneScratch {\n targetId: string;\n poolId: string;\n laneId?: string;\n}\n\n/** Read a lane press's scratch back off the hit an action was handed. */\nexport function laneScratchOf(hit: { payload?: unknown } | null | undefined): LaneScratch | null {\n const payload = hit?.payload as LaneScratch | undefined;\n return payload !== undefined && typeof payload.poolId === 'string' ? payload : null;\n}\n\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** A pool as the affordances see it: its box, the axis it stacks along, and its lanes in order. */\nexport interface PoolLanes {\n id: string;\n axis: 'x' | 'y';\n pose: RectPose;\n lanes: { id: string; pose: RectPose }[];\n}\n\n/** Every pool in `scene` that is drawn and not locked. */\nexport function poolsOf(scene: AnyScene): PoolLanes[] {\n const out: PoolLanes[] = [];\n for (const node of scene.renderOrderNodes()) {\n const trait = diagramContainerOf(node);\n if (trait?.role !== 'pool' || scene.isHidden(node.id) || scene.isLocked(node.id)) continue;\n out.push({\n id: node.id,\n axis: poolAxisOf(trait),\n pose: node.pose as RectPose,\n lanes: lanesOf(scene, node.id).map((id) => ({ id, pose: scene.get(id)!.pose as RectPose })),\n });\n }\n return out;\n}\n\n/** Options for {@link laneLayer}. */\nexport interface LaneLayerOptions {\n /** Screen-pixel reach of a boundary either side of it. Default 4. */\n hitRadiusPx?: number;\n /** Screen-pixel diameter of the add-lane button. Default 14; 0 hides it. */\n addSizePx?: number;\n fill?: CommandFill;\n stroke?: CommandStroke;\n}\n\nconst DEFAULT_FILL: CommandFill = { paint: { kind: 'solid', color: '#ffffff' } };\nconst DEFAULT_STROKE: CommandStroke = { paint: { kind: 'solid', color: '#3b6fd4' }, width: 1.5 };\n/** How far past the end of the stack the add-lane button sits, in screen pixels. */\nconst ADD_STANDOFF_PX = 14;\n\n/** The far edge of a lane: the boundary between it and the next. */\nfunction boundaryOf(axis: 'x' | 'y', lane: RectPose) {\n const b = new PathBuilder();\n return axis === 'y'\n ? b.moveTo(lane.x, lane.y + lane.height).lineTo(lane.x + lane.width, lane.y + lane.height).build()\n : b.moveTo(lane.x + lane.width, lane.y).lineTo(lane.x + lane.width, lane.y + lane.height).build();\n}\n\n/** The add-lane button: a ring with a plus, drawn in screen pixels. */\nfunction addPaint(sizePx: number, fill: CommandFill, stroke: CommandStroke): AffordanceRegion['paint'] {\n return {\n kind: 'custom',\n draw: ({ world, view }) => {\n const t = viewToTransform(view);\n const cx = t.panX + world.x * t.zoom.x;\n const cy = t.panY + world.y * t.zoom.y;\n const r = sizePx / 2;\n const arm = r * 0.55;\n return [\n { kind: 'path', path: ellipsePath({ x: cx - r, y: cy - r, width: sizePx, height: sizePx }), fill, stroke },\n { kind: 'path', path: polylineFromPoints([{ x: cx - arm, y: cy }, { x: cx + arm, y: cy }]), stroke },\n { kind: 'path', path: polylineFromPoints([{ x: cx, y: cy - arm }, { x: cx, y: cy + arm }]), stroke },\n ];\n },\n };\n}\n\n/** The affordance: a boundary region after each lane of each pool, and an add-lane button per pool. */\nexport function createLaneAffordance(scene: AnyScene, opts: LaneLayerOptions = {}): Affordance {\n const { hitRadiusPx = 4, addSizePx = 14 } = opts;\n const fill = opts.fill ?? DEFAULT_FILL;\n const stroke = opts.stroke ?? DEFAULT_STROKE;\n return {\n id: LANE_LAYER_ID,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const pool of poolsOf(scene)) {\n if (!paintsLayer(state, scene.get(pool.id as NodeId)!.layer)) continue;\n const cursor = pool.axis === 'y' ? 'row-resize' : 'col-resize';\n for (const lane of pool.lanes) {\n out.push({\n id: `${lane.id}:boundary`,\n targetId: null,\n shape: { kind: 'outline', path: boundaryOf(pool.axis, lane.pose), hitRadiusPx },\n cursor,\n strength: 'exclusive',\n claimedKinds: ['pointer'],\n bind: () => ({ initialScratch: { targetId: pool.id, poolId: pool.id, laneId: lane.id } satisfies LaneScratch }),\n });\n }\n if (addSizePx <= 0) continue;\n const p = pool.pose;\n const end = pool.axis === 'y'\n ? { x: p.x + p.width / 2, y: p.y + p.height, normal: { x: 0, y: 1 } }\n : { x: p.x + p.width, y: p.y + p.height / 2, normal: { x: 1, y: 0 } };\n out.push({\n id: `${pool.id}:add-lane`,\n targetId: null,\n shape: { kind: 'point', x: end.x, y: end.y, hitRadiusPx: addSizePx / 2 + 2, standoff: { px: ADD_STANDOFF_PX, normal: end.normal } },\n paint: addPaint(addSizePx, fill, stroke),\n cursor: 'pointer',\n strength: 'exclusive',\n claimedKinds: ['pointer'],\n bind: () => ({ initialScratch: { targetId: pool.id, poolId: pool.id } satisfies LaneScratch }),\n });\n }\n return out;\n },\n };\n}\n\n/** The composed layer, for `CanvasExtensionApi.registerLayer`. */\nexport function laneLayer(scene: AnyScene, opts: LaneLayerOptions = {}): RenderLayer<unknown> {\n return composeAffordanceLayer(LANE_LAYER_ID, 'Diagram lanes', [createLaneAffordance(scene, opts)]) as unknown as RenderLayer<unknown>;\n}\n","/**\n * The container actions: dragging the boundary after a lane resizes it, the\n * add-lane button adds one at the end of the stack, and Release members\n * removes a container and keeps what it holds. The two lane gestures take a\n * swappable commit; the default writes the scene.\n */\nimport {\n ActionDisabledReason,\n carriedDescendants,\n sceneCarrySource,\n type Action,\n type Contribution,\n type InvocationCtx,\n type NodeId,\n type OngoingHandle,\n type RectPose,\n type RenderLayer,\n type Scene,\n} from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { grabPortAction, grabPortBindings } from '../connect';\nimport { addLane, releaseMembers } from './containerStencils';\nimport { LANE_AFFORDANCE_KIND, laneLayer, laneScratchOf, poolsOf, type LaneLayerOptions, type PoolLanes } from './laneBoundaryLayer';\nimport { MIN_LANE_SIZE } from './laneStack';\nimport { titlePose } from './titlePose';\nimport { diagramContainerOf, titleIdOf } from './trait';\n\n/** The action that drags a lane's boundary. */\nexport const LANE_RESIZE_ACTION_ID = 'diagram.resizeLane';\n/** The action the add-lane button runs. */\nexport const ADD_LANE_ACTION_ID = 'diagram.addLane';\n/** The command that removes the selected containers and keeps their members. */\nexport const RELEASE_MEMBERS_ACTION_ID = 'diagram.releaseMembers';\nconst GRAB_LANE_ACTION_ID = 'diagram.grabLane';\n\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** A lane resized: its new size along its pool's stack. */\nexport interface LaneResize {\n poolId: string;\n laneId: string;\n size: number;\n}\n\n/** The default commit: the lane's and the pool's new size, as one history\n * entry labeled \"Resize lane\". The pool's layout restacks the lanes after it. */\nexport function commitLaneResizeToScene(resize: LaneResize, ctx: InvocationCtx): void {\n const scene = ctx.deps.scene as AnyScene | undefined;\n const pool = scene?.get(resize.poolId as NodeId);\n const lane = scene?.get(resize.laneId as NodeId);\n if (scene === undefined || pool === undefined || lane === undefined) return;\n const axis = diagramContainerOf(pool)?.header?.side === 'top' ? 'x' : 'y';\n const l = lane.pose as RectPose;\n const p = pool.pose as RectPose;\n const d = resize.size - (axis === 'y' ? l.height : l.width);\n scene.batch('Resize lane', () => {\n scene.setPose(lane.id, axis === 'y' ? { ...l, height: resize.size } : { ...l, width: resize.size });\n scene.setPose(pool.id, axis === 'y' ? { ...p, height: p.height + d } : { ...p, width: p.width + d });\n });\n}\n\n/** Where everything stands with the lane at `index` of `pool` resized to `size`: the\n * lane, its title, the pool and its title, and every later lane with what it holds. */\nexport function laneResizeFrame(scene: AnyScene, pool: PoolLanes, index: number, size: number): Map<string, RectPose> {\n const { axis } = pool;\n const along = (r: RectPose) => (axis === 'y' ? r.height : r.width);\n const grow = (r: RectPose, by: number): RectPose => (axis === 'y' ? { ...r, height: r.height + by } : { ...r, width: r.width + by });\n const shift = (r: RectPose, by: number): RectPose => (axis === 'y' ? { ...r, y: r.y + by } : { ...r, x: r.x + by });\n const lane = pool.lanes[index]!;\n const d = size - along(lane.pose);\n const out = new Map<string, RectPose>();\n const placeTitle = (id: string, at: RectPose) => {\n const node = scene.get(id as NodeId);\n if (node !== undefined && scene.get(titleIdOf(id) as NodeId) !== undefined) {\n out.set(titleIdOf(id), titlePose(at, diagramContainerOf(node)?.header));\n }\n };\n const laneAt = grow(lane.pose, d);\n out.set(lane.id, laneAt);\n placeTitle(lane.id, laneAt);\n const poolAt = grow(pool.pose, d);\n out.set(pool.id, poolAt);\n placeTitle(pool.id, poolAt);\n for (const later of pool.lanes.slice(index + 1)) {\n out.set(later.id, shift(later.pose, d));\n const carried = carriedDescendants(sceneCarrySource(scene), later.id as NodeId, (p) => shift(p as RectPose, d));\n for (const [id, p] of carried) out.set(id, p as RectPose);\n }\n return out;\n}\n\n/** Options for the container actions. */\nexport interface LaneActionOptions extends LaneLayerOptions {\n scene: AnyScene;\n /** The selected ids, which Release members reads. */\n selected?: () => readonly string[];\n /** Defaults to {@link commitLaneResizeToScene}. */\n commitResize?: (resize: LaneResize, ctx: InvocationCtx) => void;\n /** Defaults to `addLane` on `deps.scene`, at the end of the stack. */\n commitAddLane?: (poolId: string, ctx: InvocationCtx) => void;\n /** Runs for each selected region in place of `releaseMembers`. */\n commitRelease?: (id: string) => void;\n}\n\n/** The `diagram.resizeLane` action: an ongoing drag moving one lane's far boundary. */\nexport function createLaneResizeAction(opts: LaneActionOptions): Action {\n const commit = opts.commitResize ?? commitLaneResizeToScene;\n return {\n id: LANE_RESIZE_ACTION_ID,\n label: 'Resize lane',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const pressed = laneScratchOf(ctx.drag?.affordance);\n const pool = poolsOf(opts.scene).find((p) => p.id === pressed?.poolId);\n const index = pool?.lanes.findIndex((l) => l.id === pressed?.laneId) ?? -1;\n if (pressed === null || pool === undefined || index < 0) return {};\n const lane = pool.lanes[index]!;\n const start = pool.axis === 'y' ? lane.pose.height : lane.pose.width;\n const press: Vec2 = ctx.drag?.start ?? ctx.world;\n const sizeAt = (at: Vec2) => Math.max(MIN_LANE_SIZE, start + (pool.axis === 'y' ? at.y - press.y : at.x - press.x));\n let frame: Map<string, RectPose> | null = null;\n let open = true;\n return {\n kind: 'diagram-resize-lane',\n onMove(moveCtx: InvocationCtx): void {\n const size = sizeAt(moveCtx.world);\n frame = size === start ? null : laneResizeFrame(opts.scene, pool, index, size);\n },\n previewIds: () => (open && frame !== null ? [...frame.keys()] : null),\n previewPose: (id) => (open ? frame?.get(id) ?? null : null),\n onEnd(endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n open = false;\n if (reason === 'cancel') return;\n const size = sizeAt(endCtx.world);\n if (size !== start) commit({ poolId: pool.id, laneId: lane.id, size }, { ...endCtx, deps: ctx.deps });\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n\nconst NO_MODIFIERS = { alt: false, shift: false, meta: false, ctrl: false };\n\n/** The `diagram.addLane` action: the add-lane button's click. */\nexport function createAddLaneAction(opts: LaneActionOptions): Action {\n const commit = opts.commitAddLane ?? ((poolId: string, ctx: InvocationCtx) => {\n const scene = ctx.deps.scene as AnyScene | undefined;\n if (scene !== undefined) addLane(scene, poolId);\n });\n return {\n id: ADD_LANE_ACTION_ID,\n label: 'Add lane',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const pressed = laneScratchOf((params as { affordance?: { payload?: unknown } } | undefined)?.affordance);\n if (pressed === null || pressed.laneId !== undefined) return;\n const world = { x: Number(params?.worldX), y: Number(params?.worldY) };\n commit(pressed.poolId, { world, modifiers: NO_MODIFIERS, deps } as InvocationCtx);\n },\n },\n enabled: () => true as const,\n };\n}\n\n/** The selected containers, pools, and lanes. */\nconst selectedContainers = (opts: LaneActionOptions): string[] =>\n (opts.selected?.() ?? []).filter((id) => {\n const node = opts.scene.get(id as NodeId);\n return node !== undefined && diagramContainerOf(node) !== null;\n });\n\n/** The `diagram.releaseMembers` command: removes each selected container and\n * keeps what it holds, in one history entry. */\nexport function createReleaseMembersAction(opts: LaneActionOptions): Action {\n return {\n id: RELEASE_MEMBERS_ACTION_ID,\n label: 'Release members',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run() {\n const ids = selectedContainers(opts);\n if (ids.length === 0) return;\n const commit = opts.commitRelease;\n if (commit !== undefined) {\n for (const id of ids) commit(id);\n return;\n }\n opts.scene.batch('Release members', () => {\n for (const id of ids) releaseMembers(opts.scene, id);\n });\n },\n },\n enabled: () => (selectedContainers(opts).length > 0 ? true : ActionDisabledReason.NotApplicable),\n };\n}\n\n/**\n * Both halves of container editing: the lane layer to `registerLayer`, and\n * the contribution to pass as `ambient`, which carries the lane boundary\n * drag, the add-lane click, and the `diagram.releaseMembers` command. Like\n * `diagramPorts`, one without the other fails quietly.\n */\nexport function diagramContainers(opts: LaneActionOptions): { layer: RenderLayer<unknown>; contribution: Contribution } {\n const target = `affordance:${LANE_AFFORDANCE_KIND}` as const;\n return {\n layer: laneLayer(opts.scene, opts),\n contribution: {\n id: 'weasel-diagram-containers',\n eligibility: { claimed: true },\n actions: [\n createLaneResizeAction(opts), createAddLaneAction(opts), createReleaseMembersAction(opts), grabPortAction(GRAB_LANE_ACTION_ID),\n ],\n bindings: [\n { spec: { kind: 'drag', target }, actionId: LANE_RESIZE_ACTION_ID },\n { spec: { kind: 'click', target }, actionId: ADD_LANE_ACTION_ID },\n ...grabPortBindings(GRAB_LANE_ACTION_ID, LANE_AFFORDANCE_KIND).filter((b) => b.spec.kind !== 'click'),\n ],\n },\n };\n}\n","/**\n * A double-click on a region's header: the action that reports which region's\n * title to edit, and its binding.\n */\nimport {\n ActionDisabledReason,\n bodyPredicate,\n type Action,\n type ActionDeps,\n type GestureBinding,\n type RectPose,\n} from '@weasel-js/core';\nimport { diagramContainerOf, headerBox } from './trait';\n\n/** The action a double-click on a region's header runs. */\nexport const EDIT_CONTAINER_TITLE_ACTION_ID = 'diagram.editContainerTitle';\n\n/** The container, pool, or lane whose header holds `at`: the node under it, or a region around that. */\nexport function regionHeaderAt(deps: ActionDeps | undefined, at: { x: number; y: number } | undefined): string | null {\n if (deps === undefined || at === undefined) return null;\n const scene = deps.scene;\n for (let id = deps.nodeAtPoint?.(at) ?? null; id != null && scene !== undefined; id = scene.get(id)?.parent ?? null) {\n const node = scene.get(id);\n const trait = node === undefined ? null : diagramContainerOf(node);\n if (node === undefined || trait === null) continue;\n const h = headerBox(node.pose as RectPose, trait.header);\n if (h !== null && at.x >= h.x && at.x <= h.x + h.width && at.y >= h.y && at.y <= h.y + h.height) return id as string;\n }\n return null;\n}\n\n/** The action that hands `commit` the region whose header a double-click landed on. It declines anywhere else. */\nexport function editContainerTitleAction(commit: (id: string) => void): Action {\n return {\n id: EDIT_CONTAINER_TITLE_ACTION_ID,\n label: 'Edit container title',\n group: 'diagram',\n requires: ['scene', 'nodeAtPoint'],\n eligible: { mode: { in: ['normal', 'isolation'] } },\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const id = regionHeaderAt(deps, { x: Number(params?.worldX), y: Number(params?.worldY) });\n if (id !== null) commit(id);\n },\n },\n enabled: (deps, at) => (regionHeaderAt(deps, at) !== null ? true : ActionDisabledReason.NotApplicable),\n };\n}\n\nconst onBody = bodyPredicate((target) => target === 'selected-body' || target === 'unselected-body');\n\n/** A double-click on a node's body; the action declines unless it lands in a region's header. */\nexport function editContainerTitleBinding(): GestureBinding {\n return { spec: { kind: 'doubleClick', target: { kindOf: onBody } }, actionId: EDIT_CONTAINER_TITLE_ACTION_ID };\n}\n","import type { Action } from '@weasel-js/core';\nimport { DEFAULT_HOP_SIZE, HOPS_DOC_KEY } from './types';\n\n/** The line jumps command's id. */\nexport const SET_HOPS_ACTION_ID = 'diagram.hops';\n\n/** Options for {@link createSetHopsAction}. */\nexport interface SetHopsOptions {\n /** The radius hops take when the command turns them on. Default\n * {@link DEFAULT_HOP_SIZE}. */\n size?: number;\n}\n\n/**\n * The command that turns line jumps on for the whole document, or off, by\n * writing its `HOPS_DOC_KEY` value: one history entry, which the hop pass\n * (`useHops`) joins with every connector's hops. Active while they are on.\n */\nexport function createSetHopsAction(opts: SetHopsOptions = {}): Action {\n const size = opts.size ?? DEFAULT_HOP_SIZE;\n return {\n id: SET_HOPS_ACTION_ID,\n label: 'Line jumps',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run(deps) {\n const doc = deps.scene?.doc;\n doc?.set(HOPS_DOC_KEY, doc.get(HOPS_DOC_KEY) === undefined ? { size } : undefined);\n },\n },\n active: (deps) => deps?.scene?.doc.get(HOPS_DOC_KEY) !== undefined,\n };\n}\n","/**\n * Moving an edge label along and beside its edge.\n *\n * The label layer (`labelDragLayer`) claims the press; this action moves the\n * label. The drag previews the label's own data at the station the pointer\n * proposes, and the pose that data derives, so the preview stands where the\n * commit will.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n documentDepOf,\n effectivePose,\n translatePoseViaDescriptor,\n type Action,\n type InvocationCtx,\n type OngoingHandle,\n} from '@weasel-js/core';\nimport type { Path, Vec2 } from '@weasel-js/core/math';\nimport { LABEL_PLACEMENT, diagramLabelOf, type DiagramLabel, type LabelSpot } from './labelTrait';\nimport { labelCenter, labelSpotAt } from './labels/station';\nimport { labelScratchOf } from './labelDragLayer';\n\n/** The action that drags an edge label. */\nexport const MOVE_LABEL_ACTION_ID = 'diagram.moveLabel';\n\n/** A label placed: where it now sits on its edge, or `null` to reset it to {@link LABEL_PLACEMENT}. */\nexport interface LabelEdit {\n labelId: string;\n edgeId: string;\n placement: DiagramLabel | null;\n}\n\n/** Options for {@link createLabelDragAction}. */\nexport interface LabelDragOptions {\n /** Defaults to {@link commitLabelToScene} against `deps.scene`. */\n commit?: (edit: LabelEdit, ctx: InvocationCtx) => void;\n id?: string;\n}\n\nconst placementAt = (spot: LabelSpot): DiagramLabel => ({ at: spot.at, offset: spot.offset, dodge: false });\n\n/** `data` with its label trait set where `placement` says. */\nfunction placedData(data: unknown, placement: DiagramLabel): Record<string, unknown> {\n const record = data as Record<string, unknown>;\n return { ...record, diagram: { ...(record.diagram as Record<string, unknown>), label: placement } };\n}\n\n/** `data` with its label trait at `spot`, owned by the author from now on:\n * placement's `placed` is dropped, and placement won't move it again. */\nexport function movedLabelData(data: unknown, spot: LabelSpot): Record<string, unknown> {\n return placedData(data, placementAt(spot));\n}\n\n/** The default commit: the label's placement in `data.diagram.label`, as one\n * history entry labeled \"Move label\", or \"Reset label\" for a `null` placement. */\nexport function commitLabelToScene(edit: LabelEdit, ctx: InvocationCtx): void {\n const scene = ctx.deps.scene;\n const node = scene?.get(edit.labelId as never);\n if (scene === undefined || node === undefined || diagramLabelOf(node) === null) return;\n const placement = edit.placement ?? LABEL_PLACEMENT;\n scene.batch(edit.placement === null ? 'Reset label' : 'Move label', () => {\n scene.update(node.id, { data: placedData(node.data, placement) as never });\n });\n}\n\n/** What a label drag captured at its press, read-only after. */\ninterface LabelPress {\n labelId: string;\n edgeId: string;\n data: unknown;\n pose: unknown;\n size: { width: number; height: number };\n center: Vec2;\n path: Path;\n /** The label's center less the press point. */\n grab: Vec2;\n deps: InvocationCtx['deps'];\n}\n\nfunction pressOf(ctx: InvocationCtx): LabelPress | null {\n const pressed = labelScratchOf(ctx.drag?.affordance);\n const scene = ctx.deps.scene;\n const node = pressed === null ? undefined : scene?.get(pressed.labelId as never);\n if (pressed === null || scene === undefined || node === undefined || diagramLabelOf(node) === null) return null;\n const path = documentDepOf(scene as never, pressed.edgeId as never)?.path ?? null;\n if (path === null) return null;\n const pose = effectivePose(scene as never, node as never);\n const box = AUTO_POSE_DESCRIPTOR.getBounds(pose);\n const center = { x: box.x + box.width / 2, y: box.y + box.height / 2 };\n const press = ctx.drag?.start ?? { x: ctx.world.x, y: ctx.world.y };\n return {\n labelId: pressed.labelId, edgeId: pressed.edgeId, data: node.data, pose, path, center,\n size: { width: box.width, height: box.height },\n grab: { x: center.x - press.x, y: center.y - press.y },\n deps: ctx.deps,\n };\n}\n\n/** The station the label's center stands at with the pointer at `ctx.world`. */\nconst spotAt = (p: LabelPress, ctx: InvocationCtx): LabelSpot | null =>\n labelSpotAt(p.path, { x: ctx.world.x + p.grab.x, y: ctx.world.y + p.grab.y }, p.size);\n\n/** The press pose moved to where `spot` derives the label's center. */\nfunction poseAt(p: LabelPress, spot: LabelSpot): unknown {\n const c = labelCenter(p.path, placementAt(spot), p.size);\n return c === null ? p.pose : translatePoseViaDescriptor(p.pose, c.x - p.center.x, c.y - p.center.y, AUTO_POSE_DESCRIPTOR);\n}\n\n/** The `diagram.moveLabel` action: an ongoing drag moving one edge label along and beside its edge. */\nexport function createLabelDragAction(opts: LabelDragOptions = {}): Action {\n const { commit = commitLabelToScene } = opts;\n return {\n id: opts.id ?? MOVE_LABEL_ACTION_ID,\n label: 'Move label',\n group: 'diagram',\n requires: ['scene'],\n eligible: { mode: { in: ['normal', 'isolation'] } },\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const p = pressOf(ctx);\n if (p === null) return {};\n // Null until the pointer moves, so a still click commits nothing.\n let spot: LabelSpot | null = null;\n let open = true;\n const proposed = () => (open ? spot : null);\n return {\n kind: 'diagram-move-label',\n onMove(moveCtx: InvocationCtx): void {\n spot = spotAt(p, moveCtx);\n },\n previewIds: () => (proposed() === null ? null : [p.labelId]),\n previewPose: (id) => {\n const next = proposed();\n return id === p.labelId && next !== null ? poseAt(p, next) : null;\n },\n previewData: (id) => {\n const next = proposed();\n return id === p.labelId && next !== null ? movedLabelData(p.data, next) : null;\n },\n onEnd(endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n open = false;\n const final = reason === 'commit' && spot !== null ? spotAt(p, endCtx) ?? spot : null;\n if (final !== null) {\n commit({ labelId: p.labelId, edgeId: p.edgeId, placement: placementAt(final) }, { ...endCtx, deps: p.deps });\n }\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * The label edit that is not a drag: the Reset label command.\n */\nimport { ActionDisabledReason, type Action, type InvocationCtx, type Scene } from '@weasel-js/core';\nimport { commitLabelToScene, type LabelEdit } from './labelDragAction';\nimport { editableLabels } from './labelDragLayer';\n\n/** The command that puts the selected edges' dragged labels back where placement puts them. */\nexport const RESET_LABEL_ACTION_ID = 'diagram.resetLabel';\n\nconst NO_MODIFIERS = { alt: false, shift: false, meta: false, ctrl: false };\n\n/** The labels on `selected` edges that a drag has pinned (`dodge: false`) and an edit may touch. */\nfunction draggedLabels(scene: Scene<unknown, string, unknown> | undefined, selected: readonly string[]): LabelEdit[] {\n if (scene === undefined || selected.length === 0) return [];\n const out: LabelEdit[] = [];\n for (const { labelId, edgeId, label } of editableLabels(scene, new Set(selected))) {\n if (label.dodge === false) out.push({ labelId, edgeId, placement: null });\n }\n return out;\n}\n\n/** The `diagram.resetLabel` command: sets each selected edge's dragged label\n * back to `LABEL_PLACEMENT`, in one history entry when they commit to the scene. */\nexport function createResetLabelAction(opts: {\n selected: () => readonly string[];\n commit?: (edit: LabelEdit, ctx: InvocationCtx) => void;\n}): Action {\n const { commit = commitLabelToScene } = opts;\n return {\n id: RESET_LABEL_ACTION_ID,\n label: 'Reset label',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run(deps) {\n const edits = draggedLabels(deps.scene as never, opts.selected());\n const ctx = { world: { x: 0, y: 0 }, modifiers: NO_MODIFIERS, deps } as InvocationCtx;\n const all = () => { for (const edit of edits) commit(edit, ctx); };\n if (deps.scene === undefined) all();\n else deps.scene.batch('Reset label', all);\n },\n },\n enabled: (deps) =>\n draggedLabels(deps?.scene as never, opts.selected()).length > 0 ? true : ActionDisabledReason.NotApplicable,\n };\n}\n","/**\n * The port affordance, composed into a layer and pointed at a scene.\n */\nimport {\n composeAffordanceLayer,\n effectivePose,\n nodeGates,\n type GatedLayer,\n type RenderLayer,\n} from '@weasel-js/core';\nimport {\n PORT_LAYER_ID,\n createPortAffordance,\n type ParticipantPose,\n type ParticipantSource,\n type PortAffordanceOptions,\n} from './portAffordance';\nimport type { GraphNodeLike } 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. `layers` and each\n * node's `layer`, `parent`, `hidden` and `locked` feed `nodeGates`; a stand-in\n * without them gates nothing. */\nexport interface ParticipantScene<TPose> {\n readonly layers?: readonly GatedLayer[];\n renderOrderNodes(): readonly {\n id: string;\n kind: 'leaf' | 'container';\n layer?: string;\n parent?: string | null;\n hidden?: boolean;\n locked?: boolean;\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, marked `hidden` or\n * `locked` where the scene's `nodeGates` says so, and carrying its `layer` so\n * a view that does not paint that layer can turn its ports away too. The\n * marks keep ports off such a node; the graph reads past them, so a hidden\n * node is still laid out.\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.\n *\n * One source answers both the ports and the graph.\n */\nexport function sceneParticipants<TPose>(\n scene: ParticipantScene<TPose>,\n): () => Iterable<ParticipantPose<TPose> & { node: GraphNodeLike }> {\n return function* () {\n const gates = nodeGates(scene as never);\n for (const node of scene.renderOrderNodes()) {\n const hidden = gates.hidden(node.id);\n const locked = gates.locked(node.id);\n yield {\n node: node as GraphNodeLike,\n pose: effectivePose(scene as never, node as never) as TPose,\n ...(node.layer !== undefined ? { layer: node.layer } : {}),\n ...(hidden ? { hidden } : {}),\n ...(locked ? { locked } : {}),\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 */\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 * Handles on the ends of a selected edge — what makes an edge's end grabbable,\n * so a drag can carry it onto another shape (`reconnect`).\n *\n * Built the way the port affordance is: point regions with a `null`\n * `targetId` and no `hitKind`, composed into a layer whose id is the kind a\n * press reports. See `portAffordance` for why both matter.\n */\nimport {\n composeAffordanceLayer,\n type Affordance,\n type AffordanceRegion,\n type ChromeState,\n type CommandFill,\n type CommandStroke,\n type CursorSpec,\n type DerivedDep,\n type RenderLayer,\n} from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { edgeRouter, type ResolvedRoute, type Router } from './edge';\nimport { diagramEdgeOf, type DiagramEdge } from './edgeTrait';\nimport type { GraphNodeLike } from './graph';\nimport { offersPorts, type ParticipantPose, type ParticipantSource } from './portAffordance';\nimport type { PortsOptions } from './ports';\n\n/** The layer id the edge-end handles are composed into. */\nexport const EDGE_END_LAYER_ID = 'diagram-edge-ends';\n\n/** The affordance kind a press on an edge-end handle reports. */\nexport const EDGE_END_AFFORDANCE_KIND = `layer:${EDGE_END_LAYER_ID}` as const;\n\n/** What a press on an edge-end handle hands the reconnect action, as\n * `InvocationCtx.drag.affordance.payload`. */\nexport interface EdgeEndScratch {\n targetId: string;\n edgeId: string;\n end: 'from' | 'to';\n}\n\n/** Read an edge-end press's scratch back off the hit an action was handed. */\nexport function edgeEndScratchOf(hit: { payload?: unknown } | null | undefined): EdgeEndScratch | null {\n const payload = hit?.payload as EdgeEndScratch | undefined;\n return payload !== undefined && typeof payload.edgeId === 'string'\n && (payload.end === 'from' || payload.end === 'to') ? payload : null;\n}\n\n/** An edge as it stands: its trait, the participants at its two ends, and\n * where its routed path starts and ends. */\nexport interface EdgeEnds<TPose> {\n edge: ParticipantPose<TPose>;\n trait: DiagramEdge;\n from: ParticipantPose<TPose>;\n to: ParticipantPose<TPose>;\n points: { from: Vec2; to: Vec2 };\n /** The route as the edge's own `derivePath` draws it. */\n route: ResolvedRoute;\n}\n\n/** Options shared by the edge-end affordance and the reconnect action. */\nexport interface EdgeEndOptions<TPose> extends PortsOptions<TPose> {\n routers?: Readonly<Record<string, Router>>;\n}\n\n/** Resolves an edge's two ends from `participants`, routed as the edge's own\n * `derivePath` routes it. `null` for a node that is not a drawable edge. */\nexport function createEdgeEnds<TPose>(participants: ParticipantSource<TPose>, opts: EdgeEndOptions<TPose> = {}) {\n const derive = edgeRouter<TPose>({\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n ...(opts.routers ? { routers: opts.routers } : {}),\n });\n return function endsOf(edgeId: string): EdgeEnds<TPose> | null {\n const byId = new Map<string, ParticipantPose<TPose>>();\n for (const p of participants()) byId.set(p.node.id, p);\n const edge = byId.get(edgeId);\n if (edge === undefined) return null;\n const trait = diagramEdgeOf(edge.node);\n const deps = (edge.node as GraphNodeLike).dependsOn;\n if (trait === null || !Array.isArray(deps) || deps.length !== 2) return null;\n const from = byId.get(deps[0]!);\n const to = byId.get(deps[1]!);\n if (from === undefined || to === undefined) return null;\n const dep = (p: ParticipantPose<TPose>) => ({ node: p.node, pose: p.pose }) as unknown as DerivedDep<TPose>;\n const route = derive(edge.node, [dep(from), dep(to)]);\n const p = route?.points;\n if (route === null || p === undefined || p.length < 2) return null;\n return { edge, trait, from, to, points: { from: p[0]!, to: p[p.length - 1]! }, route };\n };\n}\n\n/** Options for {@link createEdgeEndAffordance}. */\nexport interface EdgeEndAffordanceOptions<TPose> extends EdgeEndOptions<TPose> {\n /** Also the chrome-caps visibility id. Default {@link EDGE_END_LAYER_ID}. */\n id?: string;\n /** Screen-pixel hit radius. Default 8. */\n hitRadiusPx?: number;\n /** Screen-pixel side of the painted square. Default 8; 0 paints nothing. */\n sizePx?: number;\n fill?: CommandFill;\n stroke?: CommandStroke;\n cursor?: CursorSpec;\n}\n\nconst DEFAULT_HIT_PX = 8;\nconst DEFAULT_SIZE_PX = 8;\n\n/** The affordance: one point region on each end of each selected edge. */\nexport function createEdgeEndAffordance<TPose>(\n participants: ParticipantSource<TPose>,\n selected: () => readonly string[],\n opts: EdgeEndAffordanceOptions<TPose> = {},\n): Affordance {\n const { id = EDGE_END_LAYER_ID, hitRadiusPx = DEFAULT_HIT_PX, sizePx = DEFAULT_SIZE_PX } = opts;\n const endsOf = createEdgeEnds(participants, opts);\n const look = { ...(opts.fill ? { fill: opts.fill } : {}), ...(opts.stroke ? { stroke: opts.stroke } : {}) };\n const paint = sizePx > 0 ? { paint: { kind: 'square' as const, sizePx, ...look } } : {};\n\n return {\n id,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const edgeId of selected()) {\n const ends = endsOf(edgeId);\n if (ends === null || !offersPorts(ends.edge, state)) continue;\n for (const end of ['from', 'to'] as const) {\n const at = ends.points[end];\n out.push({\n id: `${edgeId}:${end}`,\n targetId: null,\n shape: { kind: 'point', x: at.x, y: at.y, hitRadiusPx },\n ...paint,\n ...(opts.cursor !== undefined ? { cursor: opts.cursor } : {}),\n strength: 'exclusive',\n claimedKinds: ['pointer'],\n bind: () => ({ initialScratch: { targetId: edgeId, edgeId, end } satisfies EdgeEndScratch }),\n });\n }\n }\n return out;\n },\n };\n}\n\n/** The composed layer, for `CanvasExtensionApi.registerLayer`. Register it\n * after the port layer: the last-registered layer is hit first, and an edge's\n * end sits on a port. */\nexport function edgeEndLayer<TPose>(\n participants: ParticipantSource<TPose>,\n selected: () => readonly string[],\n opts: EdgeEndAffordanceOptions<TPose> = {},\n): RenderLayer<unknown> {\n return composeAffordanceLayer(\n opts.id ?? EDGE_END_LAYER_ID,\n 'Diagram edge ends',\n [createEdgeEndAffordance(participants, selected, opts)],\n ) as unknown as RenderLayer<unknown>;\n}\n","/**\n * Waypoint editing as pure math on an edge's route.\n *\n * The **stops** are the points a route must pass through: its `from` end, the\n * author's waypoints, and its `to` end. The **drawn** route is what the router\n * made of them. Every shipped router passes through each stop exactly, so the\n * drawn polyline splits at the stops and a leg's middle is found on it.\n *\n * Each edit answers the edge's new waypoints, never the whole route.\n */\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { avoid, orthogonal, type Router } from './edge';\nimport { simplifyStops } from './polyline';\n\nexport { simplifyStops };\n\n/** A handle a selected edge shows along its route. `at` is where it sits, in world units. */\nexport type RouteHandle =\n /** Waypoint `index`: dragging moves it. */\n | { kind: 'vertex'; index: number; at: Vec2 }\n /** The middle of leg `leg`, between stops `leg` and `leg + 1`: dragging inserts a waypoint there. */\n | { kind: 'insert'; leg: number; at: Vec2 }\n /** Segment `index` of an orthogonal route, which runs along `axis`: dragging slides it across. */\n | { kind: 'segment'; index: number; axis: 'x' | 'y'; at: Vec2 };\n\nconst EPS = 1e-6;\n/** World units a jog stands off from the port it keeps square. */\nconst JOG = 16;\n\nconst same = (a: Vec2, b: Vec2) => Math.abs(a.x - b.x) <= EPS && Math.abs(a.y - b.y) <= EPS;\n\n/** The axis a segment runs along, or null when it is a point or slanted. */\nexport function segmentAxis(a: Vec2, b: Vec2): 'x' | 'y' | null {\n if (same(a, b)) return null;\n if (Math.abs(a.y - b.y) <= EPS) return 'x';\n if (Math.abs(a.x - b.x) <= EPS) return 'y';\n return null;\n}\n\n/** Index in `drawn` of each stop, found in order; null when one is not on it. */\nfunction stopIndices(drawn: readonly Vec2[], stops: readonly Vec2[]): number[] | null {\n const out: number[] = [];\n let from = 0;\n for (const stop of stops) {\n let i = from;\n while (i < drawn.length && !same(drawn[i]!, stop)) i++;\n if (i === drawn.length) return null;\n out.push(i);\n from = i;\n }\n return out;\n}\n\n/** The point halfway along `drawn` between indices `a` and `b`, by length. */\nfunction middleOf(drawn: readonly Vec2[], a: number, b: number): Vec2 {\n let total = 0;\n for (let i = a; i < b; i++) total += Math.hypot(drawn[i + 1]!.x - drawn[i]!.x, drawn[i + 1]!.y - drawn[i]!.y);\n let left = total / 2;\n for (let i = a; i < b; i++) {\n const p = drawn[i]!;\n const q = drawn[i + 1]!;\n const len = Math.hypot(q.x - p.x, q.y - p.y);\n if (len >= left && len > 0) return { x: p.x + ((q.x - p.x) * left) / len, y: p.y + ((q.y - p.y) * left) / len };\n left -= len;\n }\n return drawn[a]!;\n}\n\n/** The handles an edge shows: a bar per segment under `orthogonal` and\n * `avoid`, else a dot per waypoint and a hollow dot per leg. */\nexport function routeHandles(drawn: readonly Vec2[], stops: readonly Vec2[], router: Router): RouteHandle[] {\n if (router === orthogonal || router === avoid) {\n const out: RouteHandle[] = [];\n for (let i = 0; i + 1 < drawn.length; i++) {\n const a = drawn[i]!;\n const b = drawn[i + 1]!;\n const axis = segmentAxis(a, b);\n if (axis !== null) out.push({ kind: 'segment', index: i, axis, at: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } });\n }\n return out;\n }\n const out: RouteHandle[] = [];\n for (let k = 1; k + 1 < stops.length; k++) out.push({ kind: 'vertex', index: k - 1, at: stops[k]! });\n const at = stopIndices(drawn, stops);\n for (let leg = 0; leg + 1 < stops.length; leg++) {\n const a = stops[leg]!;\n const b = stops[leg + 1]!;\n out.push({\n kind: 'insert', leg,\n at: at === null ? { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } : middleOf(drawn, at[leg]!, at[leg + 1]!),\n });\n }\n return out;\n}\n\nconst interior = (stops: readonly Vec2[]): Vec2[] => stops.slice(1, -1).map((p) => ({ x: p.x, y: p.y }));\n\n/** The waypoints with waypoint `index` moved to `to`. */\nexport function dragVertex(stops: readonly Vec2[], index: number, to: Vec2): Vec2[] {\n const out = interior(stops);\n out[index] = { x: to.x, y: to.y };\n return out;\n}\n\n/** The waypoints with one at `at` inserted on leg `leg`: it becomes waypoint `leg`. */\nexport function insertWaypoint(stops: readonly Vec2[], leg: number, at: Vec2): Vec2[] {\n const out = interior(stops);\n out.splice(leg, 0, { x: at.x, y: at.y });\n return out;\n}\n\n/** The waypoints without waypoint `index`. */\nexport function removeWaypoint(stops: readonly Vec2[], index: number): Vec2[] {\n const out = interior(stops);\n out.splice(index, 1);\n return out;\n}\n\nconst shifted = (p: Vec2, axis: 'x' | 'y', offset: number): Vec2 =>\n axis === 'x' ? { x: p.x, y: p.y + offset } : { x: p.x + offset, y: p.y };\n\n/** The point `distance` from `a` toward `b`. */\nfunction toward(a: Vec2, b: Vec2, distance: number): Vec2 {\n const len = Math.hypot(b.x - a.x, b.y - a.y);\n return len === 0 ? a : { x: a.x + ((b.x - a.x) * distance) / len, y: a.y + ((b.y - a.y) * distance) / len };\n}\n\n/**\n * The waypoints of `drawn`, an orthogonal route, with segment `index` slid\n * `offset` across its axis: every interior bend of the new route, since the\n * orthogonal router recomputes elbows between stops. A segment touching a\n * port keeps a short stub there and jogs over, so the port end stays square.\n */\nexport function dragSegment(drawn: readonly Vec2[], index: number, offset: number): Vec2[] {\n const a = drawn[index]!;\n const b = drawn[index + 1]!;\n const axis = segmentAxis(a, b);\n if (axis === null) return interior(drawn);\n const jog = Math.min(JOG, Math.hypot(b.x - a.x, b.y - a.y) / 2);\n const start = index === 0 ? toward(a, b, jog) : null;\n const end = index === drawn.length - 2 ? toward(b, a, jog) : null;\n const route = [\n ...drawn.slice(0, index),\n ...(start === null ? [] : [a, start]),\n shifted(start ?? a, axis, offset),\n shifted(end ?? b, axis, offset),\n ...(end === null ? [] : [end, b]),\n ...drawn.slice(index + 2),\n ];\n return interior(simplifyStops(route));\n}\n\n/**\n * The waypoints of an `avoid` route with segment `index` of `drawn` slid\n * `offset` across its axis and pinned there: its two ends join the author's\n * waypoints, in route order, and the router keeps the rest. A waypoint at one\n * of its ends moves with it, and a segment meeting a port jogs off it so the\n * port end stays square.\n */\nexport function pinSegment(drawn: readonly Vec2[], stops: readonly Vec2[], index: number, offset: number): Vec2[] {\n const a = drawn[index]!;\n const b = drawn[index + 1]!;\n const axis = segmentAxis(a, b);\n const waypoints = interior(stops);\n if (axis === null) return waypoints;\n const jog = Math.min(JOG, Math.hypot(b.x - a.x, b.y - a.y) / 2);\n const start = index === 0 ? toward(a, b, jog) : a;\n const end = index === drawn.length - 2 ? toward(b, a, jog) : b;\n const at = waypoints.map((w) => drawn.findIndex((p) => same(p, w)));\n const before = waypoints.filter((w, k) => at[k]! >= 0 && at[k]! <= index && !same(w, a));\n const after = waypoints.filter((w, k) => (at[k]! < 0 || at[k]! > index) && !same(w, b));\n return [...before, shifted(start, axis, offset), shifted(end, axis, offset), ...after];\n}\n\n/** The waypoints of an `avoid` route without those at either end of segment\n * `index`, which hands the segment back to the router; null when neither end is one. */\nexport function unpinSegment(drawn: readonly Vec2[], stops: readonly Vec2[], index: number): Vec2[] | null {\n const ends = [drawn[index]!, drawn[index + 1]!];\n const waypoints = interior(stops);\n const kept = waypoints.filter((w) => !ends.some((e) => same(e, w)));\n return kept.length === waypoints.length ? null : kept;\n}\n\n/**\n * The waypoints with segment `index` straightened away: its neighbors run in\n * parallel, and the one touching no port slides onto the other's line. Null\n * when it is the first or last segment, or both neighbors touch a port.\n */\nexport function removeSegment(drawn: readonly Vec2[], index: number): Vec2[] | null {\n const last = drawn.length - 2;\n if (index <= 0 || index >= last) return null;\n const axis = segmentAxis(drawn[index]!, drawn[index + 1]!);\n if (axis === null) return null;\n const across = (p: Vec2) => (axis === 'x' ? p.x : p.y);\n const prev = index - 1;\n const next = index + 1;\n if (next < last) return dragSegment(drawn, next, across(drawn[index]!) - across(drawn[index + 1]!));\n if (prev > 0) return dragSegment(drawn, prev, across(drawn[index + 1]!) - across(drawn[index]!));\n return null;\n}\n","/**\n * Handles along a selected edge's route — what makes its waypoints and\n * segments grabbable, so a drag can reshape the route (`waypointAction`).\n *\n * Built the way the edge-end handles are: point regions with a `null`\n * `targetId` and no `hitKind`, composed into a layer whose id is the kind a\n * press reports.\n */\nimport {\n composeAffordanceLayer,\n ellipsePath,\n viewToTransform,\n type Affordance,\n type AffordanceRegion,\n type ChromeState,\n type CommandFill,\n type CommandStroke,\n type CursorSpec,\n type RenderLayer,\n} from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { routerOf, type Router } from './edge';\nimport { createEdgeEnds, type EdgeEndOptions, type EdgeEnds } from './edgeEndLayer';\nimport { offersPorts, type ParticipantSource } from './portAffordance';\nimport type { Port } from './types';\nimport { routeHandles, type RouteHandle } from './waypoints';\n\n/** The layer id the route handles are composed into. */\nexport const WAYPOINT_LAYER_ID = 'diagram-waypoints';\n\n/** The affordance kind a press on a route handle reports. */\nexport const WAYPOINT_AFFORDANCE_KIND = `layer:${WAYPOINT_LAYER_ID}` as const;\n\n/** What a press on a route handle hands the route-edit actions, as the hit's `payload`. */\nexport interface WaypointScratch {\n targetId: string;\n edgeId: string;\n handle: RouteHandle;\n}\n\n/** Read a route-handle press's scratch back off the hit an action was handed. */\nexport function waypointScratchOf(hit: { payload?: unknown } | null | undefined): WaypointScratch | null {\n const payload = hit?.payload as WaypointScratch | undefined;\n return payload !== undefined && typeof payload.edgeId === 'string' && typeof payload.handle?.kind === 'string'\n ? payload : null;\n}\n\n/** An edge's route as the handles read it: its resolved ends, its stops, the\n * route drawn through them, the router that drew it, and the handles it shows. */\nexport interface EdgeRouteState {\n from: Port;\n to: Port;\n stops: readonly Vec2[];\n drawn: readonly Vec2[];\n router: Router;\n handles: readonly RouteHandle[];\n}\n\n/** The route state of an edge whose ends `ends` resolved. */\nexport function routeStateOf(ends: EdgeEnds<unknown>, routers?: Readonly<Record<string, Router>>): EdgeRouteState {\n const { route } = ends;\n const stops = [route.from.point, ...route.waypoints, route.to.point];\n const router = routerOf(ends.trait, routers);\n const handles = route.stubs !== undefined ? [] : routeHandles(route.points, stops, router);\n return { from: route.from, to: route.to, stops, drawn: route.points, router, handles };\n}\n\n/** Options for {@link createWaypointAffordance}. */\nexport interface WaypointAffordanceOptions<TPose> extends EdgeEndOptions<TPose> {\n /** Also the chrome-caps visibility id. Default {@link WAYPOINT_LAYER_ID}. */\n id?: string;\n /** Screen-pixel hit radius. Default 7. */\n hitRadiusPx?: number;\n /** Screen-pixel diameter of a waypoint's dot; an insert dot is three\n * quarters of it, and a segment bar twice as long. Default 8; 0 paints nothing. */\n sizePx?: number;\n fill?: CommandFill;\n stroke?: CommandStroke;\n cursor?: CursorSpec;\n}\n\n/** A route handle's default screen-pixel hit radius. */\nexport const WAYPOINT_HIT_PX = 7;\nconst DEFAULT_SIZE_PX = 8;\nconst DEFAULT_FILL: CommandFill = { paint: { kind: 'solid', color: '#ffffff' } };\nconst DEFAULT_STROKE: CommandStroke = { paint: { kind: 'solid', color: '#3b6fd4' }, width: 1.5 };\n\n/** A handle's mark, drawn in screen pixels so it keeps its size at any zoom. */\nfunction paintOf(handle: RouteHandle, sizePx: number, fill: CommandFill, stroke: CommandStroke): AffordanceRegion['paint'] {\n return {\n kind: 'custom',\n draw: ({ world, view }) => {\n const t = viewToTransform(view);\n const cx = t.panX + world.x * t.zoom.x;\n const cy = t.panY + world.y * t.zoom.y;\n if (handle.kind === 'segment') {\n const [w, h] = handle.axis === 'x' ? [sizePx * 2, sizePx / 2] : [sizePx / 2, sizePx * 2];\n return [{ kind: 'path', path: { kind: 'rect', x: cx - w / 2, y: cy - h / 2, width: w, height: h }, fill, stroke }];\n }\n const d = handle.kind === 'vertex' ? sizePx : sizePx * 0.75;\n const path = ellipsePath({ x: cx - d / 2, y: cy - d / 2, width: d, height: d });\n return [handle.kind === 'vertex' ? { kind: 'path', path, fill, stroke } : { kind: 'path', path, stroke }];\n },\n };\n}\n\n/** The affordance: a region on each route handle of each selected edge. */\nexport function createWaypointAffordance<TPose>(\n participants: ParticipantSource<TPose>,\n selected: () => readonly string[],\n opts: WaypointAffordanceOptions<TPose> = {},\n): Affordance {\n const { id = WAYPOINT_LAYER_ID, hitRadiusPx = WAYPOINT_HIT_PX, sizePx = DEFAULT_SIZE_PX } = opts;\n const endsOf = createEdgeEnds(participants, opts);\n const fill = opts.fill ?? DEFAULT_FILL;\n const stroke = opts.stroke ?? DEFAULT_STROKE;\n\n return {\n id,\n regions(state: ChromeState): readonly AffordanceRegion[] {\n const out: AffordanceRegion[] = [];\n for (const edgeId of selected()) {\n const ends = endsOf(edgeId);\n if (ends === null || !offersPorts(ends.edge, state)) continue;\n for (const handle of routeStateOf(ends as EdgeEnds<unknown>, opts.routers).handles) {\n out.push({\n id: `${edgeId}:${handle.kind}:${handle.kind === 'insert' ? handle.leg : handle.index}`,\n targetId: null,\n shape: { kind: 'point', x: handle.at.x, y: handle.at.y, hitRadiusPx },\n ...(sizePx > 0 ? { paint: paintOf(handle, sizePx, fill, stroke) } : {}),\n ...(opts.cursor !== undefined ? { cursor: opts.cursor } : {}),\n strength: 'exclusive',\n claimedKinds: ['pointer'],\n bind: () => ({ initialScratch: { targetId: edgeId, edgeId, handle } satisfies WaypointScratch }),\n });\n }\n }\n return out;\n },\n };\n}\n\n/** The composed layer, for `CanvasExtensionApi.registerLayer`. Register it\n * after the port layer and before the edge-end layer: the last registered is\n * hit first, and an edge's end handle must win over a handle beside it. */\nexport function waypointLayer<TPose>(\n participants: ParticipantSource<TPose>,\n selected: () => readonly string[],\n opts: WaypointAffordanceOptions<TPose> = {},\n): RenderLayer<unknown> {\n return composeAffordanceLayer(\n opts.id ?? WAYPOINT_LAYER_ID,\n 'Diagram waypoints',\n [createWaypointAffordance(participants, selected, opts)],\n ) as unknown as RenderLayer<unknown>;\n}\n","/**\n * The snap targets a route-handle drag brings: the stops beside the dragged\n * point and each end's port axis, which exist only for that drag.\n */\nimport type { SnapSource, SourceCandidate } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport type { Port } from './types';\n\n/** Options for {@link routeSnapSource}. */\nexport interface RouteSnapSourceOptions {\n /** Must not collide with a source the canvas asks. */\n id: string;\n /** Points a dragged handle lines up with on either axis. */\n stops: readonly Vec2[];\n /** Ports a dragged handle lines up with along their axis. */\n ports: readonly Port[];\n /** Screen px. */\n reachPx: number;\n}\n\ntype Axis = 'x' | 'y';\n\nconst BOTH: readonly Axis[] = ['x', 'y'];\n/** The direction of the line holding coordinate `axis` fixed. */\nconst ALONG: Record<Axis, Vec2> = { x: { x: 0, y: 1 }, y: { x: 1, y: 0 } };\n\n/** The coordinates a port lines up on: a port facing east or west on y, one\n * facing north or south on x, and one facing nowhere on both. */\nfunction portAxes(port: Port): readonly Axis[] {\n const n = port.normal;\n if (n === null) return BOTH;\n return Math.abs(n.x) >= Math.abs(n.y) ? ['y'] : ['x'];\n}\n\n/** A pointer source for a route drag: a line through each stop on each axis,\n * and through each port along its axis, marked from the target to where the\n * handle lands. */\nexport function routeSnapSource(opts: RouteSnapSourceOptions): SnapSource {\n const targets = [\n ...opts.stops.map((at) => ({ at, axes: BOTH })),\n ...opts.ports.map((p) => ({ at: p.point, axes: portAxes(p) })),\n ];\n return {\n id: opts.id,\n tier: 'target',\n reachPx: opts.reachPx,\n roles: ['pointer'],\n gestures: ['point'],\n *collect(q): Iterable<SourceCandidate> {\n const reach = q.reachWorld(q.reachPx);\n for (const p of q.probes) {\n for (const t of targets) {\n for (const axis of t.axes) {\n if (Math.abs(p.at[axis] - t.at[axis]) > reach) continue;\n yield {\n probe: p.id,\n locus: { at: { ...p.at, [axis]: t.at[axis] }, dirs: [ALONG[axis]] },\n mark: (delta) => ({\n kind: 'line',\n from: t.at,\n to: { x: p.at.x - q.delta0.x + delta.x, y: p.at.y - q.delta0.y + delta.y },\n }),\n };\n }\n }\n }\n },\n };\n}\n","/**\n * Route editing — dragging a selected edge's waypoints and segments.\n *\n * The route handles (`waypointLayer`) claim the press; this action reshapes\n * the route. The drag previews the edge's own data with the new waypoints,\n * so its `derivePath` draws the preview exactly as the commit will.\n */\nimport { SNAP_ROLES, snapMods, type Action, type InvocationCtx, type OngoingHandle, type SnapSession } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { createEdgeEnds, type EdgeEndOptions } from './edgeEndLayer';\nimport { diagramEdgeOf, samePoints, type DiagramEdge } from './edgeTrait';\nimport type { ParticipantSource } from './portAffordance';\nimport { routeSnapSource } from './routeSnapSource';\nimport { routeStateOf, waypointScratchOf, type EdgeRouteState } from './waypointLayer';\nimport { avoid } from './edge';\nimport { dragSegment, dragVertex, insertWaypoint, pinSegment, type RouteHandle } from './waypoints';\n\n/** The action that drags a route handle. */\nexport const ROUTE_EDIT_ACTION_ID = 'diagram.editRoute';\n\n/** An edge's route edited: its waypoints as they now stand. */\nexport interface RouteEdit {\n edgeId: string;\n waypoints: readonly Vec2[];\n}\n\n/** Options for the route-editing actions: the drag, the double-click that removes, and Reset route. */\nexport interface RouteEditOptions<TPose> extends EdgeEndOptions<TPose> {\n participants: ParticipantSource<TPose>;\n /** The selected edge ids, whose routes show handles. */\n selected: () => readonly string[];\n /** Screen pixels within which a dragged handle lines up with a neighbor\n * or a port's axis. Default 6. */\n snapPx?: number;\n /** Screen-pixel reach of a handle, as the handle layer's `hitRadiusPx`. Default 7. */\n hitRadiusPx?: number;\n /** Defaults to {@link commitRouteToScene} against `deps.scene`. */\n commit?: (edit: RouteEdit, ctx: InvocationCtx) => void;\n id?: string;\n}\n\nconst DEFAULT_SNAP_PX = 6;\n\n/** The id of the snap source each route drag brings. */\nconst ROUTE_SNAP_ID = 'diagram-route';\n\n/** `data` with its edge trait routed through `waypoints`: owned by the author\n * from now on, so layout's mark is dropped, and no waypoints at all when there are none. */\nexport function routedData(data: unknown, trait: DiagramEdge, waypoints: readonly Vec2[]): Record<string, unknown> {\n const { waypoints: _w, laidOut: _l, ...rest } = trait;\n return { ...(data as Record<string, unknown>), diagram: waypoints.length > 0 ? { ...rest, waypoints } : rest };\n}\n\n/** The default commit: the edge's new waypoints in `data.diagram`, as one history entry labeled \"Edit route\". */\nexport function commitRouteToScene(edit: RouteEdit, ctx: InvocationCtx): void {\n const scene = ctx.deps.scene;\n const node = scene?.get(edit.edgeId as never);\n const trait = node === undefined ? null : diagramEdgeOf(node);\n if (scene === undefined || node === undefined || trait === null) return;\n scene.batch('Edit route', () => {\n scene.update(node.id, { data: routedData(node.data, trait, edit.waypoints) as never });\n });\n}\n\n/** What a route drag captured at its press, read-only after. */\ninterface RoutePress {\n edgeId: string;\n handle: RouteHandle;\n route: EdgeRouteState;\n trait: DiagramEdge;\n data: unknown;\n pose: unknown;\n press: Vec2;\n deps: InvocationCtx['deps'];\n}\n\n/** The snap session for dragging `handle`, whose point is its probe: a\n * segment held to the axis it slides across, a bend free to turn. */\nfunction beginSnap(ctx: InvocationCtx, p: RoutePress, reachPx: number): SnapSession | null {\n const { handle, route } = p;\n const segment = handle.kind === 'segment';\n const stops = segment\n ? route.drawn.filter((_, i) => i !== handle.index && i !== handle.index + 1)\n : neighborsOf(handle, route.stops);\n const source = routeSnapSource({ id: ROUTE_SNAP_ID, stops, ports: segment ? [] : [route.from, route.to], reachPx });\n return ctx.deps.snap?.begin({\n gesture: 'point',\n press: handle.at,\n ids: [p.edgeId],\n omit: ['path-snap'],\n sources: [source],\n ...(segment ? { handle: handle.axis === 'x' ? { x: 'free', y: 'min' } : { x: 'min', y: 'free' } } : { constrain: 'axis' }),\n }) ?? null;\n}\n\n/** The stops either side of a dragged bend or of the leg a bend is inserted in. */\nfunction neighborsOf(handle: Exclude<RouteHandle, { kind: 'segment' }>, stops: readonly Vec2[]): Vec2[] {\n const at = handle.kind === 'vertex' ? handle.index + 1 : handle.leg + 1;\n return [stops[at - 1]!, stops[handle.kind === 'vertex' ? at + 1 : at]!];\n}\n\n/** How far the handle moves with the pointer at `ctx.world`, snapped through `session`. */\nfunction moveOf(p: RoutePress, session: SnapSession | null, ctx: InvocationCtx): Vec2 {\n const d = { x: ctx.world.x - p.press.x, y: ctx.world.y - p.press.y };\n if (session === null) return d;\n const at = session.at({ x: p.handle.at.x + d.x, y: p.handle.at.y + d.y }, snapMods(ctx)).point;\n return { x: at.x - p.handle.at.x, y: at.y - p.handle.at.y };\n}\n\n/** The waypoints the handle proposes moved by `d`, or null for none. A\n * segment reads only the axis it slides across. */\nfunction waypointsAt(p: RoutePress, d: Vec2): readonly Vec2[] | null {\n if (d.x === 0 && d.y === 0) return null;\n const { handle, route } = p;\n let next: Vec2[];\n if (handle.kind === 'segment') {\n const across = handle.axis === 'x' ? 'y' : 'x';\n const offset = d[across];\n next = route.router === avoid\n ? pinSegment(route.drawn, route.stops, handle.index, offset)\n : dragSegment(route.drawn, handle.index, offset);\n } else {\n const point = { x: handle.at.x + d.x, y: handle.at.y + d.y };\n next = handle.kind === 'vertex' ? dragVertex(route.stops, handle.index, point) : insertWaypoint(route.stops, handle.leg, point);\n }\n return samePoints(next, p.trait.waypoints ?? []) ? null : next;\n}\n\n/** The `diagram.editRoute` action: an ongoing drag reshaping one edge's route. */\nexport function createRouteEditAction<TPose>(opts: RouteEditOptions<TPose>): Action {\n const { commit = commitRouteToScene, snapPx = DEFAULT_SNAP_PX } = opts;\n const endsOf = createEdgeEnds(opts.participants, opts);\n return {\n id: opts.id ?? ROUTE_EDIT_ACTION_ID,\n label: 'Edit route',\n group: 'diagram',\n requires: ['scene', 'view', 'snap'],\n modifierRoles: SNAP_ROLES,\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const pressed = waypointScratchOf(ctx.drag?.affordance);\n const ends = pressed === null ? null : endsOf(pressed.edgeId);\n if (pressed === null || ends === null) return {};\n const p: RoutePress = {\n edgeId: pressed.edgeId,\n handle: pressed.handle,\n route: routeStateOf(ends as never, opts.routers),\n trait: ends.trait,\n data: ends.edge.node.data,\n pose: ends.edge.pose,\n press: ctx.drag?.start ?? { x: ctx.world.x, y: ctx.world.y },\n deps: ctx.deps,\n };\n const session = beginSnap(ctx, p, snapPx);\n let waypoints: readonly Vec2[] | null = null;\n let open = true;\n const proposed = () => (open ? waypoints : null);\n return {\n kind: 'diagram-edit-route',\n onMove(moveCtx: InvocationCtx): void {\n waypoints = waypointsAt(p, moveOf(p, session, moveCtx));\n },\n previewIds: () => (proposed() === null ? null : [p.edgeId]),\n previewPose: (id) => (id === p.edgeId && proposed() !== null ? p.pose : null),\n previewData: (id) => {\n const next = proposed();\n return id === p.edgeId && next !== null ? routedData(p.data, p.trait, next) : null;\n },\n onEnd(endCtx: InvocationCtx, reason: 'commit' | 'cancel'): void {\n open = false;\n const final = reason === 'commit' ? waypointsAt(p, moveOf(p, session, endCtx)) : null;\n session?.end();\n if (final !== null) commit({ edgeId: p.edgeId, waypoints: final }, { ...endCtx, deps: p.deps });\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * The route edits that are not drags: a double-click on a route handle, and\n * the Reset route command.\n */\nimport { ActionDisabledReason, type Action, type ActionDeps, type InvocationCtx } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { createEdgeEnds } from './edgeEndLayer';\nimport { diagramEdgeOf } from './edgeTrait';\nimport { commitRouteToScene, type RouteEdit, type RouteEditOptions } from './waypointAction';\nimport { WAYPOINT_HIT_PX, routeStateOf, waypointScratchOf, type EdgeRouteState } from './waypointLayer';\nimport { avoid } from './edge';\nimport { removeSegment, removeWaypoint, unpinSegment, type RouteHandle } from './waypoints';\n\n/** The action that removes a waypoint, straightens a segment, or unpins an\n * `avoid` connector's segment, on a double-click of its handle. */\nexport const REMOVE_WAYPOINT_ACTION_ID = 'diagram.removeWaypoint';\n/** The command that clears the selected edges' waypoints. */\nexport const RESET_ROUTE_ACTION_ID = 'diagram.resetRoute';\n\nconst NO_MODIFIERS = { alt: false, shift: false, meta: false, ctrl: false };\n\n/** The waypoints left once `handle` is double-clicked away; null where it removes nothing. */\nfunction removalOf(route: EdgeRouteState, handle: RouteHandle): Vec2[] | null {\n if (handle.kind === 'vertex') return removeWaypoint(route.stops, handle.index);\n if (handle.kind === 'segment') {\n return route.router === avoid ? unpinSegment(route.drawn, route.stops, handle.index) : removeSegment(route.drawn, handle.index);\n }\n return null;\n}\n\n/** The `diagram.removeWaypoint` action: a double-click on a waypoint's dot\n * removes it, and on a segment's bar straightens that jog away. Where it\n * would remove nothing it declines, so the double-click reaches whatever is\n * under the handle, an edge's label editing among them. */\nexport function createRemoveWaypointAction<TPose>(opts: RouteEditOptions<TPose>): Action {\n const { commit = commitRouteToScene, hitRadiusPx = WAYPOINT_HIT_PX } = opts;\n const endsOf = createEdgeEnds(opts.participants, opts);\n const routeOf = (edgeId: string) => {\n const ends = endsOf(edgeId);\n return ends === null ? null : routeStateOf(ends as never, opts.routers);\n };\n /** The removal a double-click at `at` makes, read off the handles as the layer places them. */\n const removalAt = (deps: ActionDeps | undefined, at: Vec2): RouteEdit | null => {\n const reach = hitRadiusPx / Math.abs(deps?.view?.get().scale.x || 1);\n for (const edgeId of opts.selected()) {\n const route = routeOf(edgeId);\n for (const handle of route?.handles ?? []) {\n if (Math.max(Math.abs(handle.at.x - at.x), Math.abs(handle.at.y - at.y)) > reach) continue;\n const waypoints = removalOf(route!, handle);\n if (waypoints !== null) return { edgeId, waypoints };\n }\n }\n return null;\n };\n return {\n id: REMOVE_WAYPOINT_ACTION_ID,\n label: 'Remove waypoint',\n group: 'diagram',\n requires: ['scene', 'view'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const world = { x: Number(params?.worldX), y: Number(params?.worldY) };\n const pressed = waypointScratchOf((params as { affordance?: { payload?: unknown } } | undefined)?.affordance);\n const route = pressed === null ? null : routeOf(pressed.edgeId);\n const waypoints = pressed === null || route === null ? null : removalOf(route, pressed.handle);\n const edit = pressed !== null && waypoints !== null ? { edgeId: pressed.edgeId, waypoints } : removalAt(deps, world);\n if (edit !== null) commit(edit, { world, modifiers: NO_MODIFIERS, deps } as InvocationCtx);\n },\n },\n enabled: (deps, at) => (at !== undefined && removalAt(deps, at) !== null ? true : ActionDisabledReason.NotApplicable),\n };\n}\n\n/** The selected edges that have waypoints of their own. */\nfunction routedEdges<TPose>(opts: RouteEditOptions<TPose>): string[] {\n const ids = new Set(opts.selected());\n if (ids.size === 0) return [];\n const out: string[] = [];\n for (const { node } of opts.participants()) {\n if (ids.has(node.id) && (diagramEdgeOf(node)?.waypoints ?? []).length > 0) out.push(node.id);\n }\n return out;\n}\n\n/** The `diagram.resetRoute` command: clears the selected edges' waypoints,\n * in one history entry when they commit to the scene. */\nexport function createResetRouteAction<TPose>(opts: RouteEditOptions<TPose>): Action {\n const { commit = commitRouteToScene } = opts;\n return {\n id: RESET_ROUTE_ACTION_ID,\n label: 'Reset route',\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run(deps) {\n const edges = routedEdges(opts);\n const ctx = { world: { x: 0, y: 0 }, modifiers: NO_MODIFIERS, deps } as InvocationCtx;\n const all = () => { for (const edgeId of edges) commit({ edgeId, waypoints: [] }, ctx); };\n if (deps.scene === undefined) all();\n else deps.scene.batch('Reset route', all);\n },\n },\n enabled: () => (routedEdges(opts).length > 0 ? true : ActionDisabledReason.NotApplicable),\n };\n}\n","/**\n * The commands that set the selected connectors' router: Around shapes,\n * Orthogonal, Straight, and Curved. Leaving `avoid` drops the stored route;\n * joining it leaves the route to the edit pass `useAvoidRouting` installs,\n * which routes the connectors in the same history entry.\n */\nimport { ActionDisabledReason, type Action, type InvocationCtx } from '@weasel-js/core';\nimport { diagramEdgeOf, type DiagramEdge } from './edgeTrait';\nimport type { ParticipantSource } from './portAffordance';\n\n/** The router commands' ids, by router key. */\nexport const SET_ROUTER_ACTION_IDS = {\n avoid: 'diagram.router.avoid',\n orthogonal: 'diagram.router.orthogonal',\n straight: 'diagram.router.straight',\n bezier: 'diagram.router.bezier',\n} as const;\n\n/** Each shipped router's name in a menu. */\nexport const ROUTER_LABELS: Readonly<Record<keyof typeof SET_ROUTER_ACTION_IDS, string>> = {\n avoid: 'Around shapes',\n orthogonal: 'Orthogonal',\n straight: 'Straight',\n bezier: 'Curved',\n};\n\n/** One connector's router changed. */\nexport interface RouterEdit {\n edgeId: string;\n router: string;\n}\n\n/** Options for {@link createSetRouterAction}. */\nexport interface SetRouterOptions<TPose> {\n participants: ParticipantSource<TPose>;\n /** The selected ids; the connectors among them are set. */\n selected: () => readonly string[];\n /** Defaults to {@link commitRouterToScene} against `deps.scene`. */\n commit?: (edit: RouterEdit, ctx: InvocationCtx) => void;\n}\n\n/** `data` with its edge trait on `router`, its stored route dropped. */\nexport function withRouter(data: unknown, trait: DiagramEdge, router: string): Record<string, unknown> {\n const { route: _r, ...rest } = trait;\n return { ...(data as Record<string, unknown>), diagram: { ...rest, router } };\n}\n\n/** The default commit: the connector's `data.diagram.router`, written to the scene. */\nexport function commitRouterToScene(edit: RouterEdit, ctx: InvocationCtx): void {\n const scene = ctx.deps.scene;\n const node = scene?.get(edit.edgeId as never);\n const trait = node === undefined ? null : diagramEdgeOf(node);\n if (scene === undefined || node === undefined || trait === null) return;\n scene.update(node.id, { data: withRouter(node.data, trait, edit.router) as never });\n}\n\n/** The selected connectors, and the router each names. */\nfunction selectedEdges<TPose>(opts: SetRouterOptions<TPose>): { id: string; router: string }[] {\n const ids = new Set(opts.selected());\n if (ids.size === 0) return [];\n const out: { id: string; router: string }[] = [];\n for (const { node } of opts.participants()) {\n const trait = ids.has(node.id) ? diagramEdgeOf(node) : null;\n if (trait !== null) out.push({ id: node.id, router: trait.router ?? 'straight' });\n }\n return out;\n}\n\nconst NO_MODIFIERS = { alt: false, shift: false, meta: false, ctrl: false };\n\n/** The command that puts the selected connectors on `router`, in one history\n * entry. Active while every selected connector is on it already. */\nexport function createSetRouterAction<TPose>(router: keyof typeof SET_ROUTER_ACTION_IDS, opts: SetRouterOptions<TPose>): Action {\n const { commit = commitRouterToScene } = opts;\n return {\n id: SET_ROUTER_ACTION_IDS[router],\n label: ROUTER_LABELS[router],\n group: 'diagram',\n requires: ['scene'],\n invoker: {\n timing: 'immediate',\n run(deps) {\n const edges = selectedEdges(opts).filter((e) => e.router !== router);\n const ctx = { world: { x: 0, y: 0 }, modifiers: NO_MODIFIERS, deps } as InvocationCtx;\n const all = () => { for (const e of edges) commit({ edgeId: e.id, router }, ctx); };\n if (deps.scene === undefined) all();\n else deps.scene.batch(`Route ${ROUTER_LABELS[router].toLowerCase()}`, all);\n },\n },\n enabled: () => (selectedEdges(opts).length > 0 ? true : ActionDisabledReason.NotApplicable),\n active: () => {\n const edges = selectedEdges(opts);\n return edges.length > 0 && edges.every((e) => e.router === router);\n },\n };\n}\n\n/** One command per shipped router, in menu order. */\nexport function routerActions<TPose>(opts: SetRouterOptions<TPose>): Action[] {\n return (Object.keys(SET_ROUTER_ACTION_IDS) as (keyof typeof SET_ROUTER_ACTION_IDS)[]).map((r) => createSetRouterAction(r, opts));\n}\n","/**\n * The plugin as a `Contribution` bundle — one object a consumer hands to\n * `<SceneCanvas ambient={…}>`.\n *\n * **Ambient, not a tool.** A port is grabbable whatever tool is active:\n * `claimed` makes the bundle live for a press the port layer's affordance\n * 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 — so the port layer as an overlay would paint every port and\n * make none of them grabbable. {@link diagramPorts} hands back both.\n */\nimport {\n ActionDisabledReason,\n type Action,\n type Contribution,\n type CursorSpec,\n type NodeId,\n type RenderLayer,\n type Scene,\n} from '@weasel-js/core';\nimport {\n CONNECT_ACTION_ID,\n connectBinding,\n createConnectAction,\n grabPortAction,\n grabPortBindings,\n type ConnectActionOptions,\n} from './connect';\nimport { EDIT_EDGE_LABEL_ACTION_ID } from './edgeLabel';\nimport { createSetHopsAction } from './hops/hopsAction';\nimport { createResetLabelAction } from './labelCommands';\nimport { MOVE_LABEL_ACTION_ID, createLabelDragAction, type LabelDragOptions } from './labelDragAction';\nimport { LABEL_DRAG_AFFORDANCE_KIND, labelDragLayer, labelScratchOf } from './labelDragLayer';\nimport { portLayer } from './portLayer';\nimport type { PortAffordanceOptions } from './portAffordance';\nimport { REMOVE_WAYPOINT_ACTION_ID, createRemoveWaypointAction, createResetRouteAction } from './routeCommands';\nimport { routerActions } from './routerCommands';\nimport { ROUTE_EDIT_ACTION_ID, createRouteEditAction, type RouteEditOptions } from './waypointAction';\nimport {\n WAYPOINT_AFFORDANCE_KIND,\n WAYPOINT_LAYER_ID,\n waypointLayer,\n type WaypointAffordanceOptions,\n} from './waypointLayer';\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/** The action id that absorbs the rest of a press on a route handle. */\nexport const GRAB_WAYPOINT_ACTION_ID = 'diagram.grabWaypoint';\n\n/**\n * Both halves of route editing: the handle layer to `registerLayer` — after\n * the port layer and before the edge-end layer, so an end handle wins over a\n * route handle beside it — and the contribution to pass as `ambient`, which\n * carries the drag, the double-click that removes, the\n * `diagram.resetRoute` command, the commands that set the selected\n * connectors' router (`SET_ROUTER_ACTION_IDS`), and the line jumps toggle\n * (`SET_HOPS_ACTION_ID`). Like `diagramPorts`, one without the other\n * fails quietly.\n */\nexport function diagramWaypoints<TPose>(\n opts: RouteEditOptions<TPose> & Omit<WaypointAffordanceOptions<TPose>, 'id'>,\n): { layer: RenderLayer<unknown>; contribution: Contribution } {\n const actionId = opts.id ?? ROUTE_EDIT_ACTION_ID;\n const target = `affordance:${WAYPOINT_AFFORDANCE_KIND}` as const;\n return {\n // `opts.id` names the drag action; the layer keeps its own id.\n layer: waypointLayer(opts.participants, opts.selected, { ...opts, id: WAYPOINT_LAYER_ID }),\n contribution: {\n id: 'weasel-diagram-waypoints',\n eligibility: { claimed: true },\n actions: [\n createRouteEditAction({ ...opts, id: actionId }),\n createRemoveWaypointAction(opts),\n createResetRouteAction(opts),\n ...routerActions({ participants: opts.participants, selected: opts.selected }),\n createSetHopsAction(),\n grabPortAction(GRAB_WAYPOINT_ACTION_ID),\n ],\n bindings: [\n { spec: { kind: 'drag', target }, actionId },\n { spec: { kind: 'doubleClick', target }, actionId: REMOVE_WAYPOINT_ACTION_ID },\n ...grabPortBindings(GRAB_WAYPOINT_ACTION_ID, WAYPOINT_AFFORDANCE_KIND),\n ],\n },\n };\n}\n\n/** The action id that absorbs a press on an edge label, so it reaches neither marquee nor pan. */\nexport const GRAB_LABEL_ACTION_ID = 'diagram.grabLabel';\n\n/** The action id that selects a clicked label's edge. */\nexport const SELECT_LABEL_EDGE_ACTION_ID = 'diagram.selectLabelEdge';\n\nconst NO_MODIFIERS = { shift: false, meta: false, ctrl: false };\nconst ANY_MODIFIERS = { shift: 'optional', meta: 'optional', ctrl: 'optional', alt: 'optional' } as const;\n\nfunction selectLabelEdgeAction(): Action {\n return {\n id: SELECT_LABEL_EDGE_ACTION_ID,\n label: 'Select label edge',\n group: 'diagram',\n requires: ['selection'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const p = params as { affordance?: { payload?: unknown }; mods?: { shift: boolean; meta: boolean; ctrl: boolean } } | undefined;\n const pressed = labelScratchOf(p?.affordance);\n if (pressed !== null) deps.selection?.applyClick(pressed.edgeId as NodeId, p?.mods ?? NO_MODIFIERS);\n },\n },\n enabled: (deps) => (deps?.selection !== undefined ? true : ActionDisabledReason.NotApplicable),\n };\n}\n\n/**\n * Both halves of label dragging: the label layer to `registerLayer` — before\n * the port layer, so a port or a route handle wins over a label beside it —\n * and the contribution to pass as `ambient`, which carries the drag\n * (`diagram.moveLabel`), a click that selects the label's edge, and a\n * double-click that edits the label's text through\n * `EDIT_EDGE_LABEL_ACTION_ID`, which the host registers. Like `diagramPorts`,\n * one without the other fails quietly.\n */\nexport function diagramLabelDrag(\n opts: LabelDragOptions & { scene: Scene<unknown, string, unknown>; selected: () => readonly string[]; cursor?: CursorSpec },\n): { layer: RenderLayer<unknown>; contribution: Contribution } {\n const actionId = opts.id ?? MOVE_LABEL_ACTION_ID;\n const target = `affordance:${LABEL_DRAG_AFFORDANCE_KIND}` as const;\n return {\n layer: labelDragLayer(opts.scene, opts.cursor !== undefined ? { cursor: opts.cursor } : {}),\n contribution: {\n id: 'weasel-diagram-label-drag',\n eligibility: { claimed: true },\n actions: [\n createLabelDragAction({ ...opts, id: actionId }),\n createResetLabelAction({ selected: opts.selected, ...(opts.commit ? { commit: opts.commit } : {}) }),\n grabPortAction(GRAB_LABEL_ACTION_ID),\n selectLabelEdgeAction(),\n ],\n bindings: [\n { spec: { kind: 'drag', target }, actionId },\n { spec: { kind: 'pointerDown', target }, actionId: GRAB_LABEL_ACTION_ID },\n { spec: { kind: 'click', target, mods: ANY_MODIFIERS }, actionId: SELECT_LABEL_EDGE_ACTION_ID },\n { spec: { kind: 'doubleClick', target }, actionId: EDIT_EDGE_LABEL_ACTION_ID },\n ],\n },\n };\n}\n","/**\n * A diagram scene as the avoid router reads it: every participant, container,\n * pool, group box, and header as an obstacle, and every `avoid` connector not\n * split across pages, with the ports each end may use and its label. A split\n * connector's label, on its first stub, is an obstacle of its own.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n documentPose,\n type PoseDescriptor,\n type Scene,\n} from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { diagramContainerOf, headerBox } from '../containers/trait';\nimport { diagramEdgeOf } from '../edgeTrait';\nimport { diagramGroupOf } from '../group';\nimport { diagramLabelOf } from '../labelTrait';\nimport { portSitesOf, portsOf, type PortsOptions } from '../ports';\nimport { diagramNodeOf } from '../trait';\nimport type { Port } from '../types';\nimport type { AvoidEdge, AvoidInput, AvoidLabel, AvoidObstacle, AvoidPort } from './types';\n\n/** How a scene is read for routing. */\nexport interface AvoidSceneOptions<TPose> extends PortsOptions<TPose> {\n /** The router key whose connectors are routed. Default `'avoid'`. */\n routerKey?: string;\n}\n\ntype AnyScene = Scene<unknown, string, unknown>;\ntype SceneNode = ReturnType<AnyScene['renderOrderNodes']>[number];\n\n/** The id of a container's header obstacle. */\nexport const headerIdOf = (id: string): string => `${id}/header`;\n\nconst facingPorts = (ports: readonly Port[]): AvoidPort[] =>\n ports.flatMap((p) => (p.normal === null ? [] : [{ point: p.point, normal: p.normal }]));\n\n/** Every id under `node`, at any depth: its children, or what a derived group box holds. */\nfunction members(scene: AnyScene, node: SceneNode, into: Set<string>): Set<string> {\n const under = Array.isArray(node.dependsOn) && diagramGroupOf(node) !== null ? node.dependsOn : scene.childrenOf(node.id as never);\n for (const id of under) {\n if (into.has(id)) continue;\n into.add(id);\n const child = scene.get(id as never);\n if (child !== undefined) members(scene, child, into);\n }\n return into;\n}\n\n/**\n * What the router reads off `scene`: its obstacles and its `avoid` connectors,\n * each node at the pose `poseOf` gives it, else the one the document holds.\n */\nexport function avoidSceneInput<TPose>(\n scene: Scene<unknown, string, TPose>,\n opts: AvoidSceneOptions<TPose> = {},\n poseOf?: (id: string) => TPose | undefined,\n): AvoidInput {\n const sc = scene as unknown as AnyScene;\n const geometry = opts.geometry ?? (AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>);\n const portOpts: PortsOptions<TPose> = { geometry, ...(opts.read ? { read: opts.read } : {}) };\n const key = opts.routerKey ?? 'avoid';\n const poses = new Map<string, TPose>();\n const pose = (node: SceneNode): TPose => {\n let p = poses.get(node.id);\n if (p === undefined) {\n p = poseOf?.(node.id) ?? (documentPose(sc, node as never) as TPose);\n poses.set(node.id, p);\n }\n return p;\n };\n\n const obstacles: AvoidObstacle[] = [];\n const edgeNodes: SceneNode[] = [];\n const labels = new Map<string, AvoidLabel>();\n const labelNodes = new Map<string, SceneNode>();\n const split: string[] = [];\n for (const node of sc.renderOrderNodes()) {\n const edge = diagramEdgeOf(node);\n if (edge !== null) {\n if (edge.router === key && edge.offPage === undefined) edgeNodes.push(node);\n else if (edge.router === key) split.push(node.id);\n continue;\n }\n const label = diagramLabelOf(node);\n if (label !== null) {\n const owner = Array.isArray(node.dependsOn) ? node.dependsOn[0] : undefined;\n const { width, height } = geometry.getBounds(node.pose as TPose);\n if (owner !== undefined && !labels.has(owner)) {\n labels.set(owner, { id: node.id, placement: label, size: { width, height } });\n labelNodes.set(owner, node);\n }\n continue;\n }\n const container = diagramContainerOf(node);\n const isParticipant = diagramNodeOf(node as never, opts.read) !== null;\n if (!isParticipant && container?.role !== 'lane') continue;\n const box = geometry.getBounds(pose(node));\n const header = container === null ? null : headerBox(box, container.header);\n if (header !== null) obstacles.push({ id: headerIdOf(node.id), kind: 'shape', box: header });\n if (container?.role === 'lane') continue;\n const region = container !== null || diagramGroupOf(node) !== null;\n obstacles.push(region\n ? { id: node.id, kind: 'region', box, members: members(sc, node, new Set()) }\n : { id: node.id, kind: 'shape', box });\n }\n\n for (const id of split) {\n const node = labelNodes.get(id);\n if (node !== undefined) obstacles.push({ id: node.id, kind: 'label', edge: id, box: geometry.getBounds(pose(node)) });\n }\n\n const edges: AvoidEdge[] = [];\n for (const node of edgeNodes) {\n const edge = diagramEdgeOf(node)!;\n const ends = node.dependsOn;\n if (!Array.isArray(ends) || ends.length !== 2) continue;\n if (ends[0] === ends[1] && edge.from.port === undefined && edge.to.port === undefined) continue;\n const [a, b] = ends.map((id) => sc.get(id as never));\n if (a === undefined || b === undefined) continue;\n const portsAt = (n: SceneNode, port: string | undefined) => facingPorts(port === undefined\n ? portsOf(n as never, pose(n), portOpts)\n : portSitesOf(n as never, pose(n), port, portOpts));\n const from = portsAt(a, edge.from.port);\n const to = portsAt(b, edge.to.port);\n if (from.length === 0 || to.length === 0) continue;\n edges.push({\n id: node.id,\n from: { node: a.id, ports: from },\n to: { node: b.id, ports: to },\n ...(edge.waypoints !== undefined && edge.waypoints.length > 0 ? { waypoints: edge.waypoints as Vec2[] } : {}),\n ...(edge.route !== undefined ? { route: edge.route } : {}),\n ...(labels.has(node.id) ? { label: labels.get(node.id)! } : {}),\n });\n }\n return { obstacles, edges };\n}\n","/**\n * Routes for a data-backed diagram: the specs `diagramScene` builds, with\n * every edge routed around the shapes. The routes derive from the data, so\n * they live in the specs and are never reported back to the host.\n */\nimport type { RectPose } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { diagramContainerOf, headerBox } from '../containers/trait';\nimport { diagramEdgeOf, type DiagramEdge } from '../edgeTrait';\nimport type { DiagramSpec } from '../fromData';\nimport { diagramLabelOf } from '../labelTrait';\nimport { portSitesOf, portsOf } from '../ports';\nimport { diagramNodeOf } from '../trait';\nimport type { Port } from '../types';\nimport { createAvoidRouter } from './router';\nimport { headerIdOf } from './sceneInput';\nimport type { AvoidEdge, AvoidLabel, AvoidObstacle, AvoidOptions, AvoidPort } from './types';\n\nconst facing = (ports: readonly Port[]): AvoidPort[] =>\n ports.flatMap((p) => (p.normal === null ? [] : [{ point: p.point, normal: p.normal }]));\n\n/** The obstacles specs make, as `avoidSceneInput` reads a scene: a shape's box; a\n * container's or pool's box as a region holding what is inside it, and its header;\n * a lane's header alone. A derived box, a group's, is none. */\nfunction obstaclesOf(specs: readonly DiagramSpec[]): AvoidObstacle[] {\n const children = new Map<string, string[]>();\n for (const s of specs) {\n if (s.parent == null) continue;\n children.set(s.parent as string, [...(children.get(s.parent as string) ?? []), s.id as string]);\n }\n const inside = (id: string, into: Set<string>): Set<string> => {\n for (const child of children.get(id) ?? []) {\n into.add(child);\n inside(child, into);\n }\n return into;\n };\n const out: AvoidObstacle[] = [];\n for (const spec of specs) {\n const node = { id: spec.id as string, kind: spec.kind, data: spec.data };\n if (spec.derivePose !== undefined || diagramEdgeOf(spec) !== null) continue;\n const region = diagramContainerOf(spec);\n if (diagramNodeOf(node) === null && region?.role !== 'lane') continue;\n const header = region === null ? null : headerBox(spec.pose, region.header);\n if (header !== null) out.push({ id: headerIdOf(node.id), kind: 'shape', box: header });\n if (region?.role === 'lane') continue;\n out.push(region === null\n ? { id: node.id, kind: 'shape', box: spec.pose }\n : { id: node.id, kind: 'region', box: spec.pose, members: inside(node.id, new Set()) });\n }\n return out;\n}\n\n/** Each edge's label spec, by the edge it labels. */\nfunction labelsOf(specs: readonly DiagramSpec[]): Map<string, AvoidLabel> {\n const out = new Map<string, AvoidLabel>();\n for (const spec of specs) {\n const label = diagramLabelOf(spec);\n const owner = Array.isArray(spec.dependsOn) ? spec.dependsOn[0] as string | undefined : undefined;\n if (label === null || owner === undefined || out.has(owner)) continue;\n const { width, height } = spec.pose as RectPose;\n out.set(owner, { id: spec.id as string, placement: label, size: { width, height } });\n }\n return out;\n}\n\n/**\n * A function from specs to the same specs with each edge on `avoid` and\n * holding its route. It holds one router across calls, so each call reroutes\n * only the edges the change since the last one disturbed.\n */\nexport function createSpecRouter(options: AvoidOptions = {}): (specs: readonly DiagramSpec[]) => DiagramSpec[] {\n const router = createAvoidRouter(options);\n let held = new Map<string, Vec2[] | null>();\n return (specs) => {\n const byId = new Map(specs.map((s) => [s.id as string, s]));\n const labels = labelsOf(specs);\n const obstacles = obstaclesOf(specs);\n const edges: AvoidEdge[] = [];\n for (const spec of specs) {\n const edge = diagramEdgeOf(spec);\n if (edge === null || edge.offPage !== undefined) continue;\n const ends = Array.isArray(spec.dependsOn) ? spec.dependsOn.map((id) => byId.get(id as string)) : [];\n const [a, b] = ends;\n if (a === undefined || b === undefined || a === b) continue;\n const portsAt = (s: DiagramSpec, port: string | undefined) => {\n const n = { id: s.id as string, kind: s.kind, data: s.data };\n return facing(port === undefined ? portsOf(n, s.pose as RectPose) : portSitesOf(n, s.pose as RectPose, port));\n };\n const route = held.get(spec.id as string);\n edges.push({\n id: spec.id as string,\n from: { node: a.id as string, ports: portsAt(a, edge.from.port) },\n to: { node: b.id as string, ports: portsAt(b, edge.to.port) },\n ...(edge.waypoints !== undefined && edge.waypoints.length > 0 ? { waypoints: edge.waypoints } : {}),\n ...(route != null ? { route } : {}),\n ...(labels.has(spec.id as string) ? { label: labels.get(spec.id as string)! } : {}),\n });\n }\n if (edges.length === 0) return [...specs];\n const next = new Map(held);\n for (const [id, route] of router.update({ obstacles, edges })) next.set(id, route);\n held = new Map(edges.map((e) => [e.id, next.get(e.id) ?? null]));\n return specs.map((spec) => {\n const edge = diagramEdgeOf(spec);\n if (edge === null || !held.has(spec.id as string)) return spec;\n const route = held.get(spec.id as string);\n const { route: _r, ...rest } = edge;\n const diagram: DiagramEdge = { ...rest, router: 'avoid', ...(route != null ? { route } : {}) };\n return { ...spec, data: { ...spec.data, diagram } };\n });\n };\n}\n","/**\n * A scene's connectors as line jumps read them: each one's route before any\n * hop, and the data write that stores its hops.\n */\nimport { AUTO_POSE_DESCRIPTOR, createSetDataOp, documentPose, type DerivedDep, type Op, type Scene } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { edgeRouter, type EdgeRouteOptions } from '../edge';\nimport { diagramEdgeOf, type DiagramEdge } from '../edgeTrait';\nimport type { EdgeHop } from './types';\n\nexport type AnyScene = Scene<unknown, string, unknown>;\nexport type SceneNode = ReturnType<AnyScene['renderOrderNodes']>[number];\n\n/** A connector: its node and the ids of its two ends. */\nexport interface SceneEdge {\n node: SceneNode;\n trait: DiagramEdge;\n ends: readonly [string, string];\n}\n\n/** Every connector in `scene`, in render order. */\nexport function sceneEdges(scene: AnyScene): SceneEdge[] {\n const out: SceneEdge[] = [];\n for (const node of scene.renderOrderNodes()) {\n const trait = diagramEdgeOf(node);\n const ends = node.dependsOn;\n if (trait === null || !Array.isArray(ends) || ends.length !== 2) continue;\n out.push({ node, trait, ends: [ends[0]!, ends[1]!] });\n }\n return out;\n}\n\n/** A function from a connector to the points it is routed through, as its\n * `derivePath` routes it before drawing any hop; null where it draws nothing,\n * and for a connector split across pages: its stubs are shorter than a hop's\n * clearance from their ends, and the run between them is not drawn. */\nexport function edgePolylines<TPose>(scene: AnyScene, opts: EdgeRouteOptions<TPose> = {}): (edge: SceneEdge) => Vec2[] | null {\n const route = edgeRouter<unknown>({ geometry: AUTO_POSE_DESCRIPTOR, ...(opts as EdgeRouteOptions<unknown>) });\n const dep = (id: string): DerivedDep<unknown> | undefined => {\n const node = scene.get(id as never);\n return node === undefined ? undefined : ({ node, pose: documentPose(scene, node as never), path: null } as DerivedDep<unknown>);\n };\n return (edge) => {\n const routed = route(edge.node, [dep(edge.ends[0]), dep(edge.ends[1])]);\n const points = routed?.stubs === undefined ? routed?.points : undefined;\n return points === undefined || points.length < 2 ? null : [...points];\n };\n}\n\n/** Whether `id`, or a node it sits in, is in `ids`. */\nexport function inOrUnder(scene: AnyScene, id: string, ids: { has(id: string): boolean }): boolean {\n for (let at: string | null | undefined = id; at != null; at = scene.get(at as never)?.parent) {\n if (ids.has(at)) return true;\n }\n return false;\n}\n\n/** `data` with its edge trait holding `hops`, or none when the list is empty. */\nexport function withHopsData(data: unknown, trait: DiagramEdge, hops: readonly EdgeHop[]): Record<string, unknown> {\n const { hops: _h, ...rest } = trait;\n return { ...(data as Record<string, unknown>), diagram: hops.length === 0 ? rest : { ...rest, hops } };\n}\n\nconst sameHop = (a: EdgeHop, b: EdgeHop): boolean =>\n a.at.x === b.at.x && a.at.y === b.at.y && a.r === b.r && a.over.length === b.over.length && a.over.every((o, i) => o === b.over[i]);\n\n/** The data writes that store `hops` on their connectors, skipping any unchanged. */\nexport function hopDataOps(scene: AnyScene, hops: ReadonlyMap<string, readonly EdgeHop[]>): Op[] {\n const ops: Op[] = [];\n for (const [id, list] of hops) {\n const node = scene.get(id as never);\n const trait = node === undefined ? null : diagramEdgeOf(node);\n if (node === undefined || trait === null) continue;\n const had = trait.hops ?? [];\n if (had.length === list.length && had.every((h, i) => sameHop(h, list[i]!))) continue;\n ops.push(createSetDataOp({ id, from: node.data, to: withHopsData(node.data, trait, list), label: 'Line jumps' }));\n }\n return ops;\n}\n","/**\n * Line jumps for a data-backed diagram: the specs `diagramScene` builds, with\n * each edge carrying the hops it makes over the edges before it. The hops\n * derive from the specs, so they live there and are never reported back.\n */\nimport type { DerivedDep, RectPose } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { edgeRouter } from '../edge';\nimport { diagramEdgeOf } from '../edgeTrait';\nimport type { DiagramSpec } from '../fromData';\nimport { edgeHops } from './crossings';\nimport { withHopsData } from './sceneEdges';\n\n/** A function from specs to the same specs with every edge's hops of radius\n * `r`, edges hopping those earlier in the list. An edge split across pages\n * takes no part. */\nexport function createSpecHops(r: number): (specs: readonly DiagramSpec[]) => DiagramSpec[] {\n const route = edgeRouter<RectPose>();\n return (specs) => {\n const byId = new Map(specs.map((s) => [s.id as string, s]));\n const dep = (id: string): DerivedDep<RectPose> | undefined => {\n const s = byId.get(id);\n return s === undefined ? undefined : ({ node: s, pose: s.pose, path: null } as unknown as DerivedDep<RectPose>);\n };\n const polylines = new Map<string, Vec2[]>();\n const order: string[] = [];\n for (const spec of specs) {\n const ends = spec.dependsOn;\n if (diagramEdgeOf(spec) === null || !Array.isArray(ends) || ends.length !== 2) continue;\n const routed = route(spec, [dep(ends[0] as string), dep(ends[1] as string)]);\n const points = routed?.stubs === undefined ? routed?.points : undefined;\n if (points === undefined || points.length < 2) continue;\n polylines.set(spec.id as string, [...points]);\n order.push(spec.id as string);\n }\n const hops = edgeHops(polylines, order, r);\n return specs.map((spec) => {\n const trait = diagramEdgeOf(spec);\n const list = hops.get(spec.id as string) ?? [];\n if (trait === null || (list.length === 0 && trait.hops === undefined)) return spec;\n return { ...spec, data: withHopsData(spec.data, trait, list) as DiagramSpec['data'] };\n });\n };\n}\n","/**\n * Reconnect — dragging a selected edge's end onto another port or shape.\n *\n * The edge-end handles (`edgeEndLayer`) claim the press; this action carries\n * the end. It lands where a connect from the edge's other end would land, by\n * the same resolver and the same `canConnect`, asked with the edge's from/to\n * order kept, so a reconnect can never make an edge a connect could not.\n */\nimport type {\n Action,\n Contribution,\n GestureBinding,\n InvocationCtx,\n OngoingHandle,\n OngoingOverlay,\n RenderLayer,\n Vec2,\n} from '@weasel-js/core';\nimport {\n defaultCanConnect,\n edgeEndOf,\n grabPortAction,\n grabPortBindings,\n type ConnectActionOptions,\n type MovingEnd,\n} from './connect';\nimport { createTargets, isBodyEnd, type ConnectEnd } from './connectTargets';\nimport { routerOf, type Router } from './edge';\nimport {\n EDGE_END_AFFORDANCE_KIND,\n EDGE_END_LAYER_ID,\n createEdgeEnds,\n edgeEndLayer,\n edgeEndScratchOf,\n type EdgeEndAffordanceOptions,\n type EdgeEnds,\n} from './edgeEndLayer';\nimport { diagramEdgeOf } from './edgeTrait';\nimport { portOf } from './ports';\n\nexport { EDGE_END_LAYER_ID };\n\n/** The action that drags an edge end onto a new port or body. */\nexport const RECONNECT_ACTION_ID = 'diagram.reconnect';\n/** The action id that absorbs a press on an edge-end handle. */\nexport const GRAB_EDGE_END_ACTION_ID = 'diagram.grabEdgeEnd';\n\n/** One end of one edge, moved onto `target`. */\nexport interface EndChange {\n edgeId: string;\n end: 'from' | 'to';\n target: ConnectEnd;\n}\n\n/** Options for {@link createReconnectAction}. `bodies` defaults to true: an end\n * may be dropped on a shape's body. */\nexport interface ReconnectOptions<TPose> extends Omit<ConnectActionOptions<TPose>, 'commit' | 'startFrom'> {\n /** The selected edge ids whose ends show handles. */\n selected: () => readonly string[];\n /** Defaults to {@link commitReconnectToScene} against `deps.scene`. */\n commit?: (change: EndChange, ctx: InvocationCtx) => void;\n}\n\nconst DEFAULT_SNAP = 16;\n\n/**\n * The default commit: rewrites the moved end in `data.diagram` — `{ port }`,\n * or `{}` for a body — and points the edge's `dependsOn` at the new node, as\n * one history entry.\n */\nexport function commitReconnectToScene(change: EndChange, ctx: InvocationCtx): void {\n const scene = ctx.deps.scene;\n if (scene === undefined) return;\n const node = scene.get(change.edgeId as never);\n const trait = node === undefined ? null : diagramEdgeOf(node);\n const deps = node?.dependsOn;\n if (node === undefined || trait === null || !Array.isArray(deps) || deps.length !== 2) return;\n const data = node.data as Record<string, unknown>;\n const nextDeps = [...deps];\n nextDeps[change.end === 'from' ? 0 : 1] = change.target.nodeId as never;\n scene.batch('Reconnect edge', () => {\n scene.update(node.id, {\n data: { ...data, diagram: { ...trait, [change.end]: edgeEndOf(change.target) } } as never,\n });\n scene.setDependsOn(node.id, nextDeps);\n });\n}\n\n/** The end of `ends` that stays put while `moving` is dragged: its named\n * port, else its body. */\nfunction fixedEndOf<TPose>(ends: EdgeEnds<TPose>, moving: 'from' | 'to', opts: ReconnectOptions<TPose>): ConnectEnd {\n const side = moving === 'from' ? 'to' : 'from';\n const { node, pose } = ends[side];\n const named = ends.trait[side].port;\n const port = named === undefined ? undefined : portOf(node, pose, named, {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.read ? { read: opts.read } : {}),\n });\n return port ?? { kind: 'body', nodeId: node.id, point: ends.points[side] };\n}\n\n/** Whether `target` is the end the edge already has. */\nfunction sameEnd(ends: EdgeEnds<unknown>, moving: 'from' | 'to', target: ConnectEnd): boolean {\n if (ends[moving].node.id !== target.nodeId) return false;\n const named = ends.trait[moving].port;\n return isBodyEnd(target) ? named === undefined : named === target.id;\n}\n\ninterface ReconnectScratch {\n edgeId: string;\n moving: 'from' | 'to';\n fixed: ConnectEnd;\n ends: EdgeEnds<unknown>;\n route: Router;\n current: Vec2;\n open: boolean;\n /** The deps bag from `start`; later pump events carry an empty one. */\n deps: InvocationCtx['deps'];\n}\n\n/** The `diagram.reconnect` action: an ongoing drag carrying one edge end. */\nexport function createReconnectAction<TPose>(opts: ReconnectOptions<TPose>): Action {\n const { canConnect = defaultCanConnect, commit = commitReconnectToScene } = opts;\n const endsOf = createEdgeEnds(opts.participants, opts);\n const shared = { ...opts, snapRadius: opts.snapRadius ?? DEFAULT_SNAP, bodies: opts.bodies ?? true };\n // The resolver asks `canConnect(fixed, candidate)`; a moved `from` end\n // swaps them back so the policy sees the edge's own direction.\n const targetsFor = (moving: MovingEnd) => createTargets({\n ...shared,\n canConnect: moving.end === 'to'\n ? (fixed, candidate) => canConnect(fixed, candidate, moving)\n : (fixed, candidate) => canConnect(candidate, fixed, moving),\n });\n\n return {\n id: opts.id ?? RECONNECT_ACTION_ID,\n label: 'Reconnect',\n group: 'diagram',\n requires: ['scene', 'view'],\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const pressed = edgeEndScratchOf(ctx.drag?.affordance);\n const ends = pressed === null ? null : endsOf(pressed.edgeId);\n if (pressed === null || ends === null) return {};\n const scratch: ReconnectScratch = {\n edgeId: pressed.edgeId,\n moving: pressed.end,\n fixed: fixedEndOf(ends, pressed.end, opts),\n ends: ends as EdgeEnds<unknown>,\n route: routerOf(ends.trait, opts.routers),\n current: { x: ctx.world.x, y: ctx.world.y },\n open: true,\n deps: ctx.deps,\n };\n const resolver = targetsFor({ edge: scratch.edgeId, end: scratch.moving });\n\n return {\n kind: 'diagram-reconnect',\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 points = resolver.preview(scratch.route, scratch.fixed, scratch.current, scratch.deps.view, scratch.moving, scratch.ends.trait.waypoints);\n return points.length < 2 ? null : { 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 target = resolver.target(scratch.fixed, { x: endCtx.world.x, y: endCtx.world.y }, scratch.deps.view);\n if (target === null || sameEnd(scratch.ends, scratch.moving, target)) return;\n commit({ edgeId: scratch.edgeId, end: scratch.moving, target }, { ...endCtx, deps: scratch.deps });\n },\n };\n },\n },\n enabled: () => true as const,\n };\n}\n\n/** The binding that starts a reconnect: a drag pressed on an edge-end handle. */\nexport function reconnectBinding(actionId: string = RECONNECT_ACTION_ID): GestureBinding {\n return { spec: { kind: 'drag', target: `affordance:${EDGE_END_AFFORDANCE_KIND}` }, actionId };\n}\n\n/**\n * Both halves of reconnect: the handle layer to `registerLayer` — after the\n * port layer, since an edge's end sits on a port — and the contribution to\n * pass as `ambient`. Like `diagramPorts`, one without the other fails quietly.\n */\nexport function diagramEdgeEnds<TPose>(\n opts: ReconnectOptions<TPose> & Omit<EdgeEndAffordanceOptions<TPose>, 'id'>,\n): { layer: RenderLayer<unknown>; contribution: Contribution } {\n const actionId = opts.id ?? RECONNECT_ACTION_ID;\n return {\n // `opts.id` names the action; the layer keeps its own id.\n layer: edgeEndLayer(opts.participants, opts.selected, { ...opts, id: EDGE_END_LAYER_ID }),\n contribution: {\n id: 'weasel-diagram-edge-ends',\n eligibility: { claimed: true },\n actions: [createReconnectAction({ ...opts, id: actionId }), grabPortAction(GRAB_EDGE_END_ACTION_ID)],\n bindings: [\n reconnectBinding(actionId),\n ...grabPortBindings(GRAB_EDGE_END_ACTION_ID, EDGE_END_AFFORDANCE_KIND),\n ],\n },\n };\n}\n","/**\n * The `'slide'` look of a reorder: the carried item under the pointer and the\n * others in the places they would take, published as pose overrides so\n * everything that derives its pose from them follows.\n */\nimport { effectivePose, type NodeId, type Scene } from '@weasel-js/core';\nimport type { ReorderItem, ReorderSlots } from './reorder';\n\nexport type Box = { x: number; y: number; width: number; height: number };\n\n/** Where an item stands along the axis: its start and its length. */\ninterface Span {\n start: number;\n size: number;\n}\n\n/**\n * Where each item starts along the axis once they stand in `order`: packed\n * from where the first stood, each gap kept at its place in the row.\n */\nfunction packed(items: readonly string[], spans: ReadonlyMap<string, Span>, order: readonly string[]): Map<string, number> {\n const gaps = items.slice(1).map((m, i) => spans.get(m)!.start - (spans.get(items[i]!)!.start + spans.get(items[i]!)!.size));\n const out = new Map<string, number>();\n let at = items.length > 0 ? spans.get(items[0]!)!.start : 0;\n order.forEach((m, i) => {\n out.set(m, at);\n at += spans.get(m)!.size + (gaps[i] ?? gaps[gaps.length - 1] ?? 0);\n });\n return out;\n}\n\n/** The scene nodes that move with `item`. */\nexport const carriedBy = (item: ReorderItem): readonly string[] => item.carries ?? [item.id];\n\nconst RELEASE_MS = 500;\n\n/** Slides `slots`' items around `carried` until dropped, or kept past a commit. */\nexport function slideOthers(scene: Scene<unknown, string, unknown>, slots: ReorderSlots, carried: string) {\n const { axis } = slots;\n const size = axis === 'x' ? 'width' : 'height';\n const ids = slots.items.map((i) => i.id);\n const spans = new Map(slots.items.map((i) => [i.id, { start: i.bounds[axis], size: i.bounds[size] }]));\n // Nodes that derive their pose follow the ones that hold theirs.\n const nodes = slots.items.map((item) => ({\n id: item.id,\n poses: carriedBy(item).flatMap((id) => {\n const node = scene.get(id as NodeId);\n return node === undefined || node.derivePose !== undefined ? [] : [{ id: id as NodeId, pose: effectivePose(scene, node) as Box }];\n }),\n }));\n const hold = scene.overrides.hold();\n return {\n /** The items standing in `order`, or as they were for `null`, with the carried one `by` along. */\n show(order: readonly string[] | null, by: number): void {\n const starts = packed(ids, spans, order ?? ids);\n hold.set(nodes.flatMap(({ id, poses }) => {\n const d = id === carried ? by : starts.get(id)! - spans.get(id)!.start;\n return poses.map(({ id: node, pose }) => [node, { ...pose, [axis]: pose[axis] + d }] as const);\n }));\n },\n drop: () => hold.drop(),\n /** Held until the host's new specs land, so the items do not jump back for\n * the frames in between; a host that keeps the old order gets it back shortly after. */\n keep(): void {\n const release = () => {\n stop();\n clearTimeout(timer);\n hold.drop();\n };\n const stop = scene.subscribe(release);\n const timer = setTimeout(release, RELEASE_MS);\n },\n };\n}\n","/**\n * Reorder: dragging one item of a drawn sequence — boxes in a row, rows in a\n * column, the members of a group — to another place in it. The item follows\n * the pointer along the sequence's axis and lands in the gap nearest its\n * middle. A `'bar'` drag marks that gap with an insertion bar; a `'slide'`\n * drag slides the other items into the places they would take. Either way\n * the release hands the move to a commit, and nothing is written to the scene.\n */\nimport {\n ActionDisabledReason,\n bodyPredicate,\n type Action,\n type ActionDeps,\n type Contribution,\n type GestureBinding,\n type InvocationCtx,\n type OngoingHandle,\n type OngoingOverlay,\n type TargetPredicate,\n type Vec2,\n} from '@weasel-js/core';\nimport { carriedBy, slideOthers, type Box } from './reorderSlide';\n\n/** The action that drags an item of a sequence to another place in it. */\nexport const REORDER_ACTION_ID = 'diagram.reorder';\n\n/** One item of a sequence, in world units. */\nexport interface ReorderItem {\n /** The scene node drawn for it. */\n id: string;\n bounds: Box;\n /** Where a press picks it up. Default `bounds`; `null` never picks it up, though it keeps its gaps. */\n grip?: Box | null;\n /** The scene nodes that move with it, in either `show` mode. Default `[id]`. */\n carries?: readonly string[];\n}\n\n/** A place an item can land: before `items[index]`, or after the last at `items.length`. */\nexport interface ReorderGap {\n index: number;\n /** The insertion bar's two ends. */\n a: Vec2;\n b: Vec2;\n}\n\n/** A drawn sequence: its items in order along `axis`, and the gaps between them. */\nexport interface ReorderSlots {\n axis: 'x' | 'y';\n items: readonly ReorderItem[];\n gaps: readonly ReorderGap[];\n}\n\n/** The item at index `from` dropped in gap `to`, and every item's id in the order that leaves. */\nexport interface ReorderMove {\n id: string;\n from: number;\n to: number;\n order: readonly string[];\n}\n\n/** Options for {@link createReorderAction}. */\nexport interface ReorderOptions {\n /** Default {@link REORDER_ACTION_ID}. */\n id?: string;\n /** Default 'Reorder'. */\n label?: string;\n /** The sequence a press at `at` picks from, as drawn now, or `null` when there is none. */\n slots: (deps: ActionDeps, at: Vec2) => ReorderSlots | null;\n /** Deps `slots` reads beyond `scene`. */\n requires?: Action['requires'];\n /**\n * `'bar'` (default) carries the item and draws an insertion bar at its\n * gap. `'slide'` carries everything each item `carries` as pose overrides,\n * so what derives from them follows, and slides the others into place; the\n * overrides stay after a commit until the scene next changes.\n */\n show?: 'bar' | 'slide';\n /** Whether a drop may land. The bar draws refused, or nothing slides, where not. Default: every drop. */\n canDrop?: (move: ReorderMove) => boolean;\n /** Called once, on release over a gap that is not the item's own and that `canDrop` allows. */\n commit: (move: ReorderMove, ctx: InvocationCtx) => void;\n}\n\nconst END_GAP = 24;\n\nconst inside = (p: Vec2, b: Box) => p.x >= b.x && p.x <= b.x + b.width && p.y >= b.y && p.y <= b.y + b.height;\n\n/**\n * The slots of items laid out in order along `axis`: a gap halfway between\n * each pair, its bar spanning both across the axis, and one beyond each end,\n * as far out as the nearest interior gap's half, or `END_GAP / 2` with none.\n */\nexport function sequenceSlots(axis: 'x' | 'y', items: readonly ReorderItem[]): ReorderSlots {\n const [along, across, size, depth] = axis === 'x' ? ['x', 'y', 'width', 'height'] as const : ['y', 'x', 'height', 'width'] as const;\n const lo = (b: Box) => b[along];\n const hi = (b: Box) => b[along] + b[size];\n const bar = (at: number, boxes: readonly Box[]): Pick<ReorderGap, 'a' | 'b'> => {\n const from = Math.min(...boxes.map((b) => b[across]));\n const to = Math.max(...boxes.map((b) => b[across] + b[depth]));\n const point = (c: number) => (axis === 'x' ? { x: at, y: c } : { x: c, y: at });\n return { a: point(from), b: point(to) };\n };\n const boxes = items.map((i) => i.bounds);\n const halves = boxes.slice(1).map((b, k) => (lo(b) - hi(boxes[k]!)) / 2);\n const gaps: ReorderGap[] = [];\n if (boxes.length === 0) return { axis, items, gaps };\n gaps.push({ index: 0, ...bar(lo(boxes[0]!) - (halves[0] ?? END_GAP / 2), [boxes[0]!]) });\n for (let k = 1; k < boxes.length; k++) gaps.push({ index: k, ...bar(hi(boxes[k - 1]!) + halves[k - 1]!, [boxes[k - 1]!, boxes[k]!]) });\n const last = boxes[boxes.length - 1]!;\n gaps.push({ index: boxes.length, ...bar(hi(last) + (halves[halves.length - 1] ?? END_GAP / 2), [last]) });\n return { axis, items, gaps };\n}\n\n/** What a drag holds once it has picked an item. */\ninterface Held {\n slots: ReorderSlots;\n from: number;\n item: ReorderItem;\n}\n\nfunction pickAt(slots: ReorderSlots | null, at: Vec2): { from: number; item: ReorderItem } | null {\n const from = slots?.items.findIndex((i) => i.grip !== null && inside(at, i.grip ?? i.bounds)) ?? -1;\n return from < 0 ? null : { from, item: slots!.items[from]! };\n}\n\n/** The gap nearest the carried item's middle, moved `by` along the axis, or\n * `null` for one beside the item, where a drop changes nothing. */\nfunction gapAt(held: Held, by: number): ReorderGap | null {\n const { axis, gaps } = held.slots;\n const size = axis === 'x' ? 'width' : 'height';\n const mid = held.item.bounds[axis] + held.item.bounds[size] / 2 + by;\n let best: ReorderGap | null = null;\n for (const g of gaps) if (best === null || Math.abs(g.a[axis] - mid) < Math.abs(best.a[axis] - mid)) best = g;\n return best === null || best.index === held.from || best.index === held.from + 1 ? null : best;\n}\n\nfunction moveOf(held: Held, gap: ReorderGap): ReorderMove {\n const order = held.slots.items.map((i) => i.id);\n order.splice(held.from, 1);\n order.splice(gap.index > held.from ? gap.index - 1 : gap.index, 0, held.item.id);\n return { id: held.item.id, from: held.from, to: gap.index, order };\n}\n\n/** The `diagram.reorder` action: an ongoing drag carrying one item of a sequence. */\nexport function createReorderAction(opts: ReorderOptions): Action {\n const { canDrop = () => true, show = 'bar' } = opts;\n return {\n id: opts.id ?? REORDER_ACTION_ID,\n label: opts.label ?? 'Reorder',\n group: 'diagram',\n requires: ['scene', ...(opts.requires ?? [])],\n cursor: 'grab',\n activeCursor: 'grabbing',\n enabled: (deps, at) => (deps === undefined || at === undefined || pickAt(opts.slots(deps, at), at) !== null\n ? true\n : ActionDisabledReason.NotApplicable),\n invoker: {\n timing: 'ongoing',\n start(ctx: InvocationCtx): OngoingHandle {\n const start = { x: (ctx.drag?.start ?? ctx.world).x, y: (ctx.drag?.start ?? ctx.world).y };\n const slots = opts.slots(ctx.deps, start);\n const picked = pickAt(slots, start);\n if (slots === null || picked === null) return {};\n const held: Held = { slots, ...picked };\n const { axis } = slots;\n let by = ctx.world[axis] - start[axis];\n let open = true;\n // The overlay is read every frame; ask about each gap once a drag.\n const verdicts = new Map<number, ReorderMove | null>();\n const landing = (gap: ReorderGap | null): ReorderMove | null => {\n if (gap === null) return null;\n if (!verdicts.has(gap.index)) {\n const move = moveOf(held, gap);\n verdicts.set(gap.index, canDrop(move) ? move : null);\n }\n return verdicts.get(gap.index)!;\n };\n const finish = (endCtx: InvocationCtx, reason: 'commit' | 'cancel'): ReorderMove | null => {\n open = false;\n by = endCtx.world[axis] - start[axis];\n const move = reason === 'commit' ? landing(gapAt(held, by)) : null;\n if (move !== null) opts.commit(move, { ...endCtx, deps: ctx.deps });\n return move;\n };\n\n if (show === 'slide') {\n const slide = ctx.deps.scene === undefined ? null : slideOthers(ctx.deps.scene, held.slots, held.item.id);\n return {\n kind: 'diagram-reorder',\n onMove(moveCtx: InvocationCtx): void {\n by = moveCtx.world[axis] - start[axis];\n slide?.show(landing(gapAt(held, by))?.order ?? null, by);\n },\n onEnd(endCtx, reason): void {\n const move = finish(endCtx, reason);\n if (move === null) slide?.drop();\n else slide?.keep();\n },\n };\n }\n\n const carried = carriedBy(held.item);\n const poses = new Map<string, Box>();\n for (const id of carried) {\n const pose = ctx.deps.scene?.get(id as never)?.pose as Box | undefined;\n if (pose !== undefined) poses.set(id, pose);\n }\n return {\n kind: 'diagram-reorder',\n onMove(moveCtx: InvocationCtx): void {\n by = moveCtx.world[axis] - start[axis];\n },\n previewIds: () => (open && poses.size > 0 ? [...poses.keys()] : null),\n previewPose: (id) => {\n const pose = poses.get(id);\n return pose === undefined ? null : { ...pose, [axis]: pose[axis] + by };\n },\n previewOpaqueIds: () => [...carried],\n overlay(): OngoingOverlay | null {\n const gap = open ? gapAt(held, by) : null;\n if (gap === null) return null;\n return { kind: 'polyline', points: [gap.a, gap.b], role: landing(gap) !== null ? 'insert' : 'refused' };\n },\n onEnd(endCtx, reason): void {\n finish(endCtx, reason);\n },\n };\n },\n },\n };\n}\n\n// Matches every press, as a bare drag does, but ranks a step above one, so it\n// is asked before an ambient pan; the action declines off an item's grip.\nexport const ANYWHERE = bodyPredicate(() => true);\n\n/** The binding that starts a reorder: a drag pressed on `on`, by default anywhere; the action declines off an item's grip. */\nexport function reorderBinding(actionId: string = REORDER_ACTION_ID, on: TargetPredicate = ANYWHERE): GestureBinding {\n return { spec: { kind: 'drag', target: { kindOf: on } }, actionId };\n}\n\n/** The reorder action and its binding, to pass as `ambient`. */\nexport function reorderContribution(opts: ReorderOptions & { on?: TargetPredicate }): Contribution {\n const actionId = opts.id ?? REORDER_ACTION_ID;\n return {\n id: `weasel-diagram-reorder:${actionId}`,\n eligibility: { always: true },\n actions: [createReorderAction({ ...opts, id: actionId })],\n bindings: [reorderBinding(actionId, opts.on)],\n };\n}\n","/**\n * DOM pinned to a diagram's nodes and edges: a settings card beside the picked\n * node, a button on an edge's midpoint. Each overlay is placed after every\n * paint, so it follows a pan, a zoom, a resize and a layout run's every frame.\n */\nimport {\n drawnAABBOf,\n drawnBoundsScene,\n effectivePose,\n pointAlongPath,\n type Bounds,\n type NodeId,\n type RectPose,\n type Scene,\n type SceneCanvasApi,\n type View,\n} from '@weasel-js/core';\nimport { useLatest } from '@weasel-js/react';\nimport { placeRect, type Placement } from '@weasel-js/geom';\nimport { useCallback, useLayoutEffect, useRef, type ReactNode, type RefObject } from 'react';\nimport { diagramEdgeOf } from './edgeTrait';\nimport type { DiagramSceneData } from './fromData';\n\n/** One piece of DOM held against a node, a group or an edge. */\nexport interface DiagramOverlay {\n /** The node, group or edge it is held against. While no such id is in the\n * diagram it is not shown. */\n target: string;\n /** Beside the target's box, kept inside the view and flipped to the far\n * side when the near one has no room; or `'center'`, centered on it.\n * Default `'center'`. */\n placement?: Placement | 'center';\n /** Gap between the target's box and the overlay, in CSS pixels. Default 0. */\n offset?: number;\n /** Tells two overlays on one target apart. Default `target`. */\n key?: string;\n content: ReactNode;\n}\n\ntype DiagramScene = Scene<DiagramSceneData, 'main', RectPose>;\n\n/** Where `id` is drawn, in world units: a node's or group's box, or for an\n * edge an empty rect at the midpoint along its route. `null` when the scene\n * has no such node. */\nexport function worldRectOf(scene: DiagramScene, id: string): Bounds | null {\n const node = scene.get(id as NodeId);\n if (node === undefined) return null;\n const drawn = drawnBoundsScene(scene);\n const route = diagramEdgeOf(node) === null ? null : drawn.derivedPathOf?.(id as NodeId) ?? null;\n const mid = route === null ? null : pointAlongPath(route, 0.5);\n if (mid != null) return { x: mid.point.x, y: mid.point.y, width: 0, height: 0 };\n return drawnAABBOf(drawn, id as NodeId, effectivePose(scene, node), { includeStroke: false });\n}\n\n/** `rect` in CSS pixels from the canvas's top-left, through `view`. */\nexport function screenRectOf(rect: Bounds, view: View): Bounds {\n return {\n x: (rect.x - view.x) * view.scale.x,\n y: (rect.y - view.y) * view.scale.y,\n width: rect.width * view.scale.x,\n height: rect.height * view.scale.y,\n };\n}\n\nconst CENTER = 'center';\n\n/** Place `el` against `anchor` inside a `width` × `height` view. */\nfunction place(el: HTMLElement, overlay: DiagramOverlay, anchor: Bounds, width: number, height: number): void {\n const size = { width: el.offsetWidth, height: el.offsetHeight };\n const placement = overlay.placement ?? CENTER;\n const at = placement === CENTER\n ? { x: anchor.x + (anchor.width - size.width) / 2, y: anchor.y + (anchor.height - size.height) / 2 }\n : placeRect({\n anchor, overlay: size, boundary: { x: 0, y: 0, width, height }, placement, offset: overlay.offset ?? 0,\n }).rect;\n el.style.transform = `translate(${Math.round(at.x)}px, ${Math.round(at.y)}px)`;\n}\n\n/**\n * The overlays' elements, placed after every paint and whenever one of them\n * changes size. The returned ref function takes each overlay's element by key.\n */\nexport function useOverlayPlacement(\n canvasRef: RefObject<SceneCanvasApi | null>,\n scene: DiagramScene,\n overlays: readonly DiagramOverlay[],\n): (key: string) => (el: HTMLElement | null) => void {\n const elements = useRef(new Map<string, HTMLElement>());\n const current = useLatest(overlays);\n\n const placeAll = useCallback(() => {\n const canvas = canvasRef.current;\n const surface = canvas?.element;\n if (canvas == null || surface == null) return;\n const view = canvas.getView();\n for (const overlay of current.current) {\n const el = elements.current.get(overlay.key ?? overlay.target);\n if (el === undefined) continue;\n const world = worldRectOf(scene, overlay.target);\n el.hidden = world === null;\n if (world === null) continue;\n const rect = screenRectOf(world, view);\n const anchor = { ...rect, x: rect.x + surface.offsetLeft, y: rect.y + surface.offsetTop };\n place(el, overlay, anchor, surface.offsetWidth, surface.offsetHeight);\n }\n }, [canvasRef, scene, current]);\n\n useLayoutEffect(() => {\n placeAll();\n const canvas = canvasRef.current;\n if (canvas == null) return;\n const stop = canvas.subscribeFrame(placeAll);\n const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(placeAll);\n for (const el of elements.current.values()) observer?.observe(el);\n return () => {\n stop();\n observer?.disconnect();\n };\n }, [canvasRef, placeAll, overlays]);\n\n const refs = useRef(new Map<string, (el: HTMLElement | null) => void>());\n return useCallback((key: string) => {\n let ref = refs.current.get(key);\n if (ref === undefined) {\n ref = (el) => {\n if (el !== null) {\n elements.current.set(key, el);\n return;\n }\n elements.current.delete(key);\n refs.current.delete(key);\n };\n refs.current.set(key, ref);\n }\n return ref;\n }, []);\n}\n","/**\n * Which members a reorderable group holds, and what moves with each. Plain\n * reads of the scene; `groupReorder.ts` builds a reorder's slots from them.\n */\nimport type { Bounds } from '@weasel-js/core';\nimport { diagramAnchorOf, diagramGroupOf } from './group';\nimport { diagramLabelOf } from './labelTrait';\n\n/** The scene reads a reorder makes. */\nexport interface ReorderScene {\n get(id: string): { id: string; data: unknown; dependsOn?: unknown } | undefined;\n renderOrderNodes(): Iterable<{ id: string; data: unknown; dependsOn?: unknown }>;\n /** A container's children, which a reorder carries with it. Absent, every node is a leaf. */\n childrenOf?(id: string): readonly string[];\n}\n\n/** A group whose members are carried along one axis, and the member a press picked up. */\nexport interface ReorderTarget {\n group: string;\n axis: 'x' | 'y';\n member: string;\n /** The group's members, in the order they stand along the axis. */\n members: readonly string[];\n}\n\nconst depsOf = (node: { dependsOn?: unknown } | undefined): string[] =>\n Array.isArray(node?.dependsOn) ? (node.dependsOn as string[]) : [];\n\n/** The group box directly holding each node or group. A wire label a box takes in is not one of its members. */\nfunction holders(scene: ReorderScene): Map<string, string> {\n const out = new Map<string, string>();\n for (const node of scene.renderOrderNodes()) {\n if (diagramGroupOf(node) === null) continue;\n for (const dep of depsOf(node)) {\n const member = scene.get(dep);\n if (member !== undefined && diagramLabelOf(member) === null) out.set(dep, node.id);\n }\n }\n return out;\n}\n\n/** The members of group `group`, the way {@link holders} counts them. */\nfunction membersOf(scene: ReorderScene, group: string): string[] {\n return depsOf(scene.get(group)).filter((id) => {\n const node = scene.get(id);\n return node !== undefined && diagramLabelOf(node) === null;\n });\n}\n\n/**\n * The reorderable group a press on `id` carries a member of: the nearest\n * group above `id` with `reorder` set, and its member on the way up — `id`\n * itself, or the group holding it. `null` when no group above it reorders.\n */\nexport function reorderTargetOf(\n scene: ReorderScene,\n id: string,\n boxOf: (id: string) => Bounds | null,\n): ReorderTarget | null {\n const held = holders(scene);\n for (let member = id, group = held.get(id); group !== undefined; member = group, group = held.get(group)) {\n const axis = diagramGroupOf(scene.get(group)!)?.reorder;\n if (axis === undefined) continue;\n const start = (m: string) => {\n const box = boxOf(m);\n return box === null ? 0 : axis === 'x' ? box.x : box.y;\n };\n const members = membersOf(scene, group).sort((a, b) => start(a) - start(b));\n return { group, axis, member, members };\n }\n return null;\n}\n\n/** `member` and everything drawn with it: a group's members and the labels it\n * takes in, all the way down, every container's children, and every node\n * anchored to any of those. */\nexport function carriedWith(scene: ReorderScene, member: string): Set<string> {\n const out = new Set<string>();\n const visit = (id: string) => {\n if (out.has(id)) return;\n out.add(id);\n const node = scene.get(id);\n if (node !== undefined && diagramGroupOf(node) !== null) depsOf(node).forEach(visit);\n scene.childrenOf?.(id).forEach(visit);\n };\n visit(member);\n for (const node of scene.renderOrderNodes()) {\n const on = depsOf(node)[0];\n if (on !== undefined && out.has(on) && diagramAnchorOf(node) !== null) out.add(node.id);\n }\n return out;\n}\n","/**\n * Reordering a group marked `reorder`: a member dragged along that axis among\n * its siblings, which slide into the places they would take, or the selected\n * one stepped with Alt and an arrow key. Nothing is written: the host hears\n * the new order, writes it to its data, and layout keeps it.\n */\nimport {\n ActionDisabledReason,\n bodyPredicate,\n type Action,\n type ActionDeps,\n type Contribution,\n type RectPose,\n type Scene,\n type Vec2,\n} from '@weasel-js/core';\nimport { worldRectOf } from './overlays';\nimport type { DiagramSceneData } from './fromData';\nimport { reorderContribution, sequenceSlots, type ReorderSlots } from './reorder';\nimport { carriedWith, reorderTargetOf, type ReorderTarget } from './reorderModel';\n\n/** Alt and an arrow key: the selected member one place along. */\nexport const STEP_REORDER_ACTION_ID = 'diagram.stepReorder';\n\n/** A reorderable group's members in their new order. */\nexport interface ReorderChange {\n group: string;\n order: readonly string[];\n}\n\ntype DiagramScene = Scene<DiagramSceneData, 'main', RectPose>;\n\nconst sceneOf = (deps: ActionDeps | undefined) => deps?.scene as DiagramScene | undefined;\n\nfunction targetAt(deps: ActionDeps | undefined, id: string | null | undefined): ReorderTarget | null {\n const scene = sceneOf(deps);\n if (scene === undefined || id == null) return null;\n return reorderTargetOf(scene as never, id, (m) => worldRectOf(scene, m));\n}\n\n/** The members of the reorderable group a press at `at` carries one of, each\n * with everything drawn with it, or `null` off any such group. */\nexport function groupReorderSlots(deps: ActionDeps, at: Vec2): ReorderSlots | null {\n const scene = sceneOf(deps);\n const target = targetAt(deps, deps.nodeAtPoint?.(at));\n if (scene === undefined || target === null) return null;\n return sequenceSlots(target.axis, target.members.map((m) => ({\n id: m,\n bounds: worldRectOf(scene, m) ?? { x: 0, y: 0, width: 0, height: 0 },\n carries: [...carriedWith(scene as never, m)],\n })));\n}\n\nconst STEPS: readonly { key: string; axis: 'x' | 'y'; step: -1 | 1 }[] = [\n { key: 'ArrowUp', axis: 'y', step: -1 },\n { key: 'ArrowDown', axis: 'y', step: 1 },\n { key: 'ArrowLeft', axis: 'x', step: -1 },\n { key: 'ArrowRight', axis: 'x', step: 1 },\n];\n\n/** Steps the selected node's member one place toward the start (`-1`) or the end (`1`). */\nexport function createStepReorderAction(report: (change: ReorderChange) => void): Action {\n const selectedTarget = (deps: ActionDeps | undefined) => targetAt(deps, deps?.selection?.get()[0]);\n return {\n id: STEP_REORDER_ACTION_ID,\n label: 'Move along',\n group: 'diagram',\n defaultBinding: STEPS.map(({ key, axis, step }) => ({\n spec: { kind: 'key' as const, key, mods: { alt: true } },\n opts: { params: { axis, step } },\n })),\n requires: ['scene', 'selection'],\n invoker: {\n timing: 'immediate',\n run(deps, params) {\n const target = selectedTarget(deps);\n if (target === null || params?.axis !== target.axis) return;\n const { members, member } = target;\n const at = members.indexOf(member);\n const to = at + (params.step === -1 ? -1 : 1);\n if (to < 0 || to >= members.length) return;\n const order = [...members];\n order.splice(at, 1);\n order.splice(to, 0, member);\n report({ group: target.group, order });\n },\n },\n enabled: (deps) => (selectedTarget(deps) !== null ? true : ActionDisabledReason.NotApplicable),\n };\n}\n\nconst onBody = bodyPredicate((target) => target === 'selected-body' || target === 'unselected-body');\n\n/** Everything `DiagramView` installs for `onReorder`: the reorder drag,\n * sliding, pressed on a node's body, and the step action. */\nexport function groupReorderContribution(report: (change: ReorderChange) => void): Contribution {\n const drag = reorderContribution({\n slots: groupReorderSlots,\n requires: ['nodeAtPoint'],\n show: 'slide',\n on: onBody,\n commit: (move, ctx) => {\n const group = targetAt(ctx.deps, move.id)?.group;\n if (group !== undefined) report({ group, order: move.order });\n },\n });\n return { ...drag, id: 'weasel-diagram-reorder', actions: [...(drag.actions ?? []), createStepReorderAction(report)] };\n}\n","/**\n * Label placement for a data-backed diagram: the specs `diagramScene` builds,\n * with each edge label moved off whatever covers it. Placement derives from\n * the specs, so it lives in them and is never reported back to the host.\n */\nimport type { DerivedDep, RectPose } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { diagramContainerOf } from '../containers/trait';\nimport { edgeRouter } from '../edge';\nimport { diagramEdgeOf } from '../edgeTrait';\nimport type { DiagramSpec } from '../fromData';\nimport { diagramGroupOf } from '../group';\nimport { diagramLabelOf, type DiagramLabel } from '../labelTrait';\nimport { diagramNodeOf } from '../trait';\nimport { placeLabels, type LabelPlacements, type PlaceLabel, type PlaceLabelsInput, type PlaceLabelsOptions, type PlaceRoute } from './place';\n\nconst routeOf = edgeRouter<RectPose>();\n\n/** What placement reads off `specs`: every label moving. */\nfunction inputOf(specs: readonly DiagramSpec[]): PlaceLabelsInput {\n const byId = new Map(specs.map((s) => [s.id as string, s]));\n const dep = (id: unknown): DerivedDep<RectPose> | undefined => {\n const s = byId.get(id as string);\n return s === undefined ? undefined : { node: { ...s, parent: null } as never, pose: s.pose, path: null };\n };\n const shapes: PlaceLabelsInput['shapes'][number][] = [];\n const routes: PlaceRoute[] = [];\n const labels: PlaceLabel[] = [];\n for (const spec of specs) {\n const id = spec.id as string;\n const ends = Array.isArray(spec.dependsOn) ? spec.dependsOn : [];\n if (diagramEdgeOf(spec) !== null) {\n const points = routeOf(spec, ends.map(dep))?.points;\n if (points !== undefined && points.length >= 2) routes.push({ id, points: points as Vec2[] });\n continue;\n }\n const placement = diagramLabelOf(spec);\n if (placement !== null) {\n const { width, height } = spec.pose;\n if (ends[0] !== undefined) labels.push({ id, edge: ends[0] as string, placement, size: { width, height } });\n continue;\n }\n const node = { id, kind: spec.kind, data: spec.data };\n if (spec.derivePose !== undefined || diagramContainerOf(node) !== null || diagramGroupOf(node) !== null || diagramNodeOf(node) === null) continue;\n shapes.push({ id, box: spec.pose });\n }\n return { shapes, routes, labels };\n}\n\nconst keyOf = (input: PlaceLabelsInput): string => JSON.stringify([\n input.shapes.map((s) => [s.id, s.box.x, s.box.y, s.box.width, s.box.height]),\n input.routes.map((r) => [r.id, r.points.flatMap((p) => [p.x, p.y])]),\n input.labels.map((l) => [l.id, l.edge, l.placement.at, l.placement.offset, l.placement.dodge, l.size.width, l.size.height]),\n]);\n\n/**\n * A function from specs to the same specs with each edge label placed off\n * whatever covers it. Every label is placed afresh, in id order, whenever\n * the shapes, routes, or labels change, and the last answer is reused while\n * they do not. Run it after any router, so labels dodge the routes drawn.\n */\nexport function createSpecLabelPlacer(opts: PlaceLabelsOptions = {}): (specs: readonly DiagramSpec[]) => DiagramSpec[] {\n let last: { key: string; placed: LabelPlacements } | null = null;\n return (specs) => {\n const input = inputOf(specs);\n if (input.labels.length === 0) return [...specs];\n const key = keyOf(input);\n if (last?.key !== key) last = { key, placed: placeLabels(input, opts) };\n const placed = last.placed;\n return specs.map((spec) => {\n const spot = placed.get(spec.id as string);\n const label = diagramLabelOf(spec);\n if (spot === undefined || label === null) return spec;\n const { placed: _p, ...preferred } = label;\n const next: DiagramLabel = spot === null ? preferred : { ...preferred, placed: spot };\n return { ...spec, data: { ...spec.data, diagram: { ...(spec.data.diagram as object), label: next } } };\n });\n };\n}\n","import { diagramContainerOf } from './containers/trait';\nimport { diagramEdgeOf } from './edgeTrait';\nimport { diagramGroupOf } from './group';\nimport { diagramLabelOf } from './labelTrait';\n\n/**\n * `<SceneCanvas selectTool={{ resize: { resizable } }}>` for a diagram scene:\n * edges and edge labels take their geometry from what they are attached to,\n * so their own pose is a placeholder, and a resize handle on it sits at the\n * origin and resizes nothing. A group's box is its members' union, and a\n * pool's lane is sized by its pool's stack and resized by dragging its\n * boundary.\n */\nexport function diagramResizable(scene: { get(id: never): { data: unknown } | undefined }): (id: string) => boolean {\n return (id) => {\n const node = scene.get(id as never);\n return node === undefined\n || (diagramEdgeOf(node) === null && diagramLabelOf(node) === null && diagramGroupOf(node) === null\n && diagramContainerOf(node)?.role !== 'lane');\n };\n}\n","/**\n * The edge half of writing a layout to a scene: each edge's waypoints, and\n * where its label sits among them.\n *\n * Layout writes only what it owns. An edge's route is its own while the edge\n * has no waypoints or still has the ones layout last wrote (`laidOut`), and\n * is not an `avoid` connector, which only gets its ports named; a\n * label's place is its own while the label sits at the default middle or at a\n * `{ near }`, and its edge's route is layout's.\n */\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { diagramEdgeOf, layoutOwnsPort, layoutWritesRoute, type DiagramEdge, type EdgeEnd } from './edgeTrait';\nimport { labelFollowsLayout, type Graph } from './graph';\nimport { diagramLabelOf, type DiagramLabel } from './labelTrait';\nimport type { LayoutPlan, LayoutPorts } from './layout';\n\n/** Edge routes for `applyLayout` to write alongside a layout's moves. */\nexport interface LayoutRoutes {\n /** Every edge the layout laid out. Each one layout owns gets its route\n * from `waypoints`, or loses the one a layout gave it before. */\n edges: ReadonlySet<string>;\n waypoints: ReadonlyMap<string, readonly Vec2[]>;\n labels?: ReadonlyMap<string, Vec2>;\n /** The ports layout names. Each end layout owns gets its port from here,\n * or loses the one a layout named before. */\n ports?: ReadonlyMap<string, LayoutPorts>;\n}\n\n/** How far a route may sit from the one already written and still count as\n * it, in world units: a re-run's translation can land an ulp off. */\nconst ROUTE_TOLERANCE = 1e-3;\n\n/** The routes `plan` laid out for `graph`'s edges. A layout that routes\n * nothing routes every edge straight, taking back what `layered` wrote. */\nexport function routesOf(graph: Graph, plan: LayoutPlan): LayoutRoutes {\n return {\n edges: new Set(graph.edges.map((e) => e.origin?.id ?? e.id)),\n waypoints: plan.waypoints ?? new Map(),\n ...(plan.labels !== undefined ? { labels: plan.labels } : {}),\n ...(plan.ports !== undefined ? { ports: plan.ports } : {}),\n };\n}\n\n/** A scene as {@link routeWrites} reads it. */\nexport interface RoutedScene {\n get(id: never): { data: unknown } | undefined;\n isLocked(id: never): boolean;\n renderOrderNodes(): readonly { id: string; data: unknown; dependsOn?: readonly string[] | 'children' }[];\n}\n\n/** The new `data` for every edge and label whose route or place changes. A\n * locked edge or label is left as it is. */\nexport function routeWrites(scene: RoutedScene, routes: LayoutRoutes): Map<string, unknown> {\n const out = new Map<string, unknown>();\n const owned = new Set<string>();\n for (const id of routes.edges) {\n const node = scene.get(id as never);\n const edge = node === undefined ? null : diagramEdgeOf(node);\n if (node === undefined || edge === null || scene.isLocked(id as never)) {\n if (edge !== null && layoutWritesRoute(edge)) owned.add(id);\n continue;\n }\n let next = edge;\n if (layoutWritesRoute(edge)) {\n owned.add(id);\n next = rerouted(edge, routes.waypoints.get(id));\n }\n const ports = routes.ports?.get(id);\n const from = renamed(edge.from, ports?.from);\n const to = renamed(edge.to, ports?.to);\n if (from !== edge.from || to !== edge.to) next = { ...next, from, to };\n if (next !== edge) out.set(id, withTrait(node.data, next));\n }\n // The first label on an edge is the one `buildGraph` left room for.\n const stationed = new Set<string>();\n for (const node of scene.renderOrderNodes()) {\n const label = diagramLabelOf(node);\n const deps = node.dependsOn;\n if (label === null || !Array.isArray(deps) || deps.length !== 1 || !owned.has(deps[0]!)) continue;\n if (!labelFollowsLayout(label.at) || stationed.has(deps[0]!)) continue;\n stationed.add(deps[0]!);\n const near = routes.labels?.get(deps[0]!);\n const at: DiagramLabel['at'] = near === undefined ? 'mid' : { near };\n if (sameAt(label.at, at) || scene.isLocked(node.id as never)) continue;\n out.set(node.id, withTrait(node.data, { ...label, at }, 'label'));\n }\n return out;\n}\n\n/** `edge` on the route layout gave it, or `edge` itself when that changes\n * nothing. No route clears the one layout wrote before. */\nfunction rerouted(edge: DiagramEdge, route: readonly Vec2[] | undefined): DiagramEdge {\n if (route === undefined || route.length === 0) {\n if ((edge.waypoints ?? []).length === 0 && edge.laidOut === undefined) return edge;\n const { waypoints: _w, laidOut: _l, ...rest } = edge;\n return rest;\n }\n if (edge.waypoints !== undefined && near(edge.waypoints, route)) return edge;\n return { ...edge, waypoints: route, laidOut: route };\n}\n\n/** `end` with the port layout names for it, or `end` itself when layout does\n * not own it or names what it already has. */\nfunction renamed(end: EdgeEnd, port: string | undefined): EdgeEnd {\n if (!layoutOwnsPort(end) || (end.port === port && (port === undefined || end.laidOut === port))) return end;\n const { port: _p, laidOut: _l, ...rest } = end;\n return port === undefined ? rest : { ...rest, port, laidOut: port };\n}\n\nfunction near(a: readonly Vec2[], b: readonly Vec2[]): boolean {\n return a.length === b.length\n && a.every((p, i) => Math.abs(p.x - b[i]!.x) <= ROUTE_TOLERANCE && Math.abs(p.y - b[i]!.y) <= ROUTE_TOLERANCE);\n}\n\nfunction sameAt(a: DiagramLabel['at'], b: DiagramLabel['at']): boolean {\n if (typeof a === 'object' && typeof b === 'object') return near([a.near], [b.near]);\n return a === b;\n}\n\n/** `data` with its diagram trait, or one key of it, replaced. */\nfunction withTrait(data: unknown, value: unknown, key?: string): unknown {\n const own = data as { diagram: Record<string, unknown> };\n const diagram = key === undefined ? value : { ...own.diagram, [key]: value };\n return { ...own, diagram };\n}\n","/**\n * Running a layout against a scene: `LAYOUTS`, one batch of pose writes, and\n * the action that reaches both. A layout is a pure function of the graph;\n * `applyLayout` is the only thing that touches a scene.\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 { chain } from './chain';\nimport { layered } from './layered';\nimport { tree } from './tree';\nimport { planOf, type LayoutFn, type LayoutOptions, type LayoutResult } from './layout';\nimport { routeWrites, routesOf, type LayoutRoutes } from './routeWrites';\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 chain,\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 /** Edge routes to write in the same batch, from `routesOf`. */\n routes?: LayoutRoutes;\n}\n\n/**\n * Write a layout's answer to the scene, as one undoable batch.\n *\n * Returns how many nodes moved. A layout with nothing to do, nodes or routes,\n * writes nothing and pushes no history entry.\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.\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 const data = opts.routes === undefined ? new Map<string, unknown>() : routeWrites(scene as never, opts.routes);\n if (poses.size === 0 && data.size === 0) return 0;\n // A node on a locked layer stays put, as it does under a live run.\n const open = [...poses].filter(([id]) => !scene.isLocked(id as never));\n if (open.length === 0 && data.size === 0) return 0;\n scene.batch(opts.label ?? 'Layout', () => {\n for (const [id, pose] of open) scene.setPose(id as never, pose);\n for (const [id, d] of data) scene.update(id as never, { data: d });\n });\n // Participants, not the descendants they carried along: a caller asking how\n // much a layout did means the nodes it placed.\n const wrote = new Set(open.map(([id]) => id));\n let moved = 0;\n for (const id of result.keys()) if (wrote.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 * The translation is measured from the node's document pose, which a live run\n * in flight never changes, so a frame's answer does not depend on the frame\n * 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 */\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 const plan = planOf(algorithm, graph, opts.layout);\n applyLayout(scene, plan.moves, {\n ...(opts.geometry ? { geometry: opts.geometry } : {}),\n ...(opts.label ? { label: opts.label } : {}),\n routes: routesOf(graph, plan),\n });\n },\n },\n enabled: () => true as const,\n };\n}\n","/**\n * A live layout's producers: what each frame of a run says about where the\n * participants are. `forceProducer` relaxes; `easedProducer` walks to a\n * destination it knows. `useLiveLayout` (`live.ts`) runs them.\n */\nimport {\n AUTO_POSE_DESCRIPTOR,\n type NodeId,\n type PoseDescriptor,\n} from '@weasel-js/core';\nimport { type EasingFn } from '@weasel-js/animator';\nimport { forceRelaxation, type ForceOptions } from './force';\nimport type { Graph } from './graph';\nimport { center, type LayoutFn, type LayoutOptions, type LayoutResult } from './layout';\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. */\nexport const 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. */\nexport const easeInOut: EasingFn = (t) => (t < 0.5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2);\n\n/** How far along an eased run is at `frame`, before and after its easing. */\nexport function progress(frame: number, frames: number, easing: EasingFn): { t: number; u: number } {\n const t = Math.min((frame + 1) / frames, 1);\n return { t, u: easing(t) };\n}\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, so it finishes on whichever comes\n * first: `restTicks` ticks in a row with no node moving `restDistance`, or the\n * cooling schedule running out. Nothing rests while a node is held.\n *\n * It does **not** re-anchor the way the one-shot `force` does. Re-anchoring\n * per frame would fight a drag: the anchor is measured from where the nodes\n * 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, u } = progress(frame, frames, easing);\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 * The wait before a live run whose layout answers later: a `LayoutPlanner`\n * that returns a promise.\n *\n * Only the newest request is answered, and only while the graph it was asked\n * about is still the one on screen. A drag, an edit, or a node added while the\n * answer was on its way makes the plan describe somewhere the diagram no\n * longer is, so the answer is dropped and the run never starts.\n */\nimport { useEffect, useMemo, useRef } from 'react';\nimport type { Graph } from './graph';\nimport type { LayoutPlan } from './layout';\n\n/** The shape of a graph, as a string that changes when a node or edge does. */\nexport function 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/** Whether `b` is `a` again: the same nodes and edges, every node in the same box. */\nexport function sameGraph(a: Graph, b: Graph): boolean {\n if (shapeOf(a) !== shapeOf(b)) return false;\n return a.nodes.every((n) => {\n const m = b.node(n.id)?.bounds;\n const k = n.bounds;\n return m !== undefined && m.x === k.x && m.y === k.y && m.width === k.width && m.height === k.height;\n });\n}\n\n/** A live run's outstanding request for a plan. Stable for the life of the\n * component; unmounting drops whatever is pending. */\nexport interface PendingPlan {\n /** Hand `ready` the plan once it arrives, or `failed` the reason it never\n * will, unless another request or a `drop` comes first; a superseded\n * request's failure is dropped with its answer. */\n request(answer: Promise<LayoutPlan>, ready: (plan: LayoutPlan) => void, failed: (error: unknown) => void): void;\n /** Forget the outstanding request. */\n drop(): void;\n isWaiting(): boolean;\n}\n\nexport function usePendingPlan(): PendingPlan {\n const generation = useRef(0);\n const waiting = useRef(false);\n const pending = useMemo<PendingPlan>(() => ({\n request(answer, ready, failed) {\n const mine = ++generation.current;\n waiting.current = true;\n const current = () => generation.current === mine;\n void answer.then(\n (plan) => {\n if (!current()) return;\n waiting.current = false;\n ready(plan);\n },\n (error: unknown) => {\n if (!current()) return;\n waiting.current = false;\n failed(error);\n },\n );\n },\n drop() {\n generation.current++;\n waiting.current = false;\n },\n isWaiting: () => waiting.current,\n }), []);\n useEffect(() => () => pending.drop(), [pending]);\n return pending;\n}\n","/**\n * The edge half of a live layout: each route the run will rewrite, eased from\n * where it ran to where the run puts it, frame by frame, alongside the nodes,\n * and drawn through the ports the run will name for its ends.\n *\n * Nothing here writes the document. A frame's route is published as the edge's\n * path on the scene's override channel, drawn by the edge's own `derivePath`\n * through the frame's waypoints and the poses its ends are drawn at; the\n * routes themselves are written once, when the run arrives (`routeWrites`).\n */\nimport { useEffect, useMemo, useRef } from 'react';\nimport {\n AUTO_POSE_DESCRIPTOR,\n derivedDepOf,\n type DerivedDep,\n type PoseDescriptor,\n type NodeId,\n type Path,\n type PoseOverride,\n type Scene,\n} from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { diagramEdgeOf, layoutWritesRoute, type DiagramEdge } from './edgeTrait';\nimport type { Graph } from './graph';\nimport { routeWrites, type LayoutRoutes } from './routeWrites';\n\n/** One route on its way from where it ran to where layout puts it. */\nexport interface RouteEasing {\n id: string;\n /** Point `k` of the route eases from `from[k]` to `to[k]`. */\n from: readonly Vec2[];\n /** As long as `from`, or `null` for a route layout takes away: it eases\n * onto the straight line between its ends' centers where each frame draws\n * them, and arrives with no waypoints at all. */\n to: readonly Vec2[] | null;\n /** The edge's ends as the run will write them, ports and all. */\n ends: Pick<DiagramEdge, 'from' | 'to'>;\n}\n\nconst lerp = (a: Vec2, b: Vec2, u: number): Vec2 => ({ x: a.x + (b.x - a.x) * u, y: a.y + (b.y - a.y) * u });\n\n/** The point `s` of the way along the polyline through `points`, 0 to 1. */\nfunction along(points: readonly Vec2[], s: number): Vec2 {\n if (points.length === 1) return points[0]!;\n const lengths = points.slice(1).map((p, i) => Math.hypot(p.x - points[i]!.x, p.y - points[i]!.y));\n const total = lengths.reduce((a, b) => a + b, 0);\n let left = s * total;\n for (const [i, len] of lengths.entries()) {\n if (left <= len || i === lengths.length - 1) return lerp(points[i]!, points[i + 1]!, len === 0 ? 0 : Math.min(left / len, 1));\n left -= len;\n }\n return points[points.length - 1]!;\n}\n\n/** `count` points spread evenly along the straight line from `start` to\n * `end`, its ends left off. */\nconst straightRun = (count: number, start: Vec2, end: Vec2): Vec2[] =>\n Array.from({ length: count }, (_, k) => lerp(start, end, (k + 1) / (count + 1)));\n\n/** `points` as `count` points spread along the same run, its ends kept. A\n * run of none is the straight line from `start` to `end`. */\nfunction respread(points: readonly Vec2[], count: number, start: Vec2, end: Vec2): Vec2[] {\n if (points.length === count) return [...points];\n if (points.length === 0) return straightRun(count, start, end);\n return Array.from({ length: count }, (_, k) => along(points, count === 1 ? 0.5 : k / (count - 1)));\n}\n\n/**\n * The routes a run eases: every edge `routes` lays out that the run will\n * rewrite, whether its route or the ports its ends name. A route gaining\n * waypoints starts on the straight line between its ends' centers; one losing\n * them ends there.\n */\nexport function routeEasings<TPose>(\n scene: Scene<unknown, string, TPose>,\n graph: Graph,\n routes: LayoutRoutes,\n): RouteEasing[] {\n const centerOf = (id: string): Vec2 | null => {\n const ids = graph.node(id) !== undefined ? [id] : graph.groups?.find((g) => g.id === id)?.members ?? [];\n const boxes = ids.flatMap((m) => graph.node(m)?.bounds ?? []);\n if (boxes.length === 0) return null;\n const x0 = Math.min(...boxes.map((b) => b.x));\n const y0 = Math.min(...boxes.map((b) => b.y));\n const x1 = Math.max(...boxes.map((b) => b.x + b.width));\n const y1 = Math.max(...boxes.map((b) => b.y + b.height));\n return { x: (x0 + x1) / 2, y: (y0 + y1) / 2 };\n };\n const writes = routeWrites(scene as never, routes);\n const out: RouteEasing[] = [];\n for (const id of routes.edges) {\n const node = scene.get(id as NodeId);\n const edge = node === undefined ? null : diagramEdgeOf(node);\n const written = writes.get(id);\n if (node === undefined || edge === null || written === undefined) continue;\n const next = diagramEdgeOf({ data: written });\n if (next === null) continue;\n const ends = { from: next.from, to: next.to };\n const was = edge.waypoints ?? [];\n if (!layoutWritesRoute(edge)) {\n out.push({ id, from: was, to: was, ends });\n continue;\n }\n const after = routes.waypoints.get(id) ?? [];\n if (after.length === 0) {\n out.push({ id, from: was, to: null, ends });\n continue;\n }\n const deps = Array.isArray(node.dependsOn) ? node.dependsOn : [];\n const [a, b] = deps.length === 2 ? [centerOf(deps[0]!), centerOf(deps[1]!)] : [null, null];\n if (a === null || b === null) continue;\n const count = Math.max(was.length, after.length);\n out.push({ id, from: respread(was, count, a, b), to: respread(after, count, a, b), ends });\n }\n return out;\n}\n\n/**\n * Each eased route's path `u` of the way there, drawn by the edge's own\n * `derivePath` with its ends where `poseOf` puts them. A node `poseOf` does\n * not place is drawn where the scene shows it, unless it derives its pose —\n * a group's box — when it is derived afresh from where this frame puts what\n * it depends on. An edge that derives no path is left out.\n */\nexport function easedPaths<TPose>(\n scene: Scene<unknown, string, TPose>,\n easings: readonly RouteEasing[],\n u: number,\n poseOf: (id: string) => TPose | undefined,\n geometry: PoseDescriptor<TPose> = AUTO_POSE_DESCRIPTOR as PoseDescriptor<TPose>,\n): Map<string, Path> {\n const depOf = frameDeps(scene, poseOf);\n const centerOf = (dep: DerivedDep<TPose>): Vec2 => {\n const b = geometry.getBounds(dep.pose);\n return { x: b.x + b.width / 2, y: b.y + b.height / 2 };\n };\n const out = new Map<string, Path>();\n for (const { id, from, to, ends } of easings) {\n const node = scene.get(id as NodeId);\n if (node?.derivePath === undefined || !Array.isArray(node.dependsOn)) continue;\n const deps = node.dependsOn.map(depOf);\n let target = to;\n if (target === null) {\n const [a, b] = deps;\n target = u >= 1 || a === undefined || b === undefined ? [] : straightRun(from.length, centerOf(a), centerOf(b));\n }\n const waypoints = target.length === 0 && u >= 1 ? [] : from.map((p, k) => lerp(p, target[k]!, u));\n const data = node.data as { diagram: object };\n const diagram = { ...data.diagram, ...ends, waypoints };\n const path = node.derivePath({ ...node, data: { ...data, diagram } } as never, deps);\n if (path !== null) out.set(id, path);\n }\n return out;\n}\n\n/** Each node as this frame draws it: where `poseOf` puts it, else derived from\n * where this frame puts its dependencies, else where the scene shows it. */\nfunction frameDeps<TPose>(\n scene: Scene<unknown, string, TPose>,\n poseOf: (id: string) => TPose | undefined,\n): (id: string) => DerivedDep<TPose> | undefined {\n const memo = new Map<string, DerivedDep<TPose> | undefined>();\n const depOf = (id: string): DerivedDep<TPose> | undefined => {\n if (memo.has(id)) return memo.get(id);\n // Closes a cycle at the scene's answer rather than recursing forever.\n memo.set(id, derivedDepOf(scene, id as NodeId));\n const shown = memo.get(id);\n if (shown === undefined) return undefined;\n const pose = poseOf(id) ?? derivedFromFrame(scene, shown, depOf) ?? shown.pose;\n const dep: DerivedDep<TPose> = { node: shown.node, pose, get path() { return shown.path; } };\n memo.set(id, dep);\n return dep;\n };\n return depOf;\n}\n\n/** `shown`'s pose derived from where this frame draws its dependencies, or\n * `undefined` when it derives none or something else holds it this frame. */\nfunction derivedFromFrame<TPose>(\n scene: Scene<unknown, string, TPose>,\n shown: DerivedDep<TPose>,\n depOf: (id: string) => DerivedDep<TPose> | undefined,\n): TPose | undefined {\n const { node } = shown;\n if (node.derivePose === undefined || scene.overrides.read(node.id)?.pose !== undefined) return undefined;\n const ids = node.dependsOn === 'children' ? scene.childrenOf(node.id) : node.dependsOn ?? [];\n if (ids.length === 0) return undefined;\n return node.derivePose(node as never, ids.map(depOf)) ?? undefined;\n}\n\n/** A claim on some edges' paths in the override channel. */\nexport interface PathHold {\n /** Show these paths, and stop showing any other this hold showed. */\n show(paths: ReadonlyMap<string, Path>): void;\n /** Stop showing every path this hold shows. An entry another writer has\n * since replaced is left alone. */\n drop(): void;\n}\n\n/** A {@link PathHold} on `scene`'s override channel. Its writes are published\n * with the next `commit` of the channel, which the run's own pose frame makes. */\nexport function pathHold<TPose>(scene: Scene<unknown, string, TPose>): PathHold {\n const held = new Map<string, PoseOverride<TPose>>();\n const release = (id: string, entry: PoseOverride<TPose>) => {\n held.delete(id);\n if (scene.overrides.get(id as NodeId) === entry) scene.overrides.clear(id as NodeId);\n };\n return {\n show(paths) {\n for (const [id, entry] of held) if (!paths.has(id)) release(id, entry);\n for (const [id, path] of paths) {\n const entry = held.get(id);\n if (entry !== undefined && scene.overrides.get(id as NodeId) === entry) {\n entry.path = path;\n continue;\n }\n const fresh: PoseOverride<TPose> = { path };\n held.set(id, fresh);\n scene.overrides.set(id as NodeId, fresh);\n }\n },\n drop() {\n for (const [id, entry] of held) release(id, entry);\n },\n };\n}\n\n/** The routes a live run eases, and where it shows them. Stable for the life\n * of the component, and drops what it shows when the component unmounts. */\nexport interface EasedRoutes<TPose> {\n /** The routes the run now eases; any shown before stop showing. */\n set(easings: readonly RouteEasing[]): void;\n /** Show each route `u` of the way there, its ends where `poseOf` puts\n * them; `null` shows none. `geometry` reads the poses' bounds. */\n show(\n scene: Scene<unknown, string, TPose>,\n u: number | null,\n poseOf: (id: string) => TPose | undefined,\n geometry?: PoseDescriptor<TPose>,\n ): void;\n /** Stop showing them. */\n drop(): void;\n}\n\nexport function useEasedRoutes<TPose>(): EasedRoutes<TPose> {\n const easings = useRef<readonly RouteEasing[]>([]);\n const held = useRef<{ scene: Scene<unknown, string, TPose>; hold: PathHold } | null>(null);\n const routes = useMemo<EasedRoutes<TPose>>(() => ({\n set(next) {\n held.current?.hold.drop();\n easings.current = next;\n },\n show(scene, u, poseOf, geometry) {\n if (u === null) held.current?.hold.drop();\n if (u === null || easings.current.length === 0) return;\n if (held.current?.scene !== scene) {\n held.current?.hold.drop();\n held.current = { scene, hold: pathHold(scene) };\n }\n held.current.hold.show(easedPaths(scene, easings.current, u, poseOf, geometry));\n },\n drop() {\n held.current?.hold.drop();\n },\n }), []);\n useEffect(() => () => routes.drop(), [routes]);\n return routes;\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: `force` is a relaxation whose target changes every tick;\n * `layered` and `tree` know where they are going, so they ease into it. So\n * does a `LayoutPlanner`, once it answers.\n *\n * **A node another gesture owns is a pin.** `force` holds it with `fx`/`fy`\n * and relaxes its neighbors around it, and an eased layout leaves it alone, so\n * dragging a body mid-run is the consumer's ordinary move tool.\n */\nimport { useCallback, useEffect, useMemo, useRef } from 'react';\nimport {\n useLatest,\n usePoseRun,\n type NodeId,\n type PoseDescriptor,\n type PoseRunCtx,\n type PoseRunStep,\n type Scene,\n} from '@weasel-js/core';\nimport { type EasingFn } from '@weasel-js/animator';\nimport { isPromise } from './footprint';\nimport { buildGraph, type Graph, type GraphSource } from './graph';\nimport { chain } from './chain';\nimport { layered } from './layered';\nimport { LAYOUTS, layoutPoses } from './layoutAction';\nimport { planOf, plannerPlan, type LayoutFn, type LayoutOptions, type LayoutPlan, type LayoutPlanner } from './layout';\nimport { sameGraph, shapeOf, usePendingPlan } from './livePlan';\nimport {\n EASE_FRAMES,\n easeInOut,\n easedProducer,\n forceProducer,\n progress,\n type ForceProducerOptions,\n type LiveLayoutProducer,\n} from './liveProducers';\nimport { routeEasings, useEasedRoutes } from './liveRoutes';\nimport { routeWrites, routesOf, type LayoutRoutes } from './routeWrites';\nimport { tree } from './tree';\nimport type { DiagramNodeReader } from './trait';\n\nexport {\n easedProducer,\n forceProducer,\n type EasedProducerOptions,\n type ForceProducerOptions,\n type LiveLayoutCtx,\n type LiveLayoutFrame,\n type LiveLayoutProducer,\n} from './liveProducers';\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`, a layout of the consumer's own, or a planner that\n * answers later. `'force'` relaxes continuously; anything else eases to its\n * answer. Default `'force'`. */\n algorithm?: string | LayoutFn | LayoutPlanner;\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 /** Hears why a `LayoutPlanner` failed to answer, and no run starts. Unset,\n * the failure goes to `console.error`. */\n onError?: (error: unknown) => 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, which includes waiting on a\n * planner's answer. */\n start(): void;\n /** Finish now: commit where the nodes stand. A planner's answer still to\n * come is dropped. */\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 graph `o.source` describes now. */\nfunction graphOf<TPose>(o: UseLiveLayoutOptions<TPose>): Graph {\n return buildGraph(o.source, {\n ...(o.read ? { read: o.read } : {}),\n ...(o.geometry ? { geometry: o.geometry } : {}),\n });\n}\n\n/** What `o.algorithm` plans for `graph`: `null` for a relaxation, which has\n * no destination, and a promise from a planner that answers later. */\nfunction planFor<TPose>(graph: Graph, o: UseLiveLayoutOptions<TPose>): LayoutPlan | Promise<LayoutPlan> | null {\n const algorithm = o.algorithm ?? 'force';\n if (algorithm === 'force') return null;\n if (typeof algorithm === 'object') return plannerPlan(algorithm, graph, o.layout);\n return planOf(typeof algorithm === 'function' ? algorithm : LAYOUTS[algorithm] ?? layered, graph, o.layout);\n}\n\n/** The producer that eases from `graph` to `plan`, or relaxes `graph` when\n * there is no plan. */\nfunction producerFor<TPose>(graph: Graph, plan: LayoutPlan | null, o: UseLiveLayoutOptions<TPose>): LiveLayoutProducer<TPose> {\n if (plan === null) return forceProducer<TPose>(graph, { ...o.layout, ...o.force, ...(o.geometry ? { geometry: o.geometry } : {}) });\n return easedProducer<TPose>(graph, () => plan.moves, {\n ...(o.frames === undefined ? {} : { frames: o.frames }),\n ...(o.easing ? { easing: o.easing } : {}),\n });\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 /** The routes the run's layout laid out, written once it arrives. */\n const routes = useRef<LayoutRoutes | undefined>(undefined);\n /** Whether a gesture held a participant during the run: the routes were\n * laid out around where it was going, not where it was put. */\n const held = useRef(false);\n const eased = useEasedRoutes<TPose>();\n\n const pending = usePendingPlan();\n\n /** Set the run up to ease from `graph` to `plan`, or to relax it when\n * there is no plan. */\n const install = useCallback((graph: Graph, plan: LayoutPlan | null): void => {\n const o = optsRef.current;\n producerFrame.current = 0;\n held.current = false;\n routes.current = routesOf(graph, plan ?? { moves: new Map() });\n eased.set(routeEasings(o.scene, graph, routes.current));\n producer.current = producerFor(graph, plan, o);\n }, [optsRef, eased]);\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 if (ctx.pinned.size > 0) held.current = true;\n const frame = producerFrame.current++;\n const { result, done } = producer.current({ pinned: ctx.pinned, frame });\n // A pinned participant takes its subtree out of the frame with it: its\n // rows and labels are ids of their own, and left in they would be\n // published from the pose the document still holds.\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 // Routes ease only toward where they will be written, which a held run never writes.\n const { u } = progress(frame, o.frames ?? EASE_FRAMES, o.easing ?? easeInOut);\n eased.show(o.scene, held.current ? null : u, (id) => poses.get(id) ?? ctx.pinned.get(id as NodeId), o.geometry);\n return { poses: [...poses] as [NodeId, TPose][], done };\n }, [optsRef, eased]);\n\n const run = usePoseRun<TPose>({\n scene: opts.scene,\n step,\n // Eased routes go once the routes are in the document, so no frame shows the old ones.\n onCommit: (moved) => { eased.drop(); optsRef.current.onSettle?.(moved); },\n // Routes match where the layout was going, so only a run that got there\n // with nothing held along the way writes them.\n commitWith: (finished) => {\n if (!finished || held.current || routes.current === undefined) return;\n const scene = optsRef.current.scene;\n for (const [id, data] of routeWrites(scene as never, routes.current)) scene.update(id as never, { data });\n },\n ...(opts.label ? { label: opts.label } : {}),\n ...(opts.requestFrame ? { requestFrame: opts.requestFrame } : {}),\n ...(opts.cancelFrame ? { cancelFrame: opts.cancelFrame } : {}),\n });\n\n /** Read the graph and set the run up on it: true once it is ready to run,\n * false while a planner's answer is on its way, after which it starts the\n * run itself. */\n const build = useCallback((): boolean => {\n const graph = graphOf(optsRef.current);\n shape.current = shapeOf(graph);\n const plan = planFor(graph, optsRef.current);\n if (plan === null || !isPromise(plan)) {\n install(graph, plan);\n return true;\n }\n pending.request(plan, (answer) => {\n if (!sameGraph(graph, graphOf(optsRef.current))) return;\n install(graph, answer);\n run.start();\n }, (error) => {\n const onError = optsRef.current.onError;\n if (onError) onError(error);\n else console.error(error);\n });\n return false;\n }, [optsRef, install, pending, run]);\n\n /** Abandon whatever is running or awaited, and start again from where the\n * nodes are now. */\n const restart = useCallback((): void => {\n pending.drop();\n run.cancel();\n if (build()) run.start();\n }, [pending, run, build]);\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. A planner is asked\n // again, since its answer has no place for what changed.\n useEffect(() => {\n if (opts.reheatOnGraphChange === false) return;\n return opts.scene.subscribe(() => {\n if (!run.isRunning() && !pending.isWaiting()) return;\n if (shapeOf(graphOf(optsRef.current)) === shape.current) return;\n if (typeof optsRef.current.algorithm === 'object') restart();\n else build();\n });\n }, [opts.scene, opts.reheatOnGraphChange, run, build, restart, pending, optsRef]);\n\n return useMemo<LiveLayout>(() => ({\n start() {\n if (run.isRunning() || pending.isWaiting()) return;\n if (build()) run.start();\n },\n stop: () => { pending.drop(); run.stop(); },\n cancel: () => { pending.drop(); run.cancel(); eased.drop(); },\n restart,\n isRunning: () => run.isRunning() || pending.isWaiting(),\n }), [run, build, restart, eased, pending]);\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 chain,\n});\n","/**\n * The painter for a node whose trait names an `outline`. 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.\n */\nimport {\n commandFill,\n commandStroke,\n polylineFromPoints,\n RECT_POSE_DESCRIPTOR,\n registerNodeShape,\n type NodeShapeEntry,\n type Path,\n type PoseDescriptor,\n type Stroke,\n type Fill,\n} from '@weasel-js/core';\nimport { outlinePath } from './outline';\nimport { diagramContainerOf, headerBox, laneOutlineOf } from './containers/trait';\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?: Fill | 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 ?? laneOutlineOf(node);\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?: Fill | null; stroke?: Stroke | null };\n const box = geometry.getBounds(pose);\n const declaredFill = d.fill === undefined ? opts.defaultFill : d.fill;\n const declaredStroke = d.stroke === undefined ? opts.defaultStroke : d.stroke;\n const fill = declaredFill && commandFill(declaredFill, box);\n const stroke = declaredStroke && commandStroke(declaredStroke, box);\n const header = headerBox(box, diagramContainerOf(node)?.header);\n const divider = header === null || !stroke ? [] : [{ kind: 'path' as const, path: dividerPath(box, header), stroke }];\n return [{\n kind: 'path',\n path: outlinePath(outline, box),\n ...(fill ? { fill } : {}),\n ...(stroke ? { stroke } : {}),\n }, ...divider];\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\ntype Box = { x: number; y: number; width: number; height: number };\n\n/** The line between a container's header and its body. */\nfunction dividerPath(box: Box, header: Box): Path {\n return header.width < box.width\n ? polylineFromPoints([{ x: header.x + header.width, y: box.y }, { x: header.x + header.width, y: box.y + box.height }])\n : polylineFromPoints([{ x: box.x, y: header.y + header.height }, { x: box.x + box.width, y: header.y + header.height }]);\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","import { useLatest, type NodeId, type SelectionApi } from '@weasel-js/core';\nimport { useCallback, useEffect, useRef } from 'react';\n\n/** Keeps a canvas selection and a controlled `selected` prop in step: a prop\n * change is pushed in, and every click reports what the selection holds after\n * it — a re-click on the picked node included. Wire the returned handler to\n * `<SceneCanvas onClick>`. */\nexport function useMirroredSelection(\n selection: Pick<SelectionApi, 'get' | 'set'>,\n selected: string | null | undefined,\n onSelect: ((id: string | null) => void) | undefined,\n): () => void {\n const want = selected ?? null;\n const pushed = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n if (pushed.current === want) return;\n pushed.current = want;\n if ((selection.get()[0] ?? null) !== want) selection.set(want === null ? [] : [want as NodeId]);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- runs when the prop changes, not the canvas\n }, [want]);\n const onSelectRef = useLatest(onSelect);\n return useCallback(() => {\n onSelectRef.current?.((selection.get()[0] as string | undefined) ?? null);\n }, [selection, onSelectRef]);\n}\n","/**\n * The regions half of `DiagramView`'s sync: where each container, pool, and\n * lane stands, and the region edits a change to that is reported as.\n */\nimport type { RectPose, Scene } from '@weasel-js/core';\nimport { lanesOf, poolAxisOf } from './containers/containerStencils';\nimport { diagramContainerOf } from './containers/trait';\n\ntype Box = { x: number; y: number; width: number; height: number };\n\n/**\n * A region edit, which `DiagramView` reports and does not keep: `box`, a\n * container or pool moved or resized (`parent` present when a drop changed\n * the region it is in, `null` for the top level); `lanes`, a pool's lanes\n * resized, reordered, or added to, every lane in stacking order with its size\n * (a new lane's id is minted by the view); `release`, Release members run on\n * a region; `title`, a double-click on a region's header.\n */\nexport type ContainerEdit =\n | { kind: 'box'; id: string; box: Box; parent?: string | null }\n | { kind: 'lanes'; pool: string; lanes: readonly { id: string; size: number }[] }\n | { kind: 'release'; id: string }\n | { kind: 'title'; id: string };\n\ninterface RegionAt { box: Box; parent: string | null; fitted: boolean }\n\n/** Where every region stands, and each pool's lanes in order. */\nexport interface RegionStanding {\n regions: Map<string, RegionAt>;\n pools: Map<string, { id: string; size: number }[]>;\n}\n\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** Each lane of `poolId` with its size along the stack, in order. */\nexport function laneList(scene: AnyScene, poolId: string): { id: string; size: number }[] {\n const pool = scene.get(poolId as never);\n const trait = pool === undefined ? null : diagramContainerOf(pool);\n if (trait === null) return [];\n const axis = poolAxisOf(trait);\n return lanesOf(scene, poolId).map((id) => {\n const p = scene.get(id)!.pose as RectPose;\n return { id: id as string, size: axis === 'y' ? p.height : p.width };\n });\n}\n\n/** Where each region in `scene` stands. */\nexport function readRegions(scene: AnyScene): RegionStanding {\n const regions = new Map<string, RegionAt>();\n const pools = new Map<string, { id: string; size: number }[]>();\n for (const n of scene.renderOrderNodes()) {\n const trait = diagramContainerOf(n);\n if (trait === null) continue;\n const { x, y, width, height } = n.pose as RectPose;\n regions.set(n.id, { box: { x, y, width, height }, parent: n.parent, fitted: trait.fitted === true });\n if (trait.role === 'pool') pools.set(n.id, laneList(scene, n.id));\n }\n return { regions, pools };\n}\n\nconst sameBox = (a: Box, b: Box) => a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\nconst sameLanes = (a: readonly { id: string; size: number }[], b: readonly { id: string; size: number }[]) =>\n a.length === b.length && a.every((l, i) => l.id === b[i]!.id && l.size === b[i]!.size);\n\n/**\n * The region edits between two standings. A lane's box is reported only as\n * its pool's lanes, and a fitted container carried along by a region around\n * it not at all: its box is fitted to its members, which report their own moves.\n */\nexport function regionChanges(was: RegionStanding, now: RegionStanding): ContainerEdit[] {\n const out: ContainerEdit[] = [];\n const changed = new Set<string>();\n for (const [id, at] of now.regions) {\n const before = was.regions.get(id);\n if (before !== undefined && (!sameBox(before.box, at.box) || before.parent !== at.parent)) changed.add(id);\n }\n const carried = (id: string): boolean => {\n for (let p = now.regions.get(id)?.parent ?? null; p !== null; p = now.regions.get(p)?.parent ?? null) {\n if (changed.has(p)) return true;\n }\n return false;\n };\n for (const id of changed) {\n const at = now.regions.get(id)!;\n const before = was.regions.get(id)!;\n if (now.pools.has(at.parent ?? '')) continue;\n if (at.fitted && before.parent === at.parent && carried(id)) continue;\n out.push({ kind: 'box', id, box: at.box, ...(before.parent !== at.parent ? { parent: at.parent } : {}) });\n }\n for (const [pool, lanes] of now.pools) {\n const before = was.pools.get(pool);\n if (before !== undefined && !sameLanes(before, lanes)) out.push({ kind: 'lanes', pool, lanes });\n }\n return out;\n}\n","/**\n * `DiagramView`'s two-way sync with the data it was built from: new specs are\n * reconciled into the scene, and what a drag or a layout run changed is\n * reported back, so a consumer keeping the diagram as data can store it.\n * `diagramLayoutOf` reads the same report off a `diagramScene` build.\n */\nimport { reconcileSpecs, useLatest, type RectPose, type Scene } from '@weasel-js/core';\nimport type { Vec2 } from '@weasel-js/core/math';\nimport { useEffect, useRef } from 'react';\nimport { diagramContainerOf } from './containers/trait';\nimport { diagramEdgeOf, layoutOwnsRoute, samePoints, type DiagramEdge, type EdgeEnd } from './edgeTrait';\nimport type { DiagramSceneData, DiagramSpec } from './fromData';\nimport { diagramGroupOf } from './group';\nimport type { LayoutPorts } from './layout';\nimport { readRegions, regionChanges, type ContainerEdit, type RegionStanding } from './regionSync';\nimport { isPinned } from './trait';\n\nexport type { ContainerEdit };\n\n/** Where a moved node now stands. `parent` is present when a drop changed\n * the region it is in: that container's or lane's id, or `null` for the top\n * level. The host moves the id from one `members` list to the other. */\nexport interface NodeMove { id: string; x: number; y: number; parent?: string | null }\n\n/** An edge whose route or ports a layout run rewrote. `id` is the edge's\n * scene id, `edgeIdOf` of its data edge; `waypoints` is empty when the run\n * took a route away and left the edge straight, and `ports` names the ends\n * layout owns. Store them as the data edge's `routed` and `routedPorts`,\n * which stay layout's, not as `waypoints`, `fromPort` and `toPort`, which\n * would be the author's and rename the edge. */\nexport interface EdgeRoute { id: string; waypoints: readonly Vec2[]; ports: LayoutPorts }\n\ntype DiagramScene = Scene<DiagramSceneData, 'main', RectPose>;\n\ninterface Route { waypoints: readonly Vec2[]; ports: LayoutPorts }\n\ninterface Standing {\n nodes: Map<string, { x: number; y: number; parent: string | null }>;\n routes: Map<string, Route>;\n regions: RegionStanding;\n}\n\nconst NONE: readonly Vec2[] = [];\n\n/** The port layout owns at `end`, if it named one. */\nconst laidPort = (end: EdgeEnd) => (end.laidOut !== undefined && end.port === end.laidOut ? end.laidOut : undefined);\n\nfunction portsOf(from: EdgeEnd, to: EdgeEnd): LayoutPorts {\n const f = laidPort(from);\n const t = laidPort(to);\n return { ...(f !== undefined ? { from: f } : {}), ...(t !== undefined ? { to: t } : {}) };\n}\n\nconst samePorts = (a: LayoutPorts, b: LayoutPorts) => a.from === b.from && a.to === b.to;\n\nconst routeOf = (edge: DiagramEdge): Route => ({ waypoints: edge.waypoints ?? NONE, ports: portsOf(edge.from, edge.to) });\n\nfunction readScene(scene: DiagramScene): Standing {\n const nodes = new Map<string, { x: number; y: number; parent: string | null }>();\n const routes = new Map<string, Route>();\n for (const n of scene.renderOrderNodes()) {\n if (n.kind === 'container') {\n if (diagramContainerOf(n) === null) nodes.set(n.id, { x: n.pose.x, y: n.pose.y, parent: n.parent });\n continue;\n }\n const edge = diagramEdgeOf(n);\n if (edge !== null) routes.set(n.id, routeOf(edge));\n }\n return { nodes, routes, regions: readRegions(scene as never) };\n}\n\n/** What layout placed in a `diagramScene` build, in the shapes `DiagramView`\n * reports: every node not pinned, where it stands, every edge whose route\n * or ports layout wrote, and the box of every container and pool not pinned\n * whose box is its own rather than fitted. Store them the way `onMove` and\n * `onEditContainer` say and the next build leaves them where they are. */\nexport function diagramLayoutOf(specs: readonly DiagramSpec[]): { moves: NodeMove[]; routes: EdgeRoute[]; containers: ContainerEdit[] } {\n const moves: NodeMove[] = [];\n const routes: EdgeRoute[] = [];\n const containers: ContainerEdit[] = [];\n for (const s of specs) {\n const id = s.id;\n if (id === undefined) continue;\n if (s.kind === 'container') {\n const region = diagramContainerOf(s);\n const pinned = isPinned({ id, kind: s.kind, data: s.data });\n if (region !== null) {\n if (!pinned && region.role !== 'lane' && region.fitted !== true) {\n const { x, y, width, height } = s.pose;\n containers.push({ kind: 'box', id, box: { x, y, width, height } });\n }\n } else if (diagramGroupOf(s) === null && !pinned) moves.push({ id, x: s.pose.x, y: s.pose.y });\n continue;\n }\n const edge = diagramEdgeOf(s);\n if (edge === null) continue;\n const route = routeOf(edge);\n const laid = edge.laidOut !== undefined && route.waypoints.length > 0 && layoutOwnsRoute(edge);\n if (laid || route.ports.from !== undefined || route.ports.to !== undefined) {\n routes.push({ id, waypoints: laid ? route.waypoints : NONE, ports: route.ports });\n }\n }\n return { moves, routes, containers };\n}\n\ninterface Changes { moves: NodeMove[]; routes: EdgeRoute[]; containers: ContainerEdit[] }\n\nfunction changes(was: Standing, now: Standing): Changes {\n const moves: NodeMove[] = [];\n for (const [id, { x, y, parent }] of now.nodes) {\n const before = was.nodes.get(id);\n if (before === undefined) continue;\n const reparented = before.parent !== parent;\n if (before.x !== x || before.y !== y || reparented) moves.push({ id, x, y, ...(reparented ? { parent } : {}) });\n }\n const routes: EdgeRoute[] = [];\n for (const [id, after] of now.routes) {\n const before = was.routes.get(id);\n if (before === undefined) continue;\n const moved = before.waypoints !== after.waypoints && !samePoints(before.waypoints, after.waypoints);\n if (moved || !samePorts(before.ports, after.ports)) routes.push({ id, ...after });\n }\n return { moves, routes, containers: regionChanges(was.regions, now.regions) };\n}\n\n/** The callbacks {@link useSceneSync} reports to. */\nexport interface SceneSyncReports {\n onMove?: ((moves: readonly NodeMove[], routes: readonly EdgeRoute[]) => void) | undefined;\n onEditContainer?: ((edit: ContainerEdit) => void) | undefined;\n}\n\n/** Reconcile `specs` into `scene` as they change, and report every move and\n * route change that did not come from a reconcile to `onMove`, and every\n * region change to `onEditContainer`. */\nexport function useSceneSync(scene: DiagramScene, specs: readonly DiagramSpec[], reports: SceneSyncReports): void {\n const reportsRef = useLatest(reports);\n const syncing = useRef(false);\n const applied = useRef(specs);\n useEffect(() => {\n let known = readScene(scene);\n return scene.subscribe(() => {\n const now = readScene(scene);\n const found = syncing.current ? null : changes(known, now);\n known = now;\n if (found === null) return;\n if (found.moves.length > 0 || found.routes.length > 0) reportsRef.current.onMove?.(found.moves, found.routes);\n for (const edit of found.containers) reportsRef.current.onEditContainer?.(edit);\n });\n }, [scene, reportsRef]);\n useEffect(() => {\n if (applied.current === specs) return;\n syncing.current = true;\n try {\n reconcileSpecs(scene, applied.current as DiagramSpec[], specs as DiagramSpec[]);\n } finally {\n syncing.current = false;\n }\n applied.current = specs;\n }, [scene, specs]);\n}\n","/**\n * What `DiagramView` installs for `onEditContainer`: the container actions\n * with every commit swapped for a report, and the header double-click.\n */\nimport type { Contribution, NodeId, RenderLayer, Scene } from '@weasel-js/core';\nimport { diagramContainers, laneResizeFrame, type LaneResize } from './containers/containerActions';\nimport { editContainerTitleAction, editContainerTitleBinding } from './containers/containerTitle';\nimport { poolsOf } from './containers/laneBoundaryLayer';\nimport { diagramContainerOf } from './containers/trait';\nimport { DEFAULT_LANE_SIZE } from './dataTypes';\nimport { laneList, type ContainerEdit } from './regionSync';\nimport type { NodeMove } from './sceneSync';\nimport { dataKeyReader } from './trait';\n\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** Where region edits and the moves they bring about are reported. */\nexport interface RegionReports {\n onEditContainer?: ((edit: ContainerEdit) => void) | undefined;\n onMove?: ((moves: readonly NodeMove[], routes: readonly never[]) => void) | undefined;\n}\n\n/**\n * A lane resize as reports: the pool's lanes with the one resized, and, for\n * what the lanes after it carry, a node's move or a boxed region's box.\n */\nexport function laneResizeReports(scene: AnyScene, resize: LaneResize): { lanes: ContainerEdit; moves: NodeMove[]; boxes: ContainerEdit[] } | null {\n const pool = poolsOf(scene).find((p) => p.id === resize.poolId);\n const index = pool?.lanes.findIndex((l) => l.id === resize.laneId) ?? -1;\n if (pool === undefined || index < 0) return null;\n const lanes = laneList(scene, pool.id).map((l) => (l.id === resize.laneId ? { ...l, size: resize.size } : l));\n const moves: NodeMove[] = [];\n const boxes: ContainerEdit[] = [];\n for (const [id, pose] of laneResizeFrame(scene, pool, index, resize.size)) {\n const node = scene.get(id as NodeId);\n if (node === undefined) continue;\n const region = diagramContainerOf(node);\n const { x, y, width, height } = pose;\n if (region !== null) {\n if (region.role === 'container' && region.fitted !== true) boxes.push({ kind: 'box', id, box: { x, y, width, height } });\n } else if (node.kind === 'container' && dataKeyReader(node) !== null) moves.push({ id, x, y });\n }\n return { lanes: { kind: 'lanes', pool: pool.id, lanes }, moves, boxes };\n}\n\n/** The lane layer and the contributions that report region edits through `reports`. */\nexport function regionEditing(\n scene: AnyScene,\n selected: () => readonly string[],\n reports: { readonly current: RegionReports },\n): { layer: RenderLayer<unknown>; contributions: Contribution[] } {\n const edit = (e: ContainerEdit) => reports.current.onEditContainer?.(e);\n const containers = diagramContainers({\n scene,\n selected,\n commitResize: (resize) => {\n const out = laneResizeReports(scene, resize);\n if (out === null) return;\n edit(out.lanes);\n for (const box of out.boxes) edit(box);\n if (out.moves.length > 0) reports.current.onMove?.(out.moves, []);\n },\n commitAddLane: (poolId) => {\n const lanes = [...laneList(scene, poolId), { id: scene.mintId() as string, size: DEFAULT_LANE_SIZE }];\n edit({ kind: 'lanes', pool: poolId, lanes });\n },\n commitRelease: (id) => edit({ kind: 'release', id }),\n });\n const title: Contribution = {\n id: 'weasel-diagram-container-title',\n eligibility: { always: true },\n actions: [editContainerTitleAction((id) => edit({ kind: 'title', id }))],\n bindings: [editContainerTitleBinding()],\n };\n return { layer: containers.layer, contributions: [containers.contribution, title] };\n}\n","/**\n * What `DiagramView` installs for each editing callback it is handed. Every\n * action keeps its gesture and swaps its commit for one that reports a data\n * edit, so the host changes its data and the view follows through the specs.\n */\nimport {\n createDeleteAction,\n createResizeAction,\n dragPanContribution,\n useLatest,\n type Action,\n type ActionsProp,\n type Contribution,\n type RectPose,\n type RenderLayer,\n type Scene,\n} from '@weasel-js/core';\nimport { useMemo } from 'react';\nimport { isBodyEnd } from './connectTargets';\nimport { diagramContainerOf, titleIdOf } from './containers/trait';\nimport { diagramLabelDrag, diagramPorts, diagramWaypoints } from './contribution';\nimport { editEdgeLabelAction, editEdgeLabelBinding } from './edgeLabel';\nimport { diagramEdgeOf } from './edgeTrait';\nimport type { DiagramSpec } from './fromData';\nimport type { ParticipantSource } from './portAffordance';\nimport { portLayer } from './portLayer';\nimport { diagramEdgeEnds, type EndChange } from './reconnect';\nimport { groupReorderContribution } from './groupReorder';\nimport { regionEditing } from './regionEditing';\nimport type { ContainerEdit } from './regionSync';\nimport { dataKeyReader } from './trait';\nimport type { DeleteReport, DiagramViewProps, NodeResize, ReconnectChange } from './diagramViewProps';\n\nconst AMBIENT = [dragPanContribution()];\n// A drag on empty canvas pans: the select tool's marquee would outrank the ambient pan.\nconst NO_MARQUEE = { areaSelect: null };\n\ntype AnyScene = Scene<unknown, string, unknown>;\n\n/** `id`, a region, and every node and region inside it, into `out`. */\nfunction regionAndMembers(scene: AnyScene, id: string, out: Set<string>): void {\n out.add(id);\n for (const child of scene.childrenOf(id as never)) {\n const node = scene.get(child);\n if (node === undefined || child === titleIdOf(id)) continue;\n if (diagramContainerOf(node) !== null) regionAndMembers(scene, child, out);\n else if (dataKeyReader(node) !== null) out.add(child);\n }\n}\n\n/**\n * The data a delete of `ids` takes: the selected nodes and groups, every\n * container, pool, or lane with what it holds, and every edge selected or\n * ending on one of them. Not `removalClosure`: a group depends on its\n * members, and deleting a member leaves the group standing.\n */\nexport function removedData(scene: AnyScene, ids: readonly string[]): DeleteReport {\n const nodes = new Set<string>();\n const edges = new Set<string>();\n for (const id of ids) {\n const node = scene.get(id as never);\n if (node === undefined) continue;\n if (diagramEdgeOf(node) !== null) edges.add(id);\n else if (diagramContainerOf(node) !== null) regionAndMembers(scene, id, nodes);\n else if (dataKeyReader(node) !== null) nodes.add(id);\n }\n for (const node of scene.renderOrderNodes()) {\n const ends = node.dependsOn;\n if (diagramEdgeOf(node) !== null && Array.isArray(ends) && ends.some((end) => nodes.has(end))) edges.add(node.id);\n }\n return { nodes: [...nodes], edges: [...edges] };\n}\n\n/** Core's `delete`, reporting what it would remove instead of removing it. */\nexport function reportDeleteAction(report: (removed: DeleteReport) => void): Action {\n return createDeleteAction({\n commit: (ids, deps) => {\n if (deps.scene === undefined) return;\n const removed = removedData(deps.scene as Scene<unknown, string, unknown>, ids);\n if (removed.nodes.length > 0 || removed.edges.length > 0) report(removed);\n },\n });\n}\n\n/** Core's `resize`, reporting the selected boxes it would leave instead of writing them: a\n * container's or pool's to `region` as a box edit, any other's to `report`. */\nexport function reportResizeAction(\n report: ((resizes: readonly NodeResize[]) => void) | undefined,\n region?: (edit: ContainerEdit) => void,\n): Action {\n return createResizeAction({\n commit: (poses, deps) => {\n const picked = new Set(deps.selection?.get() ?? []);\n const resizes: NodeResize[] = [];\n for (const [id, pose] of poses) {\n if (!picked.has(id)) continue;\n const { x, y, width, height } = pose as RectPose;\n const node = deps.scene?.get(id as never);\n if (node !== undefined && diagramContainerOf(node) !== null) region?.({ kind: 'box', id, box: { x, y, width, height } });\n else resizes.push({ id, x, y, width, height });\n }\n if (resizes.length > 0) report?.(resizes);\n },\n });\n}\n\nexport const reconnectChangeOf =({ edgeId, end, target }: EndChange): ReconnectChange => ({\n edge: edgeId,\n end,\n node: target.nodeId,\n ...(isBodyEnd(target) ? {} : { port: target.id }),\n});\n\n/** `specs` with every edge pickable, so a click selects it. */\nexport function withPickableEdges(specs: readonly DiagramSpec[]): DiagramSpec[] {\n return specs.map((s) => (diagramEdgeOf(s) !== null ? { ...s, pickable: true } : s));\n}\n\ntype EditingProps = Pick<\n DiagramViewProps,\n 'onConnect' | 'onReconnect' | 'onEditRoute' | 'onDelete' | 'onEditLabel' | 'onMoveLabel' | 'onReorder' | 'onResize' | 'onEditContainer' | 'onMove'\n | 'connectBodies' | 'canConnect' | 'portOptions' | 'ambient'\n>;\n\nexport interface DiagramEditing {\n /** In registration order: the last is hit first. */\n layers: readonly RenderLayer<unknown>[];\n ambient: readonly Contribution[];\n actions: ActionsProp;\n}\n\nexport function useDiagramEditing(\n props: EditingProps & {\n scene: AnyScene; source: ParticipantSource<RectPose>; selected: () => readonly string[]; mode: 'connect' | 'show' | 'none';\n },\n): DiagramEditing {\n const { scene, source, selected, mode, canConnect, portOptions, connectBodies } = props;\n const report = useLatest(props);\n const reconnects = props.onReconnect !== undefined;\n const routes = props.onEditRoute !== undefined;\n const labels = props.onEditLabel !== undefined;\n const labelMoves = props.onMoveLabel !== undefined;\n const deletes = props.onDelete !== undefined;\n const reorders = props.onReorder !== undefined;\n const resizes = props.onResize !== undefined;\n const regionEdits = props.onEditContainer !== undefined;\n\n const ports = useMemo(() => mode === 'connect'\n ? diagramPorts<RectPose>({\n ...portOptions,\n participants: source,\n bodies: connectBodies === true,\n ...(canConnect ? { canConnect } : {}),\n commit: ({ from, to }) => report.current.onConnect?.({\n from: from.nodeId,\n ...(isBodyEnd(from) ? {} : { fromPort: from.id }),\n to: to.nodeId,\n ...(isBodyEnd(to) ? {} : { toPort: to.id }),\n }),\n })\n : null, [mode, source, canConnect, portOptions, connectBodies, report]);\n // A registered layer with no `hitTest` is painted and claims no press.\n const shown = useMemo(() => {\n if (mode !== 'show') return null;\n const { hitTest: _hitTest, ...paintOnly } = portLayer<RectPose>(source, portOptions);\n return paintOnly;\n }, [mode, source, portOptions]);\n const ends = useMemo(() => reconnects\n ? diagramEdgeEnds<RectPose>({\n participants: source,\n selected,\n bodies: connectBodies === true,\n ...(canConnect ? { canConnect } : {}),\n ...(portOptions?.snapRadius !== undefined ? { snapRadius: portOptions.snapRadius } : {}),\n ...(portOptions?.showsPort ? { showsPort: portOptions.showsPort } : {}),\n commit: (change) => report.current.onReconnect?.(reconnectChangeOf(change)),\n })\n : null, [reconnects, source, selected, connectBodies, canConnect, portOptions, report]);\n const route = useMemo(() => routes\n ? diagramWaypoints<RectPose>({\n participants: source,\n selected,\n commit: ({ edgeId, waypoints }) => report.current.onEditRoute?.({ edge: edgeId, waypoints }),\n })\n : null, [routes, source, selected, report]);\n const labelDrag = useMemo(() => labelMoves\n ? diagramLabelDrag({\n scene,\n selected,\n commit: ({ edgeId, placement }) => report.current.onMoveLabel?.({ edge: edgeId, placement }),\n })\n : null, [labelMoves, scene, selected, report]);\n const label = useMemo((): Contribution | null => labels\n ? {\n id: 'weasel-diagram-edge-label',\n eligibility: { always: true },\n actions: [editEdgeLabelAction({ commit: (edgeId) => report.current.onEditLabel?.(edgeId) })],\n bindings: [editEdgeLabelBinding()],\n }\n : null, [labels, report]);\n const reorder = useMemo(\n () => (reorders ? groupReorderContribution((change) => report.current.onReorder?.(change)) : null),\n [reorders, report],\n );\n const regions = useMemo(() => (regionEdits ? regionEditing(scene, selected, report) : null), [regionEdits, scene, selected, report]);\n const actions = useMemo(() => ({\n ...NO_MARQUEE,\n ...(deletes ? { delete: reportDeleteAction((r) => report.current.onDelete?.(r)) } : {}),\n ...(resizes || regionEdits\n ? { resize: reportResizeAction((r) => report.current.onResize?.(r), (e) => report.current.onEditContainer?.(e)) }\n : {}),\n }), [deletes, resizes, regionEdits, report]);\n\n const portsLayer = ports?.layer ?? shown;\n const layers = useMemo(\n // Edge ends last: an edge's end sits on a port and beside a route handle, and the last layer is hit first.\n () => [regions?.layer, labelDrag?.layer, portsLayer, route?.layer, ends?.layer].filter((l): l is RenderLayer<unknown> => l != null),\n [regions, labelDrag, portsLayer, route, ends],\n );\n const extra = props.ambient;\n const ambient = useMemo(() => [\n ...AMBIENT,\n ...[ports?.contribution, route?.contribution, ends?.contribution, labelDrag?.contribution, label, reorder]\n .filter((c): c is Contribution => c != null),\n ...(regions?.contributions ?? []),\n ...(extra ?? []),\n ], [ports, route, ends, labelDrag, label, reorder, regions, extra]);\n return { layers, ambient, actions };\n}\n","import { pagesBounds, pagesLayer } from '@weasel-js/core';\nimport { useMemo } from 'react';\nimport type { DiagramViewProps } from './diagramViewProps';\n\n/** What `DiagramView`'s `pages` prop adds: the layer that paints them under the scene, and their bounds for the fit.\n * Keyed on the placed array and the fill, so a `pages` object built inline each render changes nothing. */\nexport function usePagesView(pages: DiagramViewProps['pages']) {\n const placed = pages?.placed;\n const fill = pages?.fill;\n return useMemo(() => {\n if (placed === undefined || fill === undefined) return { layers: undefined, box: undefined };\n return {\n layers: { pages: { layer: pagesLayer(placed, { fill }), before: 'scene' as const } },\n box: pagesBounds(placed) ?? undefined,\n };\n }, [placed, fill]);\n}\n","import {\n fitViewToBounds,\n SceneCanvas,\n useDepSource,\n useLatest,\n useScene,\n useSelection,\n WeaselProvider,\n type RectPose,\n type CanvasSize,\n type Scene,\n type SceneCanvasApi,\n type View,\n} from '@weasel-js/core';\nimport { adoptCssOnce } from '@weasel-js/react';\nimport { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState, type Ref, type RefObject } from 'react';\nimport { createSpecRouter } from './avoid/specRoutes';\nimport { diagramCanDropInto } from './containers/canDropInto';\nimport { createSpecHops } from './hops/specHops';\nimport { createSpecLabelPlacer } from './labels/specLabels';\nimport { useDiagramEditing, withPickableEdges } from './diagramEditing';\nimport type { DiagramLayout, DiagramViewApi, DiagramViewProps } from './diagramViewProps';\nimport { withDiagramRegistry } from './edge';\nimport { diagramGroupOf } from './group';\nimport type { DiagramSceneData, DiagramSpec } from './fromData';\nimport { useLiveLayout, type LiveLayout } from './live';\nimport { usePagesView } from './usePagesView';\nimport { useMirroredSelection } from './mirrorSelection';\nimport { screenRectOf, useOverlayPlacement, worldRectOf } from './overlays';\nimport { sceneParticipants } from './portLayer';\nimport { registerMarkShape } from './marks';\nimport { diagramResizable } from './resizable';\nimport { useSceneSync } from './sceneSync';\nimport { registerDiagramShape } from './shape';\n\nexport type { ContainerEdit, EdgeRoute, NodeMove } from './sceneSync';\nexport type {\n DeleteReport, DiagramLayout, DiagramViewApi, DiagramViewProps, LabelMove, NodeResize, ReconnectChange, RouteChange,\n} from './diagramViewProps';\nexport type { DiagramOverlay } from './overlays';\nexport type { ReorderChange } from './groupReorder';\n\n/** The view's box holds the canvas and the overlays placed over it, and is as\n * big as the canvas: its parent's box on an axis the canvas fills. */\nconst VIEW_RULE = ':where([data-wzl-diagram]) { position: relative; width: fit-content; }'\n + ' :where([data-wzl-diagram~=\"fill-x\"]) { width: 100%; }'\n + ' :where([data-wzl-diagram~=\"fill-y\"]) { height: 100%; }'\n + ' :where([data-wzl-diagram]) > canvas { display: block; }'\n + ' :where([data-wzl-diagram-overlay]) { position: absolute; left: 0; top: 0; }'\n + ' :where([data-wzl-diagram-overlay][hidden]) { display: none; }';\n\nconst adoptViewRule = (el: HTMLElement | null) => {\n if (el !== null) adoptCssOnce(el, VIEW_RULE);\n};\n\nconst IDENTITY: View = { x: 0, y: 0, scale: { x: 1, y: 1 } };\nconst sameView = (a: View, b: View) =>\n a.x === b.x && a.y === b.y && a.scale.x === b.scale.x && a.scale.y === b.scale.y;\n\n/** A diagram: drag or wheel to pan, zoom, and pick a node; drag nodes with\n * `onMove`, join ports with `onConnect`. Every edit is reported, never\n * written: change the specs to keep it. Labels paint only in a registered\n * font family; `diagramScene` defaults to sans-serif, so call\n * `registerCanvasFont('sans-serif')` or text renders blank. */\nexport const DiagramView = forwardRef<DiagramViewApi, DiagramViewProps>(function DiagramView(props, ref) {\n return (\n <WeaselProvider>\n <Inner {...props} apiRef={ref} />\n </WeaselProvider>\n );\n});\n\nfunction Inner({\n specs: given, router, labels, hops, width, height, selected, onSelect, onHover, onMove, onResize, onConnect, onReconnect, onEditRoute, onDelete, onEditLabel, onMoveLabel,\n onReorder, onEditContainer, connectBodies,\n pickEdges, overlays = NO_OVERLAYS,\n ambient: extraAmbient, enableKeybindings, canConnect, portOptions, ports: portMode, live: liveOpts,\n minScale, maxScale, anchor, fitPadding, background, pages, view, onViewChange, className, apiRef,\n}: DiagramViewProps & { apiRef: Ref<DiagramViewApi> }) {\n const edgesPick = pickEdges ?? (onReconnect !== undefined || onEditRoute !== undefined || onDelete !== undefined || onEditLabel !== undefined || onMoveLabel !== undefined);\n const avoid = useMemo(() => (router === 'avoid' ? createSpecRouter() : null), [router]);\n const placer = useMemo(() => (labels === 'dodge' ? createSpecLabelPlacer() : null), [labels]);\n const routed = useMemo(() => {\n const out = avoid === null ? given : avoid(given);\n return placer === null ? out : placer(out);\n }, [avoid, placer, given]);\n const hopped = useMemo(() => (hops === undefined ? routed : createSpecHops(hops)(routed)), [hops, routed]);\n const specs = useMemo(() => (edgesPick ? withPickableEdges(hopped) : hopped), [edgesPick, hopped]);\n useEffect(() => {\n const disposers = [registerDiagramShape<RectPose>(), registerMarkShape<RectPose>()];\n return () => disposers.forEach((dispose) => dispose());\n }, []);\n const registry = useMemo(() => withDiagramRegistry<RectPose>(), []);\n const scene = useScene<DiagramSceneData, 'main', RectPose>({\n systemLayers: [{ id: 'main' }],\n initial: specs as DiagramSpec[],\n registry,\n });\n const selection = useSelection({ scene, mode: 'single' });\n const onClick = useMirroredSelection(selection, selected, onSelect);\n\n useSceneSync(scene, specs, { onMove, onEditContainer });\n\n const source = useMemo(() => sceneParticipants<RectPose>(scene), [scene]);\n // Each `layout()` call is a new run: the state change lands the algorithm in\n // the live layout's options before the effect restarts it.\n const [run, setRun] = useState<{ algorithm: DiagramLayout } | null>(null);\n const controlled = view !== undefined;\n const fills = width === undefined || height === undefined;\n const [measured, setMeasured] = useState<CanvasSize | null>(null);\n const boxWidth = width ?? measured?.width ?? 0;\n const boxHeight = height ?? measured?.height ?? 0;\n // A filling canvas is 0 × 0 until measured, and no box to fit into.\n const unsized = boxWidth === 0 || boxHeight === 0;\n const fitOpts = { minScale, maxScale, anchor, padding: fitPadding };\n const { layers, box: pagesBox } = usePagesView(pages);\n const defaultView = useMemo(\n () => controlled || unsized ? undefined : fitDiagram(specs, { width: boxWidth, height: boxHeight }, fitOpts, pagesBox),\n // A later `specs` keeps the view it has.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [controlled, unsized, boxWidth, boxHeight, minScale, maxScale, anchor, fitPadding, pagesBox],\n );\n // A settled run's fit holds until the box or a fit option changes.\n const [settledFit, setSettledFit] = useState<{ view: View | undefined; over: View | undefined } | null>(null);\n const fit = settledFit !== null && settledFit.over === defaultView ? settledFit.view : defaultView;\n const settled = useLatest((moved: number) => {\n liveOpts?.onSettle?.(moved);\n if (controlled || moved === 0) return;\n const boxes = Array.from(source(), ({ node, pose }) => ({ ...node, pose }));\n setSettledFit({ view: fitDiagram(boxes, { width: boxWidth, height: boxHeight }, fitOpts, pagesBox), over: defaultView });\n });\n const live = useLiveLayout<RectPose>({\n ...liveOpts, scene, source, algorithm: run?.algorithm ?? 'force', onSettle: (moved) => settled.current(moved),\n });\n useEffect(() => {\n if (run !== null) live.restart();\n }, [run, live]);\n const canvasRef = useRef<SceneCanvasApi | null>(null);\n useDiagramApi(apiRef, canvasRef, scene, live, setRun);\n\n const selectedIds = useCallback(() => selection.get() as readonly string[], [selection]);\n const editing = useDiagramEditing({\n scene: scene as never, source, selected: selectedIds, mode: portMode ?? (onConnect !== undefined ? 'connect' : 'none'),\n onConnect, onReconnect, onEditRoute, onDelete, onEditLabel, onMoveLabel, onReorder, onResize, onEditContainer, onMove,\n connectBodies, canConnect, portOptions, ambient: extraAmbient,\n });\n useEffect(() => {\n const canvas = canvasRef.current;\n if (canvas === null) return;\n const disposers = editing.layers.map((layer) => canvas.registerLayer(layer));\n return () => disposers.forEach((dispose) => dispose());\n }, [editing.layers]);\n const moves = onMove !== undefined || onEditContainer !== undefined;\n const resizes = onResize !== undefined || onEditContainer !== undefined;\n const edits = moves || onConnect !== undefined || onReorder !== undefined || resizes || edgesPick;\n const features = useMemo(() => ['view', 'pick', ...(moves ? ['move' as const] : []), ...(resizes ? ['resize' as const] : [])] as const, [moves, resizes]);\n const selectTool = useMemo(() => ({ resize: { resizable: diagramResizable(scene) } }), [scene]);\n\n useRefit(canvasRef, fit);\n const overlayRef = useOverlayPlacement(canvasRef, scene, overlays);\n const fillsOn = [width === undefined ? 'fill-x' : '', height === undefined ? 'fill-y' : ''].join(' ').trim();\n return (\n <div ref={adoptViewRule} data-wzl-diagram={fillsOn} className={className}>\n <SceneCanvas\n ref={canvasRef}\n scene={scene}\n selection={selection}\n features={features}\n {...(resizes ? { selectTool } : {})}\n enableKeybindings={enableKeybindings ?? edits}\n ambient={editing.ambient}\n actions={editing.actions}\n onClick={onClick}\n {...(onHover ? { onHover } : {})}\n width={width}\n height={height}\n {...(fills ? { onResize: setMeasured } : {})}\n {...(defaultView ? { defaultView } : {})}\n {...(view ? { view } : {})}\n {...(onViewChange ? { onViewChange } : {})}\n {...(background ? { backgroundFill: background } : {})}\n {...(layers ? { layers } : {})}\n >\n <DropRules scene={scene} />\n </SceneCanvas>\n {overlays.map((o) => {\n const key = o.key ?? o.target;\n return <div key={key} ref={overlayRef(key)} data-wzl-diagram-overlay=\"\">{o.content}</div>;\n })}\n </div>\n );\n}\n\nconst NO_OVERLAYS: readonly never[] = [];\n\n/** Shapes drop only into containers and lanes, and lanes only into pools. A child of `<SceneCanvas>`, so its dep source registers after the canvas's own. */\nfunction DropRules({ scene }: { scene: Scene<DiagramSceneData, 'main', RectPose> }): null {\n const canDropInto = useMemo(() => diagramCanDropInto(scene as never), [scene]);\n useDepSource('canDropInto', () => canDropInto);\n return null;\n}\n\n/** What a `ref` on the view holds. */\nfunction useDiagramApi(\n apiRef: Ref<DiagramViewApi>,\n canvasRef: RefObject<SceneCanvasApi | null>,\n scene: Scene<DiagramSceneData, 'main', RectPose>,\n live: LiveLayout,\n setRun: (run: { algorithm: DiagramLayout }) => void,\n): void {\n useImperativeHandle(apiRef, () => ({\n layout: (algorithm = 'force') => setRun({ algorithm }),\n live,\n worldAt: (clientX, clientY) => {\n const [x, y] = canvasRef.current?.clientToWorld(clientX, clientY) ?? [clientX, clientY];\n return { x, y };\n },\n visible: () => {\n const canvas = canvasRef.current;\n const r = canvas?.element?.getBoundingClientRect();\n if (canvas == null || r === undefined || r.width === 0 || r.height === 0) return null;\n const [x0, y0] = canvas.clientToWorld(r.left, r.top);\n const [x1, y1] = canvas.clientToWorld(r.right, r.bottom);\n return { x: x0, y: y0, width: x1 - x0, height: y1 - y0 };\n },\n rectOf: (id) => {\n const canvas = canvasRef.current;\n const world = worldRectOf(scene, id);\n const r = canvas?.element?.getBoundingClientRect();\n if (canvas == null || world === null || r === undefined) return null;\n const rect = screenRectOf(world, canvas.getView());\n return { ...rect, x: rect.x + r.left, y: rect.y + r.top };\n },\n subscribeFrame: (fn) => canvasRef.current?.subscribeFrame(() => fn()) ?? (() => {}),\n }), [canvasRef, live, scene, setRun]);\n}\n\n/** Apply each new fit while the view is still the last one applied. */\nfunction useRefit(canvasRef: RefObject<SceneCanvasApi | null>, fit: View | undefined): void {\n const fitted = useRef(fit);\n useEffect(() => {\n const canvas = canvasRef.current;\n const was = fitted.current;\n if (canvas === null || fit === undefined || was === fit) return;\n // A view the user has panned or zoomed off its fit is theirs to keep.\n if (!sameView(canvas.getView(), was ?? IDENTITY)) return;\n fitted.current = fit;\n canvas.setView(fit);\n }, [canvasRef, fit]);\n}\n\n/** How `fitDiagram` frames a diagram in its box. */\nexport interface DiagramFit {\n minScale?: number;\n maxScale?: number;\n anchor?: 'center' | 'start';\n padding?: number;\n}\n\n/** The view `DiagramView` opens on: every node box and group box in view, never above\n * `maxScale` (default 1) and never below `minScale`. `extra` is further bounds to take in, such as the pages'. Takes specs, or a scene's\n * nodes at the poses they are drawn at. */\nexport function fitDiagram(\n specs: readonly { kind: string; pose: unknown; data: unknown }[],\n size: { width: number; height: number },\n fit: DiagramFit = {},\n extra?: { x: number; y: number; width: number; height: number },\n): View | undefined {\n const boxes = specs.filter((s) => s.kind === 'container' || diagramGroupOf(s) !== null).map((s) => s.pose as RectPose);\n if (extra !== undefined) boxes.push({ ...extra } as RectPose);\n if (boxes.length === 0) return undefined;\n const x = Math.min(...boxes.map((b) => b.x));\n const y = Math.min(...boxes.map((b) => b.y));\n const bounds = {\n x,\n y,\n width: Math.max(...boxes.map((b) => b.x + b.width)) - x,\n height: Math.max(...boxes.map((b) => b.y + b.height)) - y,\n };\n return fitViewToBounds(bounds, size, { x: 0, y: 0, scale: { x: 1, y: 1 } }, {\n maxScale: fit.maxScale ?? 1,\n ...(fit.minScale !== undefined ? { minScale: fit.minScale } : {}),\n ...(fit.anchor !== undefined ? { anchor: fit.anchor } : {}),\n ...(fit.padding !== undefined ? { padding: fit.padding } : {}),\n });\n}\n"]}