@statelyai/flow 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -169,7 +169,7 @@ The canonical data model is `VisualGraph` from `@statelyai/graph`. Flow extends
169
169
 
170
170
  <!-- flow entity types from src/types.ts -->
171
171
 
172
- - **`FlowNode`** — `VisualNode` + `{ kind, dx, dy, style, ports, autoSize, autoSizeAnchor, selectionBounds, resize, hidden, selectable, draggable, connectable, deletable, resizable }` for application-defined rendering kinds, drag offsets, DOM-owned sizing, anchor policy, optional marquee hit geometry, style overrides, resize constraints, and per-entity behavior. Keep the structural `type` equal to `"node"`; use `kind` for variants such as `state` or `annotation`.
172
+ - **`FlowNode`** — `VisualNode` + `{ kind, appearance, dx, dy, style, ports, autoSize, autoSizeAnchor, selectionBounds, resize, hidden, selectable, draggable, connectable, deletable, resizable }` for application-defined rendering kinds, drag offsets, DOM-owned sizing, anchor policy, optional marquee hit geometry, style overrides, resize constraints, and per-entity behavior. Keep the structural `type` equal to `"node"`; use `kind` for variants such as `state` or `annotation`.
173
173
  - **`FlowEdge`** — `VisualEdge` + `{ label, waypoints, svgPath, sourcePort, targetPort, kind, style, labelAnchor }` for edge labels, editable router via-points, exact SVG geometry, port binding, and edge styling. Canonical `VisualEdge.points` plus `routing` are an authoritative precomputed route and bypass Flow routers; an optional `svgPath` controls exact SVG paint while points remain authoritative for interaction geometry. Reconnects, node geometry updates, committed drags, and layout application clear stale precomputed routes; layout results may provide either interior router waypoints or a complete authoritative route. `label.autoSize` makes rendered DOM own transient label dimensions without overwriting authored fallback `width`/`height`; inherited edge `x/y/width/height` are reserved, while positioned edge content belongs on `label`.
174
174
  - **`FlowGraph`** — `VisualGraph` with `FlowNode[]` and `FlowEdge[]`
175
175
  - **`FlowEntityRef`** — descriptor for a node, edge, port, or block resolved by id. `FlowAddressable` is a deprecated alias.
@@ -188,6 +188,71 @@ culling, and toolbar anchors; surviving measurements remain stable across
188
188
  positions, so stale DOM measurements cannot move bounds or toolbar anchors back
189
189
  to a pre-drag location.
190
190
 
191
+ ## Entity appearances
192
+
193
+ <!-- appearance references and resolution policy from src/appearances.ts, src/types.ts, src/engine.ts -->
194
+
195
+ `kind` describes domain meaning; `type` remains `node`/`edge`. Use `appearance`
196
+ for reusable presentation, and projections for temporary selection, execution,
197
+ or search styling. Nodes and edge labels accept authored references:
198
+
199
+ ```ts
200
+ node.appearance = { name: 'asset', options: { contentPosition: 'above' } };
201
+ edge.label.appearance = { name: 'asset', options: { contentPosition: 'below' } };
202
+
203
+ const flow = createFlow({
204
+ graph,
205
+ engine: {
206
+ appearances: {
207
+ defaults: { node: { name: 'asset', options: { contentPosition: 'above' } } },
208
+ definitions: {
209
+ asset: ({ options }) => ({
210
+ renderer: 'asset', // defaults to the registered name
211
+ sizing: 'content', // 'fixed' uses authored dimensions
212
+ connection: {
213
+ bounds: { selector: '[data-asset-body]' },
214
+ sides: (options.sides as Direction[] | undefined) ?? (options.contentPosition === 'below'
215
+ ? ['left', 'right', 'top'] : ['left', 'right', 'bottom']),
216
+ },
217
+ }),
218
+ },
219
+ },
220
+ },
221
+ });
222
+ ```
223
+
224
+ Definitions are static policies or pure functions of `{ entity, options }`.
225
+ Defaults support `node` and `edgeLabel`; an entity reference replaces its host
226
+ default. Explicit `autoSize` and resize overrides retain precedence. Functions,
227
+ renderer registrations, defaults, and measurements stay outside serialized
228
+ graph data. Unknown names retain their saved references and fall back to legacy
229
+ sizing, renderers, and unrestricted connections.
230
+
231
+ `connection.bounds` accepts a node-local/label-local rectangle or `{ selector }`
232
+ for a DOM-measured border. Selectors are scoped to each entity wrapper and must
233
+ match exactly one descendant; missing, ambiguous, or invalid selectors fall back
234
+ to visual bounds. DOM adapters follow resizing, image loads, subtree changes (including caption
235
+ text edits), and layout-changing wrapper styles. Drag translations do not trigger
236
+ border remeasurement.
237
+ `connection.sides` limits attachment sides; `connection.ports` limits port names.
238
+ The nested fields take precedence over legacy `connectionBounds`, `sides`, and
239
+ `ports`. Without a selector, renderers can still use `data-flow-connection-bounds`.
240
+ Full visual bounds still own selection, culling, groups, and fit geometry;
241
+ connections use the separate border. `sides` limits body attachments and authored
242
+ ports; `ports` optionally limits permitted port names. Core applies this policy
243
+ to routing, previews, candidate selection, validation, and reconnection. Existing
244
+ edges referencing newly forbidden ports retain their saved identities and route
245
+ from a permitted body side. Empty `sides` disables new connections; saved edges
246
+ retain a fallback route. Edge labels apply bounds/sides to their existing
247
+ source→label→target route; they do not become independent connection targets.
248
+
249
+ Change host policies through `flow.configure({ engine: { appearances } })`.
250
+ Appearance switches and new DOM measurements invalidate affected routes, including
251
+ precomputed routes. Connection-constrained appearances route through the resolved policy even when
252
+ saved precomputed points exist; unconstrained appearances retain authoritative
253
+ route semantics. Custom routers receive resolved
254
+ bounds, directions, and endpoint points and must honor them.
255
+
191
256
  ## Graph projections
192
257
 
193
258
  <!-- graph projection types from src/projections.ts -->
@@ -1,5 +1,57 @@
1
1
  import { ExtractEvents } from "@xstate/store";
2
2
  import { EdgeRouting, EdgeRouting as EdgeRouting$1, EntityRect, Graph, GraphEdge, GraphNode, GraphPort, PortDirection, VisualEdge, VisualEdge as VisualEdge$1, VisualGraph, VisualGraphConfig, VisualNode, VisualNode as VisualNode$1, VisualPort, VisualPort as VisualPort$1 } from "@statelyai/graph";
3
+ //#region src/appearances.d.ts
4
+ /** Authored, serializable reference to a reusable presentation. */
5
+ type FlowAppearance = {
6
+ name: string;
7
+ options?: Record<string, unknown>;
8
+ };
9
+ type FlowAppearanceConnection = {
10
+ /** Local rectangle, or a single descendant selected within the rendered entity. */
11
+ bounds?: Rect | {
12
+ selector: string;
13
+ };
14
+ sides?: readonly Direction[];
15
+ ports?: readonly string[];
16
+ };
17
+ type FlowAppearancePolicy = {
18
+ connection?: FlowAppearanceConnection;
19
+ /** Renderer registry key; defaults to the appearance name. */
20
+ renderer?: string;
21
+ sizing?: "content" | "fixed";
22
+ /** Node-local / label-local connection rectangle, independent of visual bounds. */
23
+ connectionBounds?: Rect;
24
+ /** Restricts body attachment and ports, including gestures and routing. */
25
+ sides?: readonly Direction[];
26
+ /** Optional permitted authored port names. Port identities are never replaced. */
27
+ ports?: readonly string[];
28
+ };
29
+ type FlowAppearanceDefinition = FlowAppearancePolicy | ((args: {
30
+ entity: FlowNode | FlowEdgeLabel;
31
+ options: Readonly<Record<string, unknown>>;
32
+ }) => FlowAppearancePolicy);
33
+ type FlowAppearances = {
34
+ definitions?: Readonly<Record<string, FlowAppearanceDefinition>>;
35
+ defaults?: {
36
+ node?: FlowAppearance;
37
+ edgeLabel?: FlowAppearance;
38
+ };
39
+ };
40
+ type ResolvedFlowAppearance = FlowAppearancePolicy & {
41
+ reference: FlowAppearance | undefined;
42
+ registered: boolean;
43
+ autoSize: boolean;
44
+ connectionSelector?: string;
45
+ sides: readonly Direction[];
46
+ };
47
+ declare const appearanceSides: readonly Direction[];
48
+ declare function resolveAppearance(entity: FlowNode | FlowEdgeLabel, appearances?: FlowAppearances): ResolvedFlowAppearance;
49
+ /** Keyed by authored reference, so stale local measurements cannot follow appearance switches. */
50
+ declare function appearanceMeasurementId(id: string, appearance: ResolvedFlowAppearance): string;
51
+ declare function appearanceAllowsPort(node: FlowNode, portName: string, appearance: ResolvedFlowAppearance): boolean;
52
+ /** Preserve the usual facing side; otherwise choose the closest permitted side anchor. */
53
+ declare function appearanceDirection(bounds: Rect, other: Rect, preferred: Direction, sides: readonly Direction[]): Direction;
54
+ //#endregion
3
55
  //#region src/hierarchy.d.ts
4
56
  type GroupContentSide = 'top' | 'left' | 'bottom' | 'right';
5
57
  type GroupInsets = {
@@ -119,6 +171,7 @@ type FlowPort<TPortData = unknown> = VisualPort$1<TPortData> & {
119
171
  * Visual position = { x + dx, y + dy }
120
172
  */
121
173
  type FlowNodeAttributes = {
174
+ appearance?: FlowAppearance;
122
175
  /** Application-defined node/rendering kind. `type` remains the structural `node` discriminant. */
123
176
  kind?: string;
124
177
  dx?: number;
@@ -153,6 +206,9 @@ type FlowNodeAttributes = {
153
206
  height: number;
154
207
  /** Derived position correction excluded from serialization. */
155
208
  anchorOffset?: Point;
209
+ /** Derived sizing state; excluded from serialization. */
210
+ appearanceAutoSize?: boolean;
211
+ appearanceKey?: string;
156
212
  };
157
213
  /**
158
214
  * Marks this node as a group and configures how its bounds relate to its
@@ -188,6 +244,7 @@ type FlowNodeAttributes = {
188
244
  };
189
245
  /** Flow edge label — positioned like a node, lives on edge */
190
246
  type FlowEdgeLabel<TData = unknown> = {
247
+ appearance?: FlowAppearance;
191
248
  x: number;
192
249
  y: number;
193
250
  dx?: number;
@@ -682,6 +739,7 @@ type ConnectionValidationResult = boolean | {
682
739
  reason?: string;
683
740
  };
684
741
  type FlowEngineOptions = {
742
+ appearances?: FlowAppearances;
685
743
  /** Default edge router (default: bezierRouter) */
686
744
  edgeRouter?: EdgeRouter;
687
745
  /**
@@ -1421,6 +1479,9 @@ declare function createFlowEngine(store: FlowStore, initialOptions?: FlowEngineO
1421
1479
  } & Record<never, never>>;
1422
1480
  getContext: () => FlowStoreContext;
1423
1481
  setOptions: (partial: Partial<FlowEngineOptions>, replace?: boolean) => void;
1482
+ resolveAppearance: (entity: FlowNode | FlowEdgeLabel) => ResolvedFlowAppearance;
1483
+ isPortAllowed: (nodeOrId: FlowNode | string, portName: string) => boolean;
1484
+ getConnectionBounds: (id: string) => Rect | null;
1424
1485
  getNode: (id: string) => FlowNode | undefined;
1425
1486
  getEdge: (id: string) => FlowEdge | undefined;
1426
1487
  getEntity: (id: string) => FlowNode | FlowEdge | undefined;
@@ -2014,6 +2075,8 @@ declare const defaultFlowProfile: {
2014
2075
  */
2015
2076
  type BoxSelectionTest = (box: Rect, bounds: Rect) => boolean;
2016
2077
  type FlowStoreContext = {
2078
+ /** Host presentation policies; never serialized with authored graph data. */
2079
+ appearances?: FlowAppearances;
2017
2080
  graph: FlowGraph;
2018
2081
  parentNodeId: string | null;
2019
2082
  depth: number | null;
@@ -2127,6 +2190,7 @@ type FlowHighlightEntry = {
2127
2190
  * construct-only or have dedicated runtime events.
2128
2191
  */
2129
2192
  type FlowStoreOptions = {
2193
+ appearances?: FlowAppearances;
2130
2194
  minZoom?: number;
2131
2195
  maxZoom?: number;
2132
2196
  translateExtent?: [Point, Point] | null;
@@ -3505,4 +3569,4 @@ declare const readonlyConfig: Partial<FlowConfig>;
3505
3569
  */
3506
3570
  declare function resolveBehavior<TEntity, TState>(predicate: ((entity: TEntity, state: TState) => boolean) | false | undefined, entity: TEntity, state: TState, defaultValue?: boolean): boolean;
3507
3571
  //#endregion
3508
- export { type ActiveGraphProjection, type AnchorSpec, type AnchorTransform, type AnimateViewportOptions, type AutoLayoutState, type AvoidRouterOptions, type BehaviorPredicate, type BezierRouterOptions, type BoxSelectModeOptions, type BoxSelectionTest, CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, type CanvasState, type ComposedGraphProjectionAttrs, type ConnectEndTarget, type ConnectModeOptions, type ConnectionCandidate, type ConnectionCandidateOptions, type ConnectionCandidateSource, type ConnectionEndedEvent, type ConnectionPreviewData, type ConnectionPreviewGraphOptions, type ConnectionState, type ConnectionValidationContext, type ConnectionValidationResult, type CreateEdgeInput, type CreateFlowOptions, type CreateNodeInput, type Direction, type EdgeAdjacencyIndex, type EdgeDirection, type EdgePathData, type EdgePathOptions, type EdgeRouter, type EdgeRouterContext, type EdgeRouterGraph, type EdgeRouting, type EdgeSourceBoundsContext, type EntityRect, type EntityVisualState, type FitViewExclusion, type FitViewExclusionSide, type FitViewOptions, type FlowAbortSignal, type FlowAddressable, type FlowAutoSizeAnchor, type FlowCapabilityCommand, type FlowCapabilityResult, type FlowChangeSet, type FlowColorMode, type FlowCommand, type FlowCommitEvent, type FlowConfig, type FlowConfiguration, type FlowConfigureOptions, type FlowConnectMovedEvent, type FlowConnectStartedEvent, type FlowConnection, type FlowConnectionMode, type FlowConnectionOptions, type FlowConnectionsApi, type FlowContent, type FlowContentApi, type FlowContentInsertResult, type FlowController, type FlowCreateIdContext, type FlowDataSchema, type FlowDataSchemas, type FlowDataVersions, type FlowDragEndedEvent, type FlowDragMovedEvent, type FlowDragStartedEvent, type FlowEdge, type FlowEdgeAttributes, type FlowEdgeLabel, type FlowEdgePatch, type FlowEdgeStyle, type FlowEdgeUpdater, type FlowEdgesApi, type FlowEngine, type FlowEngineOptions, type FlowEntitiesDeletedEvent, type FlowEntityChangeNotifier, type FlowEntityChangeNotifierOptions, type FlowEntityGestureEvent, type FlowEntityRef, type FlowEntityUpdate, type FlowErrorEvent, type FlowEventObject, type FlowGestureModifiers, type FlowGraph, type FlowGraphChangedEvent, type FlowGraphHistoryPolicy, type FlowGraphRetentionPolicy, FlowGraphValidationError, type FlowHighlightEntry, type FlowHighlights, type FlowHighlightsApi, type FlowHistoryApi, type FlowInputEffects, type FlowInputEvent, type FlowInputMode, type FlowInputModeContext, type FlowInputModifiers, type FlowInputProfile, type FlowInputReaction, type FlowInputRuntime, type FlowInputRuntimeOptions, type FlowInputSessionHandlers, type FlowInputTarget, type FlowKeyBinding, type FlowKeyInputEvent, type FlowKeymap, type FlowLayoutApi, type FlowModeDefinition, type FlowNode, type FlowNodeAttributes, type FlowNodePatch, type FlowNodeUpdater, type FlowNodesApi, type FlowOrigin, type FlowPaneGestureEvent, type FlowPatch, type FlowPinchInputEvent, type FlowPointerInputEvent, type FlowPolicies, type FlowPort, type FlowProfile, type FlowProjectionListener, type FlowProjectionsApi, type FlowReplaceGraphOptions, type FlowResizeEndedEvent, type FlowResizeStartedEvent, type FlowResolvers, type FlowResult, type FlowRules, type FlowRuntimeSettings, type FlowSelectionAlignment, type FlowSelectionApi, type FlowSelectionChangedEvent, type FlowSelectionDistribution, type FlowSelectionDuplicateResult, type FlowSerialized, type FlowSessionResult, type FlowSettings, type FlowStore, type FlowStoreContext, type FlowStoreOptions, type FlowTransactionDraft, type FlowTransactionOptions, type FlowTransition, type FlowTransitions, type FlowTriggerCommand, type FlowTriggerName, type FlowUpdateEdgeEvent, type FlowUpdateNodeEvent, type FlowValidationIssue, type FlowViewApi, type FlowViewBoundaryEndpoints, type FlowViewChangedEvent, type FlowViewEndpoint, type FlowViewEntities, type FlowViewScope, type FlowViewSelectionPolicy, type FlowViewportApi, type FlowViewportChangedEvent, type FlowWheelInputEvent, type Graph, type GraphDecoration, type GraphEdge, type GraphEdgeAttrs, type GraphNode, type GraphNodeAttrs, type GraphPort, type GraphProjection, type GraphProjectionMapper, type GroupContentSide, type GroupGeometry, type GroupInsets, type GroupLayout, type InteractionMode, type LabelAnchor, type LayoutAlgorithm, type LayoutAnimationControls, type LayoutAnimationOptions, type LayoutApplyOptions, type LayoutDiagnostic, type LayoutEdgeRoute, type LayoutPositions, type LayoutRequestedEvent, type LayoutResult, type LayoutRunOptions, type LayoutRunResult, type MarkerType, type MinimapProjection, type MinimapProjectionOptions, type MinimapViewportCenterOptions, type PathData, type Point, type PortDirection, type ProposedConnection, type ReconnectModeOptions, type Rect, type RenderableEntitiesOptions, type ReparentDecision, type ReparentDropContext, type ReparentOptions, type ResizeConstraints, type ResizeHandle, type ResolvedFitViewExclusion, type SelectionMode, type ShapeHandler, type Side, type Size, type SnapLine, type SnapOptions, type SnapResult, type SpacingGuide, type StandardSchemaV1Like, type StepRouterOptions, type StyleOverrides, type ToolbarPlacement, type ToolbarPlacementInput, type Viewport, type ViewportAnimationCancelFrame, type ViewportAnimationControls, type ViewportAnimationFrame, type ViewportAnimationOptions, type VisualEdge, type VisualGraph, type VisualNode, type VisualPort, type WheelInteraction, type WheelInteractionOptions, animateViewport, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
3572
+ export { type ActiveGraphProjection, type AnchorSpec, type AnchorTransform, type AnimateViewportOptions, type AutoLayoutState, type AvoidRouterOptions, type BehaviorPredicate, type BezierRouterOptions, type BoxSelectModeOptions, type BoxSelectionTest, CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, type CanvasState, type ComposedGraphProjectionAttrs, type ConnectEndTarget, type ConnectModeOptions, type ConnectionCandidate, type ConnectionCandidateOptions, type ConnectionCandidateSource, type ConnectionEndedEvent, type ConnectionPreviewData, type ConnectionPreviewGraphOptions, type ConnectionState, type ConnectionValidationContext, type ConnectionValidationResult, type CreateEdgeInput, type CreateFlowOptions, type CreateNodeInput, type Direction, type EdgeAdjacencyIndex, type EdgeDirection, type EdgePathData, type EdgePathOptions, type EdgeRouter, type EdgeRouterContext, type EdgeRouterGraph, type EdgeRouting, type EdgeSourceBoundsContext, type EntityRect, type EntityVisualState, type FitViewExclusion, type FitViewExclusionSide, type FitViewOptions, type FlowAbortSignal, type FlowAddressable, FlowAppearance, FlowAppearanceConnection, FlowAppearanceDefinition, FlowAppearancePolicy, FlowAppearances, type FlowAutoSizeAnchor, type FlowCapabilityCommand, type FlowCapabilityResult, type FlowChangeSet, type FlowColorMode, type FlowCommand, type FlowCommitEvent, type FlowConfig, type FlowConfiguration, type FlowConfigureOptions, type FlowConnectMovedEvent, type FlowConnectStartedEvent, type FlowConnection, type FlowConnectionMode, type FlowConnectionOptions, type FlowConnectionsApi, type FlowContent, type FlowContentApi, type FlowContentInsertResult, type FlowController, type FlowCreateIdContext, type FlowDataSchema, type FlowDataSchemas, type FlowDataVersions, type FlowDragEndedEvent, type FlowDragMovedEvent, type FlowDragStartedEvent, type FlowEdge, type FlowEdgeAttributes, type FlowEdgeLabel, type FlowEdgePatch, type FlowEdgeStyle, type FlowEdgeUpdater, type FlowEdgesApi, type FlowEngine, type FlowEngineOptions, type FlowEntitiesDeletedEvent, type FlowEntityChangeNotifier, type FlowEntityChangeNotifierOptions, type FlowEntityGestureEvent, type FlowEntityRef, type FlowEntityUpdate, type FlowErrorEvent, type FlowEventObject, type FlowGestureModifiers, type FlowGraph, type FlowGraphChangedEvent, type FlowGraphHistoryPolicy, type FlowGraphRetentionPolicy, FlowGraphValidationError, type FlowHighlightEntry, type FlowHighlights, type FlowHighlightsApi, type FlowHistoryApi, type FlowInputEffects, type FlowInputEvent, type FlowInputMode, type FlowInputModeContext, type FlowInputModifiers, type FlowInputProfile, type FlowInputReaction, type FlowInputRuntime, type FlowInputRuntimeOptions, type FlowInputSessionHandlers, type FlowInputTarget, type FlowKeyBinding, type FlowKeyInputEvent, type FlowKeymap, type FlowLayoutApi, type FlowModeDefinition, type FlowNode, type FlowNodeAttributes, type FlowNodePatch, type FlowNodeUpdater, type FlowNodesApi, type FlowOrigin, type FlowPaneGestureEvent, type FlowPatch, type FlowPinchInputEvent, type FlowPointerInputEvent, type FlowPolicies, type FlowPort, type FlowProfile, type FlowProjectionListener, type FlowProjectionsApi, type FlowReplaceGraphOptions, type FlowResizeEndedEvent, type FlowResizeStartedEvent, type FlowResolvers, type FlowResult, type FlowRules, type FlowRuntimeSettings, type FlowSelectionAlignment, type FlowSelectionApi, type FlowSelectionChangedEvent, type FlowSelectionDistribution, type FlowSelectionDuplicateResult, type FlowSerialized, type FlowSessionResult, type FlowSettings, type FlowStore, type FlowStoreContext, type FlowStoreOptions, type FlowTransactionDraft, type FlowTransactionOptions, type FlowTransition, type FlowTransitions, type FlowTriggerCommand, type FlowTriggerName, type FlowUpdateEdgeEvent, type FlowUpdateNodeEvent, type FlowValidationIssue, type FlowViewApi, type FlowViewBoundaryEndpoints, type FlowViewChangedEvent, type FlowViewEndpoint, type FlowViewEntities, type FlowViewScope, type FlowViewSelectionPolicy, type FlowViewportApi, type FlowViewportChangedEvent, type FlowWheelInputEvent, type Graph, type GraphDecoration, type GraphEdge, type GraphEdgeAttrs, type GraphNode, type GraphNodeAttrs, type GraphPort, type GraphProjection, type GraphProjectionMapper, type GroupContentSide, type GroupGeometry, type GroupInsets, type GroupLayout, type InteractionMode, type LabelAnchor, type LayoutAlgorithm, type LayoutAnimationControls, type LayoutAnimationOptions, type LayoutApplyOptions, type LayoutDiagnostic, type LayoutEdgeRoute, type LayoutPositions, type LayoutRequestedEvent, type LayoutResult, type LayoutRunOptions, type LayoutRunResult, type MarkerType, type MinimapProjection, type MinimapProjectionOptions, type MinimapViewportCenterOptions, type PathData, type Point, type PortDirection, type ProposedConnection, type ReconnectModeOptions, type Rect, type RenderableEntitiesOptions, type ReparentDecision, type ReparentDropContext, type ReparentOptions, type ResizeConstraints, type ResizeHandle, type ResolvedFitViewExclusion, ResolvedFlowAppearance, type SelectionMode, type ShapeHandler, type Side, type Size, type SnapLine, type SnapOptions, type SnapResult, type SpacingGuide, type StandardSchemaV1Like, type StepRouterOptions, type StyleOverrides, type ToolbarPlacement, type ToolbarPlacementInput, type Viewport, type ViewportAnimationCancelFrame, type ViewportAnimationControls, type ViewportAnimationFrame, type ViewportAnimationOptions, type VisualEdge, type VisualGraph, type VisualNode, type VisualPort, type WheelInteraction, type WheelInteractionOptions, animateViewport, appearanceAllowsPort, appearanceDirection, appearanceMeasurementId, appearanceSides, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveAppearance, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
package/dist/esm/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createStore } from "@xstate/store";
2
2
  import { undoRedo } from "@xstate/store/undo";
3
- import { current, enableMapSet, isDraft, produce } from "immer";
3
+ import { castDraft, current, enableMapSet, isDraft, produce } from "immer";
4
4
  import { getPatches } from "@statelyai/graph";
5
5
  //#region src/marker.ts
6
6
  const BUILT_IN_MARKERS = /* @__PURE__ */ new Set([
@@ -147,6 +147,58 @@ function toDecorationArray(value) {
147
147
  return Array.isArray(value) ? [...value] : [value];
148
148
  }
149
149
  //#endregion
150
+ //#region src/appearances.ts
151
+ const appearanceSides = [
152
+ "top",
153
+ "right",
154
+ "bottom",
155
+ "left"
156
+ ];
157
+ function resolveAppearance(entity, appearances = {}) {
158
+ const reference = entity.appearance ?? appearances.defaults?.["type" in entity ? "node" : "edgeLabel"];
159
+ const definition = reference && Object.prototype.hasOwnProperty.call(appearances.definitions ?? {}, reference.name) ? appearances.definitions?.[reference.name] : void 0;
160
+ const policy = typeof definition === "function" ? definition({
161
+ entity,
162
+ options: reference?.options ?? {}
163
+ }) : definition ?? {};
164
+ return {
165
+ ...policy,
166
+ reference,
167
+ registered: definition !== void 0,
168
+ renderer: definition ? policy.renderer ?? reference?.name : void 0,
169
+ autoSize: entity.autoSize ?? policy.sizing === "content",
170
+ connectionBounds: policy.connection?.bounds && !("selector" in policy.connection.bounds) ? policy.connection.bounds : policy.connection?.bounds ? void 0 : policy.connectionBounds,
171
+ connectionSelector: policy.connection?.bounds && "selector" in policy.connection.bounds ? policy.connection.bounds.selector : void 0,
172
+ sides: policy.connection?.sides ?? policy.sides ?? appearanceSides,
173
+ ports: policy.connection?.ports ?? policy.ports
174
+ };
175
+ }
176
+ /** Keyed by authored reference, so stale local measurements cannot follow appearance switches. */
177
+ function appearanceMeasurementId(id, appearance) {
178
+ return JSON.stringify([
179
+ "flow-appearance-boundary",
180
+ id,
181
+ appearance.reference ?? null,
182
+ appearance.connectionSelector ?? null
183
+ ]);
184
+ }
185
+ function appearanceAllowsPort(node, portName, appearance) {
186
+ const port = node.ports?.find((candidate) => candidate.name === portName);
187
+ const side = port?.side;
188
+ return !!port && (side ? appearance.sides.includes(side) : appearance.sides.length === 4) && (!appearance.ports || appearance.ports.includes(portName));
189
+ }
190
+ /** Preserve the usual facing side; otherwise choose the closest permitted side anchor. */
191
+ function appearanceDirection(bounds, other, preferred, sides) {
192
+ if (sides.includes(preferred)) return preferred;
193
+ const cx = other.x + other.width / 2, cy = other.y + other.height / 2;
194
+ const distance = (side) => {
195
+ const x = side === "left" ? bounds.x : side === "right" ? bounds.x + bounds.width : bounds.x + bounds.width / 2;
196
+ const y = side === "top" ? bounds.y : side === "bottom" ? bounds.y + bounds.height : bounds.y + bounds.height / 2;
197
+ return Math.hypot(cx - x, cy - y);
198
+ };
199
+ return sides.reduce((best, side) => distance(side) < distance(best) ? side : best, sides[0] ?? preferred);
200
+ }
201
+ //#endregion
150
202
  //#region src/profile.ts
151
203
  function defineFlowProfile(profile) {
152
204
  return profile;
@@ -545,9 +597,11 @@ const resolvedPosition = visualPosition;
545
597
  * Authored `width/height` are never mutated — measured size lives on
546
598
  * `node.measured`, so this is the single place that reconciles the two. */
547
599
  function resolvedSize(node) {
600
+ const measuredAppearance = node.measured?.appearanceKey !== void 0 && node.measured.appearanceKey === JSON.stringify(node.appearance ?? null);
601
+ const autoSize = node.autoSize ?? (measuredAppearance && node.measured?.appearanceAutoSize);
548
602
  return {
549
- width: node.style?.customWidth ?? (node.autoSize ? node.measured?.width ?? node.width : node.width),
550
- height: node.style?.customHeight ?? (node.autoSize ? node.measured?.height ?? node.height : node.height)
603
+ width: node.style?.customWidth ?? (autoSize ? node.measured?.width ?? node.width : node.width),
604
+ height: node.style?.customHeight ?? (autoSize ? node.measured?.height ?? node.height : node.height)
551
605
  };
552
606
  }
553
607
  function visualBounds(node) {
@@ -2289,6 +2343,15 @@ function validateEdgeData(edge, index, schemas, issues) {
2289
2343
  edge.label.data = validateData(edge.label.data, schemas?.label, `$.graph.edges[${index}].label.data`, issues);
2290
2344
  }
2291
2345
  }
2346
+ function validateAppearance(value, path, issues) {
2347
+ if (value === void 0) return;
2348
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.name !== "string" || !value.name.length) {
2349
+ issue(issues, "invalid_appearance", path, "expected an appearance with a non-empty name");
2350
+ return;
2351
+ }
2352
+ const options = value.options;
2353
+ if (options !== void 0 && (!options || typeof options !== "object" || Array.isArray(options))) issue(issues, "invalid_appearance", `${path}.options`, "expected an options object");
2354
+ }
2292
2355
  function validateAndCloneGraph(input, schemas) {
2293
2356
  const issues = [];
2294
2357
  const cloned = cloneJsonValue(input, "$.graph", issues, /* @__PURE__ */ new Set());
@@ -2315,6 +2378,7 @@ function validateAndCloneGraph(input, schemas) {
2315
2378
  nodesById.set(node.id, node);
2316
2379
  }
2317
2380
  validateFiniteGeometry(node, path, issues);
2381
+ validateAppearance(node.appearance, `${path}.appearance`, issues);
2318
2382
  validateAutoSizeAnchor(node.autoSizeAnchor, `${path}.autoSizeAnchor`, issues);
2319
2383
  validateNodeData(node, index, schemas?.node, issues);
2320
2384
  if (node.ports !== void 0) {
@@ -2361,6 +2425,7 @@ function validateAndCloneGraph(input, schemas) {
2361
2425
  const node = nodesById.get(nodeId);
2362
2426
  if (!Array.isArray(node?.ports) || !node.ports.some((port) => !!port && typeof port === "object" && !Array.isArray(port) && port.name === portName)) issue(issues, "missing_port", `${path}.${key}`, `port "${portName}" does not exist on node "${nodeId}"`);
2363
2427
  }
2428
+ if (edge.label && typeof edge.label === "object") validateAppearance(edge.label.appearance, `${path}.label.appearance`, issues);
2364
2429
  if (edge.label && typeof edge.label === "object" && !Array.isArray(edge.label)) validateFiniteGeometry(edge.label, `${path}.label`, issues);
2365
2430
  if (edge.waypoints !== void 0) if (!Array.isArray(edge.waypoints)) issue(issues, "invalid_waypoints", `${path}.waypoints`, "expected an array");
2366
2431
  else edge.waypoints.forEach((point, pointIndex) => {
@@ -2448,6 +2513,7 @@ function invalidateAuthoritativeEdgePath(edge) {
2448
2513
  }
2449
2514
  /** Whether a node mutation changes any position an incident edge can anchor to. */
2450
2515
  function nodeEndpointGeometryChanged(previous, next) {
2516
+ if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) return true;
2451
2517
  const previousBounds = resolvedBounds(previous);
2452
2518
  const nextBounds = resolvedBounds(next);
2453
2519
  if (previousBounds.x !== nextBounds.x || previousBounds.y !== nextBounds.y || previousBounds.width !== nextBounds.width || previousBounds.height !== nextBounds.height) return true;
@@ -3230,6 +3296,7 @@ function createFlowStore(initialGraph = {
3230
3296
  const initialMode = getMode(profile, options.mode ?? profile.defaultMode);
3231
3297
  const initialContext = {
3232
3298
  graph: validatedInitialGraph,
3299
+ appearances: options.appearances,
3233
3300
  parentNodeId: null,
3234
3301
  depth: null,
3235
3302
  viewport: createViewport(),
@@ -3367,7 +3434,15 @@ function createFlowStore(initialGraph = {
3367
3434
  });
3368
3435
  return;
3369
3436
  }
3370
- draft.graph.nodes[index] = next;
3437
+ draft.graph.nodes[index] = { ...next };
3438
+ if (JSON.stringify(previous.appearance) !== JSON.stringify(next.appearance)) {
3439
+ draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous, ctx.appearances)));
3440
+ const node = draft.graph.nodes[index];
3441
+ node.x -= previous.measured?.anchorOffset?.x ?? 0;
3442
+ node.y -= previous.measured?.anchorOffset?.y ?? 0;
3443
+ delete node.measured;
3444
+ draft.measurements.delete(node.id);
3445
+ }
3371
3446
  if (nodeEndpointGeometryChanged(previous, next)) invalidatePathsForNodeGeometry(draft, /* @__PURE__ */ new Set([event.id]));
3372
3447
  enqueue.emit.graphChanged({
3373
3448
  graph: snapshotGraph(draft.graph),
@@ -3473,6 +3548,11 @@ function createFlowStore(initialGraph = {
3473
3548
  return;
3474
3549
  }
3475
3550
  draft.graph.edges[index] = next;
3551
+ if (JSON.stringify(previous.label?.appearance) !== JSON.stringify(next.label?.appearance)) {
3552
+ if (previous.label) draft.measurements.delete(appearanceMeasurementId(previous.id, resolveAppearance(previous.label, ctx.appearances)));
3553
+ draft.measurements.delete(previous.id);
3554
+ invalidateAuthoritativeEdgePath(draft.graph.edges[index]);
3555
+ }
3476
3556
  enqueue.emit.graphChanged({
3477
3557
  graph: snapshotGraph(draft.graph),
3478
3558
  event: createEventObject("updateEdge", event)
@@ -3551,7 +3631,25 @@ function createFlowStore(initialGraph = {
3551
3631
  },
3552
3632
  replaceGraph: (ctx, event, enqueue) => event.graphChanged === false && event.retention !== "reset" && !event.layoutAnimationOffsets ? ctx : produce(ctx, (draft) => {
3553
3633
  const previousSelection = new Set(draft.selection);
3554
- draft.graph = event.graph;
3634
+ const previousNodes = new Map(ctx.graph.nodes.map((node) => [node.id, node]));
3635
+ const changedAppearances = /* @__PURE__ */ new Set();
3636
+ draft.graph = {
3637
+ ...event.graph,
3638
+ nodes: event.graph.nodes.map((node) => {
3639
+ const previous = previousNodes.get(node.id);
3640
+ if (!previous || JSON.stringify(previous.appearance) === JSON.stringify(node.appearance)) return node;
3641
+ const next = {
3642
+ ...node,
3643
+ x: node.x - (node.measured?.anchorOffset?.x ?? 0),
3644
+ y: node.y - (node.measured?.anchorOffset?.y ?? 0)
3645
+ };
3646
+ delete next.measured;
3647
+ draft.measurements.delete(node.id);
3648
+ changedAppearances.add(node.id);
3649
+ return next;
3650
+ })
3651
+ };
3652
+ if (changedAppearances.size) invalidatePathsForNodeGeometry(draft, changedAppearances);
3555
3653
  draft.layoutAnimation = event.layoutAnimationOffsets?.size ? {
3556
3654
  status: "running",
3557
3655
  offsets: new Map(event.layoutAnimationOffsets)
@@ -3592,11 +3690,15 @@ function createFlowStore(initialGraph = {
3592
3690
  draft.focusedEntityId = draft.focusedEntityId && ids.has(draft.focusedEntityId) ? draft.focusedEntityId : null;
3593
3691
  draft.parentNodeId = draft.parentNodeId && nodeIds.has(draft.parentNodeId) ? draft.parentNodeId : null;
3594
3692
  const measurementIds = new Set(ids);
3595
- for (const node of draft.graph.nodes) for (const port of node.ports ?? []) {
3596
- const portId = port.id;
3597
- if (portId) measurementIds.add(portId);
3598
- measurementIds.add(`${node.id}:${port.name}`);
3693
+ for (const node of draft.graph.nodes) {
3694
+ measurementIds.add(appearanceMeasurementId(node.id, resolveAppearance(node, ctx.appearances)));
3695
+ for (const port of node.ports ?? []) {
3696
+ const portId = port.id;
3697
+ if (portId) measurementIds.add(portId);
3698
+ measurementIds.add(`${node.id}:${port.name}`);
3699
+ }
3599
3700
  }
3701
+ for (const edge of draft.graph.edges) if (edge.label) measurementIds.add(appearanceMeasurementId(edge.id, resolveAppearance(edge.label, ctx.appearances)));
3600
3702
  for (const id of draft.measurements.keys()) if (!measurementIds.has(id)) draft.measurements.delete(id);
3601
3703
  if (draft.draggedEntityId && !ids.has(draft.draggedEntityId)) {
3602
3704
  draft.draggedEntityId = null;
@@ -4172,6 +4274,7 @@ function createFlowStore(initialGraph = {
4172
4274
  }),
4173
4275
  configure: (ctx, event) => {
4174
4276
  if (event.profile) profile = event.profile;
4277
+ const previousAppearances = ctx.appearances;
4175
4278
  return produce(ctx, (draft) => {
4176
4279
  if (event.minZoom !== void 0) draft.minZoom = Math.max(.01, event.minZoom);
4177
4280
  if (event.maxZoom !== void 0) draft.maxZoom = Math.max(draft.minZoom, event.maxZoom);
@@ -4195,6 +4298,24 @@ function createFlowStore(initialGraph = {
4195
4298
  if (event.selectionMode !== void 0) draft.selectionMode = event.selectionMode;
4196
4299
  if (event.labelAnchor !== void 0) draft.labelAnchor = event.labelAnchor;
4197
4300
  if (event.profile || event.mode !== void 0) draft.mode = getMode(profile, event.mode ?? draft.mode);
4301
+ if (event.appearances !== void 0 && event.appearances !== previousAppearances) {
4302
+ draft.appearances = castDraft(event.appearances);
4303
+ const appearanceNodes = /* @__PURE__ */ new Set();
4304
+ for (const node of draft.graph.nodes) {
4305
+ if (!resolveAppearance(node, previousAppearances).reference && !resolveAppearance(node, draft.appearances).reference) continue;
4306
+ node.x -= node.measured?.anchorOffset?.x ?? 0;
4307
+ node.y -= node.measured?.anchorOffset?.y ?? 0;
4308
+ delete node.measured;
4309
+ draft.measurements.delete(node.id);
4310
+ appearanceNodes.add(node.id);
4311
+ }
4312
+ if (appearanceNodes.size) invalidatePathsForNodeGeometry(draft, appearanceNodes);
4313
+ for (const edge of draft.graph.edges) if (edge.label && (resolveAppearance(edge.label, previousAppearances).reference || resolveAppearance(edge.label, draft.appearances).reference)) {
4314
+ draft.measurements.delete(edge.id);
4315
+ invalidateAuthoritativeEdgePath(edge);
4316
+ }
4317
+ for (const id of draft.measurements.keys()) if (id.startsWith("[\"flow-appearance-boundary\",")) draft.measurements.delete(id);
4318
+ }
4198
4319
  draft.configRevision += 1;
4199
4320
  });
4200
4321
  },
@@ -4655,11 +4776,14 @@ function createFlowStore(initialGraph = {
4655
4776
  }
4656
4777
  }
4657
4778
  return produce(ctx, (draft) => {
4779
+ const boundaryNodes = /* @__PURE__ */ new Set();
4780
+ const candidateNodes = /* @__PURE__ */ new Set();
4658
4781
  for (const measurement of event.measurements) {
4659
4782
  const nodeIndex = nodeIndices.get(measurement.id);
4660
4783
  if (nodeIndex !== void 0) {
4661
4784
  const node = draft.graph.nodes[nodeIndex];
4662
- if (node.autoSize) {
4785
+ candidateNodes.add(node.id);
4786
+ if (resolveAppearance(node, draft.appearances).autoSize) {
4663
4787
  const previousSize = resolvedSize(node);
4664
4788
  const previousOffset = node.measured?.anchorOffset ?? {
4665
4789
  x: 0,
@@ -4685,10 +4809,12 @@ function createFlowStore(initialGraph = {
4685
4809
  height: measurement.rect.height
4686
4810
  };
4687
4811
  const existing = draft.measurements.get(measurement.id);
4688
- if (delta.x === 0 && delta.y === 0 && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4812
+ if (delta.x === 0 && delta.y === 0 && node.measured?.appearanceKey === JSON.stringify(node.appearance ?? null) && node.measured?.width === measurement.rect.width && node.measured?.height === measurement.rect.height && previousOffset.x === anchorOffset.x && previousOffset.y === anchorOffset.y && existing?.x === normalizedRect.x && existing.y === normalizedRect.y && existing.width === normalizedRect.width && existing.height === normalizedRect.height) continue;
4689
4813
  node.measured = {
4690
4814
  width: measurement.rect.width,
4691
4815
  height: measurement.rect.height,
4816
+ appearanceAutoSize: resolveAppearance(node, draft.appearances).autoSize,
4817
+ appearanceKey: JSON.stringify(node.appearance ?? null),
4692
4818
  ...anchorOffset.x !== 0 || anchorOffset.y !== 0 ? { anchorOffset } : {}
4693
4819
  };
4694
4820
  node.x += delta.x;
@@ -4698,10 +4824,17 @@ function createFlowStore(initialGraph = {
4698
4824
  continue;
4699
4825
  }
4700
4826
  draft.measurements.set(measurement.id, measurement.rect);
4827
+ if (measurement.id.startsWith("[\"flow-appearance-boundary\",")) {
4828
+ const [, id] = JSON.parse(measurement.id);
4829
+ if (nodeIndices.has(id)) boundaryNodes.add(id);
4830
+ const labelIndex = edgeIndices.get(id);
4831
+ if (labelIndex !== void 0) invalidateAuthoritativeEdgePath(draft.graph.edges[labelIndex]);
4832
+ }
4701
4833
  const edgeIndex = edgeIndices.get(measurement.id);
4702
4834
  const edge = edgeIndex === void 0 ? void 0 : draft.graph.edges[edgeIndex];
4703
4835
  if (edge?.label) {
4704
- if (!edge.label.autoSize) {
4836
+ if (resolveAppearance(edge.label, draft.appearances).registered) invalidateAuthoritativeEdgePath(edge);
4837
+ if (!resolveAppearance(edge.label, draft.appearances).autoSize && !resolveAppearance(edge.label, draft.appearances).registered && !edge.label.appearance) {
4705
4838
  edge.label.width = measurement.rect.width;
4706
4839
  edge.label.height = measurement.rect.height;
4707
4840
  }
@@ -4710,6 +4843,7 @@ function createFlowStore(initialGraph = {
4710
4843
  const portTarget = portIndices.get(measurement.id);
4711
4844
  if (portTarget) {
4712
4845
  const candidate = draft.graph.nodes[portTarget.nodeIndex];
4846
+ candidateNodes.add(candidate.id);
4713
4847
  const port = candidate.ports?.[portTarget.portIndex];
4714
4848
  if (!port) continue;
4715
4849
  const origin = snappedBounds(candidate, draft.snapToGrid ? draft.snapGrid : null);
@@ -4719,10 +4853,25 @@ function createFlowStore(initialGraph = {
4719
4853
  port.height = measurement.rect.height;
4720
4854
  }
4721
4855
  }
4856
+ for (const id of candidateNodes) {
4857
+ const index = nodeIndices.get(id);
4858
+ if (nodeEndpointGeometryChanged(ctx.graph.nodes[index], draft.graph.nodes[index])) boundaryNodes.add(id);
4859
+ }
4860
+ if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4722
4861
  });
4723
4862
  },
4724
4863
  removeMeasurements: (ctx, event) => produce(ctx, (draft) => {
4725
- for (const id of event.ids) draft.measurements.delete(id);
4864
+ const boundaryNodes = /* @__PURE__ */ new Set();
4865
+ for (const id of event.ids) {
4866
+ if (!draft.measurements.delete(id)) continue;
4867
+ if (id.startsWith("[\"flow-appearance-boundary\",")) {
4868
+ const [, entityId] = JSON.parse(id);
4869
+ boundaryNodes.add(entityId);
4870
+ const edge = draft.graph.edges.find((candidate) => candidate.id === entityId);
4871
+ if (edge) invalidateAuthoritativeEdgePath(edge);
4872
+ }
4873
+ }
4874
+ if (boundaryNodes.size) invalidatePathsForNodeGeometry(draft, boundaryNodes);
4726
4875
  }),
4727
4876
  bakeLabelPositions: (ctx, event, enqueue) => produce(ctx, (draft) => {
4728
4877
  for (const [edgeId, center] of event.positions) {
@@ -4766,7 +4915,7 @@ function createFlowStore(initialGraph = {
4766
4915
  }
4767
4916
  function areNodesMeasured(context) {
4768
4917
  return context.graph.nodes.every((node) => {
4769
- if (node.hidden || !node.autoSize) return true;
4918
+ if (node.hidden || !resolveAppearance(node, context.appearances).autoSize) return true;
4770
4919
  return context.measurements.has(node.id) || node.measured !== void 0;
4771
4920
  });
4772
4921
  }
@@ -5093,7 +5242,77 @@ function createFlowEngine(store, initialOptions = {}) {
5093
5242
  }
5094
5243
  return index;
5095
5244
  }
5245
+ let appearanceSettings = ctx().appearances;
5246
+ let appearanceCache = /* @__PURE__ */ new WeakMap();
5247
+ let sizedNodeCache = /* @__PURE__ */ new WeakMap();
5248
+ if (initialOptions.appearances && initialOptions.appearances !== appearanceSettings) store.trigger.configure({ appearances: initialOptions.appearances });
5249
+ function appearanceFor(entity) {
5250
+ if (appearanceSettings !== ctx().appearances) {
5251
+ appearanceSettings = ctx().appearances;
5252
+ appearanceCache = /* @__PURE__ */ new WeakMap();
5253
+ sizedNodeCache = /* @__PURE__ */ new WeakMap();
5254
+ }
5255
+ let appearance = appearanceCache.get(entity);
5256
+ if (!appearance) {
5257
+ appearance = resolveAppearance(entity, appearanceSettings);
5258
+ appearanceCache.set(entity, appearance);
5259
+ }
5260
+ return appearance;
5261
+ }
5262
+ function sizedNode(node) {
5263
+ const autoSize = appearanceFor(node).autoSize;
5264
+ const cached = sizedNodeCache.get(node);
5265
+ if (cached) return cached;
5266
+ const measured = node.measured?.appearanceKey !== void 0 && node.measured.appearanceKey !== JSON.stringify(node.appearance ?? null) ? void 0 : node.measured;
5267
+ const sized = (node.autoSize === autoSize || !autoSize && !node.autoSize && !node.measured?.appearanceAutoSize) && measured === node.measured ? node : {
5268
+ ...node,
5269
+ autoSize,
5270
+ measured
5271
+ };
5272
+ sizedNodeCache.set(node, sized);
5273
+ return sized;
5274
+ }
5275
+ const resolvedSize$1 = (node) => resolvedSize(sizedNode(node));
5276
+ const resolvedBounds$1 = (node) => resolvedBounds(sizedNode(node));
5277
+ const snappedBounds$1 = (node, grid, offset) => snappedBounds(sizedNode(node), grid, offset);
5278
+ const resolvedEdgeLabelSize$1 = (label, measurement) => resolvedEdgeLabelSize({
5279
+ ...label,
5280
+ autoSize: appearanceFor(label).autoSize
5281
+ }, measurement);
5282
+ function connectionBounds(id, entity, visual) {
5283
+ const appearance = appearanceFor(entity);
5284
+ const local = appearance.connectionBounds ?? (appearance.registered ? ctx().measurements.get(appearanceMeasurementId(id, appearance)) : void 0);
5285
+ return local ? {
5286
+ ...local,
5287
+ x: visual.x + local.x,
5288
+ y: visual.y + local.y
5289
+ } : visual;
5290
+ }
5291
+ /** A constrained presentation must not be bypassed by graph-owned route points. */
5292
+ function resolvedAuthoritativePath(edge, source = getNode(edge.sourceId), target = getNode(edge.targetId)) {
5293
+ const path = authoritativeEdgePath(edge);
5294
+ if (!path) return null;
5295
+ const constrained = (id, entity) => {
5296
+ if (!entity) return false;
5297
+ const appearance = appearanceFor(entity);
5298
+ return !!appearance.connectionBounds || appearance.ports !== void 0 || [
5299
+ "top",
5300
+ "right",
5301
+ "bottom",
5302
+ "left"
5303
+ ].some((side) => !appearance.sides.includes(side)) || appearance.registered && ctx().measurements.has(appearanceMeasurementId(id, appearance));
5304
+ };
5305
+ return constrained(edge.sourceId, source) || constrained(edge.targetId, target) || constrained(edge.id, edge.label ?? void 0) ? null : path;
5306
+ }
5307
+ function connectionDirection(entity, bounds, other) {
5308
+ return appearanceDirection(bounds, other, bestDirection(bounds, other), appearanceFor(entity).sides);
5309
+ }
5310
+ function isPortAllowed(nodeOrId, portName) {
5311
+ const node = typeof nodeOrId === "string" ? getNode(nodeOrId) : nodeOrId;
5312
+ return !!node && appearanceAllowsPort(node, portName, appearanceFor(node));
5313
+ }
5096
5314
  function setOptions(partial, replace = false) {
5315
+ const previousAppearances = engineOptions.appearances;
5097
5316
  engineOptions = replace ? { ...partial } : {
5098
5317
  ...engineOptions,
5099
5318
  ...partial,
@@ -5124,6 +5343,8 @@ function createFlowEngine(store, initialOptions = {}) {
5124
5343
  nodeIndexCache = /* @__PURE__ */ new WeakMap();
5125
5344
  obstacleCache = /* @__PURE__ */ new WeakMap();
5126
5345
  edgePathMemo.clear();
5346
+ const appearances = replace ? partial.appearances ?? {} : partial.appearances;
5347
+ if (appearances !== void 0 && appearances !== previousAppearances) store.trigger.configure({ appearances });
5127
5348
  }
5128
5349
  function ownerObstacles(owner, c) {
5129
5350
  let byOwner = obstacleCache.get(c);
@@ -5194,8 +5415,8 @@ function createFlowEngine(store, initialOptions = {}) {
5194
5415
  return geometry;
5195
5416
  }
5196
5417
  function computeGroupGeometryRaw(c, node, visiting, excludeChildren, visualSnap) {
5197
- const contentSize = resolvedSize(node);
5198
- if (node.group.type === "fixed") return fixedGroupGeometry(withLayoutOffset(resolvedBounds(node), node.id, c), node.group.contentSize ?? {
5418
+ const contentSize = resolvedSize$1(node);
5419
+ if (node.group.type === "fixed") return fixedGroupGeometry(withLayoutOffset(resolvedBounds$1(node), node.id, c), node.group.contentSize ?? {
5199
5420
  width: 0,
5200
5421
  height: 0
5201
5422
  }, node.group);
@@ -5208,7 +5429,7 @@ function createFlowEngine(store, initialOptions = {}) {
5208
5429
  if (isHiddenByCollapsedAncestor(child.id, c)) continue;
5209
5430
  if (excludeChildren?.has(child.id)) continue;
5210
5431
  const liveResize = c.canvasState === "resizing" && c.resizingEntityId === child.id ? getResizeBoundsFromContext(c) : null;
5211
- const b = liveResize ? liveResize : visualSnap ? visualBounds(child, visualSnap) : isDerivedGroup(child) ? excludeChildren ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds : groupGeometryFor(c, child, seen)?.bounds ?? withLayoutOffset(resolvedBounds(child), child.id, c) : hierarchyBounds(child, c);
5432
+ const b = liveResize ? liveResize : visualSnap ? visualBounds(child, visualSnap) : isDerivedGroup(child) ? excludeChildren ? computeGroupGeometryRaw(c, child, seen, excludeChildren).bounds : groupGeometryFor(c, child, seen)?.bounds ?? withLayoutOffset(resolvedBounds$1(child), child.id, c) : hierarchyBounds(child, c);
5212
5433
  union = uniteRects(union, b);
5213
5434
  }
5214
5435
  const nodeMap = indexNodes(c.graph.nodes);
@@ -5238,7 +5459,7 @@ function createFlowEngine(store, initialOptions = {}) {
5238
5459
  const geometry = groupGeometryFor(c, node);
5239
5460
  if (geometry) return geometry.bounds;
5240
5461
  }
5241
- return withLayoutOffset(resolvedBounds(node), node.id, c);
5462
+ return withLayoutOffset(resolvedBounds$1(node), node.id, c);
5242
5463
  }
5243
5464
  const edgePathMemo = /* @__PURE__ */ new Map();
5244
5465
  let edgePathMemoInputs = null;
@@ -5448,6 +5669,14 @@ function createFlowEngine(store, initialOptions = {}) {
5448
5669
  };
5449
5670
  const sourcePort = proposed.sourcePort && srcNode.ports ? srcNode.ports.find((p) => p.name === proposed.sourcePort) ?? null : null;
5450
5671
  const targetPort = proposed.targetPort && tgtNode.ports ? tgtNode.ports.find((p) => p.name === proposed.targetPort) ?? null : null;
5672
+ if (proposed.sourcePort && proposed.sourcePort !== "*" && appearanceFor(srcNode).registered && !isPortAllowed(srcNode, proposed.sourcePort) || proposed.targetPort && proposed.targetPort !== "*" && appearanceFor(tgtNode).registered && !isPortAllowed(tgtNode, proposed.targetPort)) return {
5673
+ valid: false,
5674
+ reason: "appearance-port"
5675
+ };
5676
+ if (!appearanceFor(srcNode).sides.length || !appearanceFor(tgtNode).sides.length) return {
5677
+ valid: false,
5678
+ reason: "appearance-sides"
5679
+ };
5451
5680
  if (sourcePort) {
5452
5681
  if (sourcePort.direction === "in") return {
5453
5682
  valid: false,
@@ -5570,6 +5799,7 @@ function createFlowEngine(store, initialOptions = {}) {
5570
5799
  if (!resolveEntityConfig(node).connectable) continue;
5571
5800
  const nodePosition = layoutPosition(node, c);
5572
5801
  for (const port of node.ports ?? []) {
5802
+ if (!isPortAllowed(node, port.name)) continue;
5573
5803
  const position = {
5574
5804
  x: nodePosition.x + port.x + port.width / 2,
5575
5805
  y: nodePosition.y + port.y + port.height / 2
@@ -5587,8 +5817,16 @@ function createFlowEngine(store, initialOptions = {}) {
5587
5817
  };
5588
5818
  }
5589
5819
  if (mode !== "loose") continue;
5590
- const bounds = hierarchyBounds(node, c);
5591
- const distance = node.group ? groupConnectionDistance(pointer, node, c) : distanceToRect(pointer, bounds);
5820
+ const bounds = connectionBounds(node.id, node, hierarchyBounds(node, c));
5821
+ const sides = appearanceFor(node).sides;
5822
+ if (!sides.length) continue;
5823
+ const boundaryDistance = Math.min(...sides.map((side) => distanceToRect(pointer, {
5824
+ x: side === "right" ? bounds.x + bounds.width : bounds.x,
5825
+ y: side === "bottom" ? bounds.y + bounds.height : bounds.y,
5826
+ width: side === "left" || side === "right" ? 0 : bounds.width,
5827
+ height: side === "top" || side === "bottom" ? 0 : bounds.height
5828
+ })));
5829
+ const distance = sides.length < 4 ? boundaryDistance : node.group ? groupConnectionDistance(pointer, node, c) : distanceToRect(pointer, bounds);
5592
5830
  if (distance > radius) continue;
5593
5831
  const isValid = isConnectionCandidateValid(options.source, node.id, null);
5594
5832
  if (!isValid) continue;
@@ -5623,40 +5861,20 @@ function createFlowEngine(store, initialOptions = {}) {
5623
5861
  if (!source || !target) return void 0;
5624
5862
  const sourceBounds = visualBounds(source, snap);
5625
5863
  const targetBounds = visualBounds(target, snap);
5626
- return { ...visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id))), snap) };
5864
+ return { ...visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, ctx().measurements.get(edge.id))), snap) };
5627
5865
  };
5628
5866
  }
5629
5867
  function getEdgePath(edgeId) {
5630
- const c = ctx();
5631
- const { graph } = c;
5632
- const edge = indexEdges(graph.edges).get(edgeId) ?? foldedEdgesFor(c).byId.get(edgeId);
5633
- if (!edge) return null;
5634
- const authoritative = authoritativeEdgePath(edge);
5635
- if (authoritative) return authoritative;
5636
- const nodeIndex = indexNodes(graph.nodes);
5637
- const sourceNode = nodeIndex.get(edge.sourceId);
5638
- const targetNode = nodeIndex.get(edge.targetId);
5639
- if (!sourceNode || !targetNode) return null;
5640
- const srcBounds = withLayoutOffset(resolvedBounds(sourceNode), sourceNode.id, c);
5641
- const tgtBounds = withLayoutOffset(resolvedBounds(targetNode), targetNode.id, c);
5642
- const sourceDirection = bestDirection(srcBounds, tgtBounds);
5643
- const targetDirection = bestDirection(tgtBounds, srcBounds);
5644
- const snap = getVisualSnapOffset();
5645
- const routerCtx = {
5646
- graph,
5647
- getEntityBounds: createRouterEntityBoundsLookup(graph, snap, nodeIndex, indexEdges(graph.edges)),
5648
- sourceBounds: srcBounds,
5649
- targetBounds: tgtBounds,
5650
- sourceDirection,
5651
- targetDirection,
5652
- sourcePoint: getShapeAnchor(sourceNode, srcBounds, sourceDirection),
5653
- targetPoint: getShapeAnchor(targetNode, tgtBounds, targetDirection),
5654
- waypoints: offsetEdgeWaypoints(edge, visualOwnedEdgeOffset(edge, snap)),
5655
- get obstacles() {
5656
- return edgeObstacles(edge, c);
5657
- }
5868
+ const segments = getAllEdgePaths().get(edgeId)?.segments;
5869
+ if (!segments?.length) return null;
5870
+ if (segments.length === 1) return segments[0];
5871
+ return {
5872
+ points: segments.flatMap((segment) => segment.points),
5873
+ sourceDirection: segments[0].sourceDirection,
5874
+ targetDirection: segments.at(-1).targetDirection,
5875
+ routing: "polyline",
5876
+ svgPath: segments.map(pathToSVG).join(" ")
5658
5877
  };
5659
- return (engineOptions.edgeRouter ?? bezierRouter)(edge, routerCtx);
5660
5878
  }
5661
5879
  function getEdgePathBounds(edgeId) {
5662
5880
  const path = getAllEdgePaths().get(edgeId);
@@ -5687,7 +5905,7 @@ function createFlowEngine(store, initialOptions = {}) {
5687
5905
  }
5688
5906
  if (addressable.kind === "edge") {
5689
5907
  const labelBounds = getEdgeLabelBounds(id);
5690
- if (authoritativeEdgePath(addressable.edge)) {
5908
+ if (resolvedAuthoritativePath(addressable.edge)) {
5691
5909
  const edgePathBounds = getEdgePathBounds(id);
5692
5910
  if (edgePathBounds) return labelBounds ? unionRect(edgePathBounds, labelBounds) : edgePathBounds;
5693
5911
  }
@@ -5726,7 +5944,7 @@ function createFlowEngine(store, initialOptions = {}) {
5726
5944
  height: tgt.style?.customHeight ?? tgt.height
5727
5945
  }, tgt.id);
5728
5946
  const anchor = edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed";
5729
- const size = resolvedEdgeLabelSize(edge.label, measurement);
5947
+ const size = resolvedEdgeLabelSize$1(edge.label, measurement);
5730
5948
  const basePos = resolveLabelAnchor(anchor, edge.label, srcB, tgtB, edge, size);
5731
5949
  return withLayoutOffset({
5732
5950
  x: basePos.x + (edge.label.dx ?? 0),
@@ -5749,7 +5967,7 @@ function createFlowEngine(store, initialOptions = {}) {
5749
5967
  }
5750
5968
  for (const e of c.graph.edges) {
5751
5969
  if (!c.selection.has(e.id)) continue;
5752
- if (includeEdgePoints) for (const point of authoritativeEdgePath(e)?.points ?? []) {
5970
+ if (includeEdgePoints) for (const point of resolvedAuthoritativePath(e)?.points ?? []) {
5753
5971
  minX = Math.min(minX, point.x);
5754
5972
  minY = Math.min(minY, point.y);
5755
5973
  maxX = Math.max(maxX, point.x);
@@ -5895,7 +6113,7 @@ function createFlowEngine(store, initialOptions = {}) {
5895
6113
  if (geometry) return geometry.bounds;
5896
6114
  }
5897
6115
  const entityOffset = (node.dx ?? 0) !== 0 || (node.dy ?? 0) !== 0 ? snap.offset : null;
5898
- return withLayoutOffset(snappedBounds(node, snap.grid, entityOffset), node.id, c);
6116
+ return withLayoutOffset(snappedBounds$1(node, snap.grid, entityOffset), node.id, c);
5899
6117
  }
5900
6118
  function visualLabelBounds(edge, basePos, snap) {
5901
6119
  const isSelected = snap.selection.has(edge.id);
@@ -5916,7 +6134,7 @@ function createFlowEngine(store, initialOptions = {}) {
5916
6134
  y = snapToGrid(y, snap.grid[1]);
5917
6135
  }
5918
6136
  }
5919
- const size = edge.label ? resolvedEdgeLabelSize(edge.label, ctx().measurements.get(edge.id)) : {
6137
+ const size = edge.label ? resolvedEdgeLabelSize$1(edge.label, ctx().measurements.get(edge.id)) : {
5920
6138
  width: 0,
5921
6139
  height: 0
5922
6140
  };
@@ -5936,7 +6154,7 @@ function createFlowEngine(store, initialOptions = {}) {
5936
6154
  }
5937
6155
  /** Get bounds for edge endpoint — port bounds if specified, otherwise node bounds */
5938
6156
  function getEndpointBounds(node, portName, snap) {
5939
- if (portName && portName !== "*" && node.ports) {
6157
+ if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
5940
6158
  const port = node.ports.find((p) => p.name === portName);
5941
6159
  if (port) {
5942
6160
  const np = snap ? visualPosition(node, snap) : layoutPosition(node);
@@ -5948,22 +6166,31 @@ function createFlowEngine(store, initialOptions = {}) {
5948
6166
  };
5949
6167
  }
5950
6168
  }
5951
- if (snap) return visualBounds(node, snap);
5952
- return withLayoutOffset(resolvedBounds(node), node.id);
6169
+ const visual = snap ? visualBounds(node, snap) : hierarchyBounds(node, ctx());
6170
+ return connectionBounds(node.id, node, visual);
5953
6171
  }
5954
6172
  function portSideOf(node, portName) {
5955
6173
  if (!portName || portName === "*" || !node.ports) return null;
5956
- return node.ports.find((p) => p.name === portName)?.side ?? null;
6174
+ const port = node.ports.find((p) => p.name === portName);
6175
+ return port && isPortAllowed(node, portName) ? port.side ?? null : null;
5957
6176
  }
5958
6177
  function getShapeAnchor(node, bounds, direction) {
6178
+ const appearance = appearanceFor(node);
6179
+ if (appearance.connectionBounds || appearance.registered && ctx().measurements.has(appearanceMeasurementId(node.id, appearance))) return rectEdgeAnchor(bounds, direction);
5959
6180
  return getShapeOrDefault(node.shape ?? "rect").edgeAnchor(bounds, direction);
5960
6181
  }
5961
6182
  function resolveEndpointPoint(node, nodeBounds, portName, otherBounds, fallbackDirection, snap) {
5962
- if (portName === "*" && node.ports?.length) return closestPortPosition(node, {
5963
- x: otherBounds.x + otherBounds.width / 2,
5964
- y: otherBounds.y + otherBounds.height / 2
5965
- }, snap ? visualPosition(node, snap) : layoutPosition(node));
5966
- if (portName && portName !== "*" && node.ports) {
6183
+ if (portName === "*" && node.ports?.some((port) => isPortAllowed(node, port.name))) {
6184
+ const otherCenter = {
6185
+ x: otherBounds.x + otherBounds.width / 2,
6186
+ y: otherBounds.y + otherBounds.height / 2
6187
+ };
6188
+ return closestPortPosition({
6189
+ ...node,
6190
+ ports: node.ports.filter((port) => isPortAllowed(node, port.name))
6191
+ }, otherCenter, snap ? visualPosition(node, snap) : layoutPosition(node));
6192
+ }
6193
+ if (portName && portName !== "*" && node.ports && isPortAllowed(node, portName)) {
5967
6194
  const port = node.ports.find((p) => p.name === portName);
5968
6195
  if (port) {
5969
6196
  const position = snap ? visualPosition(node, snap) : layoutPosition(node);
@@ -6015,8 +6242,8 @@ function createFlowEngine(store, initialOptions = {}) {
6015
6242
  getEdgeLabelBounds
6016
6243
  });
6017
6244
  const sourceBounds = resolvedSourceBounds ?? naturalSourceBounds;
6018
- const sourceDirection = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds);
6019
- const targetDirection = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds);
6245
+ const sourceDirection = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
6246
+ const targetDirection = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
6020
6247
  return {
6021
6248
  sourceBounds,
6022
6249
  targetBounds,
@@ -6028,6 +6255,7 @@ function createFlowEngine(store, initialOptions = {}) {
6028
6255
  }
6029
6256
  function edgePathsCacheInputs(c, snap) {
6030
6257
  return {
6258
+ appearances: c.appearances,
6031
6259
  canonicalGraph: c.graph,
6032
6260
  selection: c.selection,
6033
6261
  collapsedNodeIds: c.collapsedNodeIds,
@@ -6043,7 +6271,7 @@ function createFlowEngine(store, initialOptions = {}) {
6043
6271
  };
6044
6272
  }
6045
6273
  function sameEdgePathsCacheInputs(a, b) {
6046
- return a.canonicalGraph === b.canonicalGraph && a.selection === b.selection && a.collapsedNodeIds === b.collapsedNodeIds && a.connection === b.connection && a.offsetX === b.offsetX && a.offsetY === b.offsetY && a.gridX === b.gridX && a.gridY === b.gridY && a.resizingEntityId === b.resizingEntityId && a.resizeCorners === b.resizeCorners && a.measurements === b.measurements && a.layoutOffsets === b.layoutOffsets;
6274
+ return a.appearances === b.appearances && a.canonicalGraph === b.canonicalGraph && a.selection === b.selection && a.collapsedNodeIds === b.collapsedNodeIds && a.connection === b.connection && a.offsetX === b.offsetX && a.offsetY === b.offsetY && a.gridX === b.gridX && a.gridY === b.gridY && a.resizingEntityId === b.resizingEntityId && a.resizeCorners === b.resizeCorners && a.measurements === b.measurements && a.layoutOffsets === b.layoutOffsets;
6047
6275
  }
6048
6276
  /** Route all edges. Callers must treat the returned Map as read-only. */
6049
6277
  function getAllEdgePaths(options = {}) {
@@ -6080,9 +6308,10 @@ function createFlowEngine(store, initialOptions = {}) {
6080
6308
  const memoUsable = !engineOptions.isVisible && !globalConfig.visible && !engineOptions.resolveEdgeSourceBounds;
6081
6309
  if (memoUsable) {
6082
6310
  const inputs = edgePathMemoInputs;
6083
- if (!inputs || inputs.selection !== c.selection || inputs.offsetX !== snap.offset.x || inputs.offsetY !== snap.offset.y || inputs.grid !== snap.grid || inputs.resizingEntityId !== c.resizingEntityId || inputs.resizeCorners !== c.resizeCorners || inputs.measurements !== c.measurements || inputs.layoutOffsets !== c.layoutAnimation.offsets) {
6311
+ if (!inputs || inputs.appearances !== c.appearances || inputs.selection !== c.selection || inputs.offsetX !== snap.offset.x || inputs.offsetY !== snap.offset.y || inputs.grid !== snap.grid || inputs.resizingEntityId !== c.resizingEntityId || inputs.resizeCorners !== c.resizeCorners || inputs.measurements !== c.measurements || inputs.layoutOffsets !== c.layoutAnimation.offsets) {
6084
6312
  edgePathMemo.clear();
6085
6313
  edgePathMemoInputs = {
6314
+ appearances: c.appearances,
6086
6315
  selection: c.selection,
6087
6316
  offsetX: snap.offset.x,
6088
6317
  offsetY: snap.offset.y,
@@ -6129,39 +6358,40 @@ function createFlowEngine(store, initialOptions = {}) {
6129
6358
  const getObstacles = () => obstaclesCache ??= edgeObstacles(edge, c);
6130
6359
  const waypoints = offsetEdgeWaypoints(edge, visualOwnedEdgeOffset(edge, snap));
6131
6360
  let pathData;
6132
- const authoritative = authoritativeEdgePath(edge);
6361
+ const authoritative = resolvedAuthoritativePath(edge, source, target);
6133
6362
  if (authoritative) pathData = {
6134
6363
  segments: [authoritative],
6135
- labelBounds: edge.label ? visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id))), snap) : null
6364
+ labelBounds: edge.label ? visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, c.measurements.get(edge.id))), snap) : null
6136
6365
  };
6137
6366
  else if (edge.label) {
6138
- const labelBounds = visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize(edge.label, c.measurements.get(edge.id))), snap);
6139
- const srcDir = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, labelBounds);
6140
- const lblDir1 = bestDirection(labelBounds, sourceBounds);
6367
+ const labelBounds = visualLabelBounds(edge, resolveLabelAnchor(edge.labelAnchor ?? engineOptions.labelAnchor ?? "fixed", edge.label, sourceBounds, targetBounds, edge, resolvedEdgeLabelSize$1(edge.label, c.measurements.get(edge.id))), snap);
6368
+ const labelConnectionBounds = connectionBounds(edge.id, edge.label, labelBounds);
6369
+ const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, labelConnectionBounds);
6370
+ const lblDir1 = connectionDirection(edge.label, labelConnectionBounds, sourceBounds);
6141
6371
  const seg1 = (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6142
6372
  graph,
6143
6373
  getEntityBounds,
6144
6374
  sourceBounds,
6145
- targetBounds: labelBounds,
6375
+ targetBounds: labelConnectionBounds,
6146
6376
  sourceDirection: srcDir,
6147
6377
  targetDirection: lblDir1,
6148
- sourcePoint,
6378
+ sourcePoint: resolveEndpointPoint(source, sourceBounds, edge.sourcePort, labelConnectionBounds, srcDir, snap),
6149
6379
  waypoints,
6150
6380
  get obstacles() {
6151
6381
  return getObstacles();
6152
6382
  }
6153
6383
  });
6154
- const lblDir2 = bestDirection(labelBounds, targetBounds);
6155
- const tgtDir = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, labelBounds);
6384
+ const lblDir2 = connectionDirection(edge.label, labelConnectionBounds, targetBounds);
6385
+ const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, labelConnectionBounds);
6156
6386
  pathData = {
6157
6387
  segments: [seg1, (engineOptions.edgeRouter ?? bezierRouter)(edge, {
6158
6388
  graph,
6159
6389
  getEntityBounds,
6160
- sourceBounds: labelBounds,
6390
+ sourceBounds: labelConnectionBounds,
6161
6391
  targetBounds,
6162
6392
  sourceDirection: lblDir2,
6163
6393
  targetDirection: tgtDir,
6164
- targetPoint,
6394
+ targetPoint: resolveEndpointPoint(target, targetBounds, edge.targetPort, labelConnectionBounds, tgtDir, snap),
6165
6395
  waypoints,
6166
6396
  get obstacles() {
6167
6397
  return getObstacles();
@@ -6170,8 +6400,8 @@ function createFlowEngine(store, initialOptions = {}) {
6170
6400
  labelBounds
6171
6401
  };
6172
6402
  } else {
6173
- const srcDir = portSideOf(source, edge.sourcePort) ?? bestDirection(sourceBounds, targetBounds);
6174
- const tgtDir = portSideOf(target, edge.targetPort) ?? bestDirection(targetBounds, sourceBounds);
6403
+ const srcDir = portSideOf(source, edge.sourcePort) ?? connectionDirection(source, sourceBounds, targetBounds);
6404
+ const tgtDir = portSideOf(target, edge.targetPort) ?? connectionDirection(target, targetBounds, sourceBounds);
6175
6405
  pathData = {
6176
6406
  segments: [(engineOptions.edgeRouter ?? bezierRouter)(edge, {
6177
6407
  graph,
@@ -6213,7 +6443,13 @@ function createFlowEngine(store, initialOptions = {}) {
6213
6443
  }
6214
6444
  function graphBoundsFor(c) {
6215
6445
  if (graphBoundsCache?.nodesInput === c.graph.nodes && graphBoundsCache.edgesInput === c.graph.edges && graphBoundsCache.measurementsInput === c.measurements) return graphBoundsCache.value;
6216
- const value = getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);
6446
+ const value = c.appearances ? getGraphBounds(c.graph.nodes.map(sizedNode), c.graph.edges.map((edge) => edge.label ? {
6447
+ ...edge,
6448
+ label: {
6449
+ ...edge.label,
6450
+ autoSize: appearanceFor(edge.label).autoSize
6451
+ }
6452
+ } : edge), c.measurements) : getGraphBounds(c.graph.nodes, c.graph.edges, c.measurements);
6217
6453
  graphBoundsCache = {
6218
6454
  nodesInput: c.graph.nodes,
6219
6455
  edgesInput: c.graph.edges,
@@ -6254,7 +6490,7 @@ function createFlowEngine(store, initialOptions = {}) {
6254
6490
  const source = getNode(edge.sourceId);
6255
6491
  const target = getNode(edge.targetId);
6256
6492
  if (!source || !target) return null;
6257
- return unionRect(withLayoutOffset(resolvedBounds(source), source.id, c), withLayoutOffset(resolvedBounds(target), target.id, c));
6493
+ return unionRect(withLayoutOffset(resolvedBounds$1(source), source.id, c), withLayoutOffset(resolvedBounds$1(target), target.id, c));
6258
6494
  }
6259
6495
  /**
6260
6496
  * Viewport-query index keyed by geometry identities, never viewport. Building
@@ -6364,7 +6600,7 @@ function createFlowEngine(store, initialOptions = {}) {
6364
6600
  })) return true;
6365
6601
  const srcNode = getNode(e.sourceId);
6366
6602
  const tgtNode = getNode(e.targetId);
6367
- return !!srcNode && !!tgtNode && (rectsIntersect(withLayoutOffset(resolvedBounds(srcNode), srcNode.id, c), cullRect) || rectsIntersect(withLayoutOffset(resolvedBounds(tgtNode), tgtNode.id, c), cullRect));
6603
+ return !!srcNode && !!tgtNode && (rectsIntersect(withLayoutOffset(resolvedBounds$1(srcNode), srcNode.id, c), cullRect) || rectsIntersect(withLayoutOffset(resolvedBounds$1(tgtNode), tgtNode.id, c), cullRect));
6368
6604
  })
6369
6605
  };
6370
6606
  }
@@ -6489,6 +6725,15 @@ function createFlowEngine(store, initialOptions = {}) {
6489
6725
  trigger: store.trigger,
6490
6726
  getContext: ctx,
6491
6727
  setOptions,
6728
+ resolveAppearance: appearanceFor,
6729
+ isPortAllowed,
6730
+ getConnectionBounds: (id) => {
6731
+ const node = getNode(id);
6732
+ if (node) return connectionBounds(id, node, getPublicVisualBounds(node));
6733
+ const edge = getEdge(id);
6734
+ const bounds = getAllEdgePaths().get(id)?.labelBounds;
6735
+ return edge?.label && bounds ? connectionBounds(id, edge.label, bounds) : null;
6736
+ },
6492
6737
  getNode,
6493
6738
  getEdge,
6494
6739
  getEntity,
@@ -6651,7 +6896,7 @@ function createFlowEngine(store, initialOptions = {}) {
6651
6896
  const ids = [];
6652
6897
  for (const n of graph.nodes) {
6653
6898
  if (!isNodeVisible(n, c)) continue;
6654
- if (rectsIntersect(rect, n.selectionBounds ? resolvedSelectionBounds(n) : visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6899
+ if (rectsIntersect(rect, n.selectionBounds ? resolvedSelectionBounds(sizedNode(n)) : visualBounds(n, getVisualSnapOffset()))) ids.push(n.id);
6655
6900
  }
6656
6901
  for (const e of graph.edges) {
6657
6902
  if (!isEdgeVisible(e, graph, c)) continue;
@@ -6686,11 +6931,20 @@ function createFlowEngine(store, initialOptions = {}) {
6686
6931
  const { graph } = ctx();
6687
6932
  const edge = graph.edges.find((e) => e.id === edgeId);
6688
6933
  if (!edge) return null;
6689
- const authoritative = authoritativeEdgePath(edge);
6934
+ const authoritative = resolvedAuthoritativePath(edge);
6690
6935
  if (authoritative) return {
6691
6936
  source: authoritative.points[0],
6692
6937
  target: authoritative.points.at(-1)
6693
6938
  };
6939
+ if (edge.label) {
6940
+ const path = getAllEdgePaths().get(edgeId);
6941
+ const first = path?.segments[0]?.points[0];
6942
+ const last = path?.segments.at(-1)?.points.at(-1);
6943
+ if (first && last) return {
6944
+ source: first,
6945
+ target: last
6946
+ };
6947
+ }
6694
6948
  const srcNode = graph.nodes.find((n) => n.id === edge.sourceId);
6695
6949
  const tgtNode = graph.nodes.find((n) => n.id === edge.targetId);
6696
6950
  if (!srcNode || !tgtNode) return null;
@@ -7461,6 +7715,7 @@ function createFlow(options = {}) {
7461
7715
  }, options.dataSchemas);
7462
7716
  const store = createFlowStore(initialGraph, {
7463
7717
  ...options.store,
7718
+ appearances: options.engine?.appearances ?? options.store?.appearances,
7464
7719
  labelAnchor: options.store?.labelAnchor ?? options.engine?.labelAnchor
7465
7720
  });
7466
7721
  const engine = createFlowEngine(store, options.engine);
@@ -8160,7 +8415,13 @@ function createFlow(options = {}) {
8160
8415
  autoSize: false,
8161
8416
  style: void 0
8162
8417
  } : node;
8163
- }), edges, context.measurements);
8418
+ }), edges.map((edge) => edge.label ? {
8419
+ ...edge,
8420
+ label: {
8421
+ ...edge.label,
8422
+ autoSize: engine.resolveAppearance(edge.label).autoSize
8423
+ }
8424
+ } : edge), context.measurements);
8164
8425
  if (bounds.width === 0 && bounds.height === 0) return null;
8165
8426
  const { nodes: _nodes, includeHidden: _includeHidden, ...viewportOptions } = fitOptions ?? {};
8166
8427
  return viewportForBounds(bounds, context.viewportSize, {
@@ -9883,6 +10144,7 @@ function connectMode(options = {}) {
9883
10144
  const { nodeId, portName } = event.target;
9884
10145
  const node = engine.getNode(nodeId);
9885
10146
  if (!node?.ports?.some((port) => port.name === portName)) return null;
10147
+ if (!engine.isPortAllowed(node, portName)) return null;
9886
10148
  if (!engine.resolveEntityConfig(node).connectable) return null;
9887
10149
  return {
9888
10150
  commands: [trigger("connectionStart", {
@@ -10896,4 +11158,4 @@ function createEntityChangeNotifier(store, options = {}) {
10896
11158
  };
10897
11159
  }
10898
11160
  //#endregion
10899
- export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
11161
+ export { CONNECTION_PREVIEW_EDGE_ID, CONNECTION_PREVIEW_NODE_ID, FlowGraphValidationError, animateViewport, appearanceAllowsPort, appearanceDirection, appearanceMeasurementId, appearanceSides, applyFlowPatches, areNodesMeasured, avoidRouter, bestDirection, bezierRouter, boxSelectMode, boxToRect, calcAutoPan, canvasToScreen, clampZoom, cloneJsonSafe, composeGraphProjectionAttrs, configureAvoidRouter, configureBezierRouter, configureStepRouter, connectMode, constrainViewport, createConnectionPreviewGraph, createEdge, createEntityChangeNotifier, createFlow, createFlowChangeSet, createFlowEngine, createFlowInputRuntime, createFlowStore, createGraph, createNode, createPort, createViewport, defaultConfig, defaultFlowProfile, defaultInputModes, defaultInputModesForKeymap, defaultKeymap, defaultModesForContext, defineFlowProfile, deriveFlowView, deriveGroupGeometry, entityPressMode, extractFlowContent, fitFrameAroundExclusions, fixedGroupGeometry, fromJSON, getAnchorTransform, getAutoPanDelta, getConnectedEdges, getEdgeOwner, getGraphBounds, getIncomers, getMinimapProjection, getMinimapViewportCenter, getNeighbors, getOutgoers, getProjectedEdgeAttrs, getProjectedNodeAttrs, getSelectionBounds, getShape, getShapeOrDefault, getSnapLines, getToolbarPlacement, getVisibleBounds, hoverMode, indexChildren, indexEdgeAdjacency, indexEdges, indexNodes, insertFlowContent, isDerivedGroup, isGroup, isTrackpadPinch, keyboardMode, keyboardNavMode, markerToSVG, matchesKeyBinding, mergeGraphEdgeAttrs, mergeGraphNodeAttrs, nodeDepths, normalizeWheelPan, panBy, panMode, panePressMode, parseFlowSerialized, pathToSVG, pinchMode, portPressMode, preventDefault, profileModesForContext, profilePoliciesForContext, readonlyConfig, readonlyInputModes, readonlyInputModesForKeymap, reconnectMode, rectContains, rectsIntersect, registerShape, resolveAppearance, resolveBehavior, resolveGroupPadding, resolveKeymap, resolvedBounds, resolvedEdgeLabelBounds, resolvedEdgeLabelSize, resolvedPosition, resolvedSelectionBounds, screenToCanvas, selectMode, serializeFlowGraph, snapPointToGrid, snapToGrid, snappedBounds, sortActiveGraphProjections, stepRouter, straightRouter, toSVGTransform, toViewBox, trigger, unionRect, validateAndCloneGraph, validateFitFrame, validateViewport, viewportCenteredOn, viewportForBounds, visualBounds, visualPosition, wheelInteraction, wheelMode, wheelZoomDelta, zoomTo };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@statelyai/flow",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "Framework-agnostic flow visualization engine. Builds on @statelyai/graph.",
5
5
  "type": "module",
6
6
  "sideEffects": true,