@pixerate/editor-svelte 0.120.0 → 0.121.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.
@@ -17,8 +17,13 @@ export interface CreateCanvasExplosionOptions<TNode extends CanvasNode = CanvasN
17
17
  onSave?: () => void;
18
18
  }
19
19
  /**
20
- * Headless Svelte 5 rune managing canvas node explosion, spatial layout displacement,
21
- * coordinated multi-node animation paths, and reversible collapsing.
20
+ * Imperative explosion coordinator for a mutable graph (whiteboards, diagrams): adds child
21
+ * nodes and edges, animates them out along a trajectory while surrounding nodes slide aside,
22
+ * and collapses back exactly. The layout math is `computeCanvasExplosionLayout` from
23
+ * `@pixerate/editor/canvas`; several nodes can be exploded at once. For a canvas derived from
24
+ * state (`$derived`), use `createCanvasExplosionState` and the layout functions instead.
25
+ *
26
+ * `explodeNode` throws when a child id is already on the canvas or repeated.
22
27
  */
23
28
  export declare function createCanvasExplosion<TNode extends CanvasNode = CanvasNode, TEdge extends CanvasEdge = CanvasEdge>(graph: CanvasGraphTarget<TNode, TEdge>, options?: CreateCanvasExplosionOptions<TNode>): {
24
29
  readonly explodedNodeIds: string[];
@@ -1,9 +1,14 @@
1
1
  import { cubicOut } from 'svelte/easing';
2
- import { calculateDirectionalDisplacement, calculateReflowDisplacement } from './createCanvasDisplacement.js';
2
+ import { computeCanvasExplosionLayout } from '@pixerate/editor/canvas';
3
3
  import { createFanOutTrajectory, linearPositionTrajectory, runMultiNodeTransition } from './createCanvasTrajectory.js';
4
4
  /**
5
- * Headless Svelte 5 rune managing canvas node explosion, spatial layout displacement,
6
- * coordinated multi-node animation paths, and reversible collapsing.
5
+ * Imperative explosion coordinator for a mutable graph (whiteboards, diagrams): adds child
6
+ * nodes and edges, animates them out along a trajectory while surrounding nodes slide aside,
7
+ * and collapses back exactly. The layout math is `computeCanvasExplosionLayout` from
8
+ * `@pixerate/editor/canvas`; several nodes can be exploded at once. For a canvas derived from
9
+ * state (`$derived`), use `createCanvasExplosionState` and the layout functions instead.
10
+ *
11
+ * `explodeNode` throws when a child id is already on the canvas or repeated.
7
12
  */
8
13
  export function createCanvasExplosion(graph, options = {}) {
9
14
  let explodedNodeIds = $state([]);
@@ -36,98 +41,50 @@ export function createCanvasExplosion(graph, options = {}) {
36
41
  return explodedNodeIds.includes(nodeId);
37
42
  }
38
43
  function explodeNode(parentId, explodeOptions) {
39
- if (isExploded(parentId)) {
44
+ // Already exploded, or its explosion is still animating
45
+ if (isExploded(parentId) || snapshots.has(parentId)) {
40
46
  return false;
41
47
  }
42
48
  const parentNode = graph.nodes.find((n) => n.id === parentId);
43
49
  if (!parentNode) {
44
50
  return false;
45
51
  }
46
- const { childNodes, childEdges = [], connectParentToChildren = 'all', displacementStrategy = 'directional', directionalOptions = {}, reflowOptions = {}, trajectory, duration = 500, staggerDelay = 20, easing = cubicOut, onComplete } = explodeOptions;
47
- if (childNodes.length === 0) {
52
+ const { childNodes: requestedChildren, childEdges = [], connectParentToChildren = 'all', displacementStrategy = 'directional', directionalOptions = {}, reflowOptions = {}, trajectory, duration = 500, staggerDelay = 20, easing = cubicOut, onComplete } = explodeOptions;
53
+ if (requestedChildren.length === 0) {
48
54
  return false;
49
55
  }
50
- // 1. Calculate displacement for existing nodes
51
- let displacementMap;
52
- if (displacementStrategy === 'dagre') {
53
- displacementMap = calculateReflowDisplacement({
54
- existingNodes: graph.nodes,
55
- existingEdges: graph.edges,
56
- originNode: parentNode,
57
- childNodes,
58
- childEdges,
59
- getNodesBounds: options.getNodesBounds,
60
- options: {
61
- ...reflowOptions,
62
- direction: reflowOptions.direction ?? 'LR'
63
- }
64
- });
65
- }
66
- else if (displacementStrategy === 'none') {
67
- displacementMap = new Map();
68
- }
69
- else {
70
- displacementMap = calculateDirectionalDisplacement({
71
- existingNodes: graph.nodes,
72
- originNode: parentNode,
73
- childNodes,
74
- getNodesBounds: options.getNodesBounds,
75
- options: directionalOptions
76
- });
77
- }
78
- // 2. Build snapshot of displaced nodes before mutating positions
79
- const displacedNodesSnapshot = Array.from(displacementMap.entries()).map(([id]) => {
80
- const node = graph.nodes.find((n) => n.id === id);
81
- return {
82
- id,
83
- originalPosition: { ...(node?.position ?? { x: 0, y: 0 }) }
84
- };
56
+ // 1-3. Pure layout: displacement of existing nodes, child copies and the edges to add
57
+ // Loose type parameter: SvelteFlow `class` is ClassValue, core `CanvasNode.class` is a string (see GOTCHAS).
58
+ const layout = computeCanvasExplosionLayout({
59
+ existingNodes: graph.nodes,
60
+ existingEdges: graph.edges,
61
+ originNode: parentNode,
62
+ childNodes: requestedChildren,
63
+ childEdges,
64
+ strategy: displacementStrategy,
65
+ options: directionalOptions,
66
+ reflowOptions,
67
+ connectParentToChildren,
68
+ createEdge: graph.createEdge ? (source, target) => graph.createEdge(source, target) : undefined,
69
+ getNodesBounds: options.getNodesBounds
85
70
  });
86
- // 3. Prepare child edges & parent connection edges
87
- const edgesToAdd = [...childEdges];
88
- const defaultCreateEdge = (sourceId, targetId) => {
89
- if (graph.createEdge) {
90
- return graph.createEdge(sourceId, targetId);
91
- }
92
- return {
93
- id: crypto.randomUUID(),
94
- type: 'default',
95
- source: sourceId,
96
- target: targetId
97
- };
98
- };
99
- if (connectParentToChildren === 'all' || connectParentToChildren === true) {
100
- childNodes.forEach((child) => {
101
- const exists = edgesToAdd.some((e) => e.source === parentId && e.target === child.id);
102
- if (!exists) {
103
- edgesToAdd.push(defaultCreateEdge(parentId, child.id));
104
- }
105
- });
106
- }
107
- else if (connectParentToChildren === 'first' && childNodes.length > 0) {
108
- const firstChild = childNodes[0];
109
- const exists = edgesToAdd.some((e) => e.source === parentId && e.target === firstChild.id);
110
- if (!exists) {
111
- edgesToAdd.push(defaultCreateEdge(parentId, firstChild.id));
112
- }
113
- }
71
+ const displacementMap = layout.displacedPositions;
72
+ const childNodes = layout.childNodes;
73
+ const edgesToAdd = layout.childEdges.map((edge) => ({ ...edge }));
114
74
  const snapshot = {
115
75
  parentId,
116
76
  childNodeIds: childNodes.map((n) => n.id),
117
77
  childEdgeIds: edgesToAdd.map((e) => e.id),
118
- displacedNodes: displacedNodesSnapshot,
78
+ displacedNodes: [...layout.originalPositions].map(([id, originalPosition]) => ({ id, originalPosition })),
119
79
  timestamp: Date.now()
120
80
  };
121
81
  snapshots.set(parentId, snapshot);
122
- // 4. Position child nodes initially at origin node coordinate
82
+ // 4. Position child nodes (copies, so the caller's objects stay untouched) at the origin
123
83
  const originPos = { ...parentNode.position };
124
84
  const targetPositions = childNodes.map((child) => ({ ...child.position }));
125
85
  childNodes.forEach((child) => {
126
86
  child.position = { ...originPos };
127
- if (!child.data)
128
- child.data = {};
129
- child.data.scale = 0;
130
- child.data.opacity = 0;
87
+ child.data = { ...(child.data ?? {}), scale: 0, opacity: 0 };
131
88
  const currentStyle = (child.style || '').replace(/opacity:\s*[^;]+;?/g, '').trim();
132
89
  child.style = `${currentStyle ? currentStyle + '; ' : ''}opacity: 0;`;
133
90
  });
@@ -330,7 +287,7 @@ export function createCanvasExplosion(graph, options = {}) {
330
287
  return true;
331
288
  }
332
289
  function toggleExplode(parentId, explodeOptions, collapseOptions) {
333
- if (isExploded(parentId)) {
290
+ if (snapshots.has(parentId)) {
334
291
  return collapseNode(parentId, collapseOptions);
335
292
  }
336
293
  return explodeNode(parentId, explodeOptions);
@@ -0,0 +1,17 @@
1
+ import { type CanvasExplosionState, type CanvasExplosionStateController, type CanvasExplosionStateOptions } from '@pixerate/editor/canvas';
2
+ export type { CanvasExplosionState, CanvasExplosionStateOptions };
3
+ export interface CanvasExplosionStateRune extends CanvasExplosionState {
4
+ /** The framework-free controller underneath (for `canvasExplosionToolTarget` and agent tools). */
5
+ readonly controller: CanvasExplosionStateController;
6
+ }
7
+ /**
8
+ * Headless, declarative explosion state as a Svelte 5 rune: which node is exploded
9
+ * (`activeId`), which is still collapsing (`collapsingId`, so its children can play a collapse
10
+ * animation before unmounting), and the collapse timer. It never touches a graph: derive the
11
+ * canvas from it with `$derived` and `computeCanvasExplosionLayout` /
12
+ * `calculateDirectionalDisplacement`.
13
+ *
14
+ * Created during component initialisation it cleans up its timer when the component unmounts;
15
+ * created elsewhere, call `destroy()` yourself.
16
+ */
17
+ export declare function createCanvasExplosionState(options?: CanvasExplosionStateOptions): CanvasExplosionStateRune;
@@ -0,0 +1,44 @@
1
+ import { createCanvasExplosionStateController } from '@pixerate/editor/canvas';
2
+ /**
3
+ * Headless, declarative explosion state as a Svelte 5 rune: which node is exploded
4
+ * (`activeId`), which is still collapsing (`collapsingId`, so its children can play a collapse
5
+ * animation before unmounting), and the collapse timer. It never touches a graph: derive the
6
+ * canvas from it with `$derived` and `computeCanvasExplosionLayout` /
7
+ * `calculateDirectionalDisplacement`.
8
+ *
9
+ * Created during component initialisation it cleans up its timer when the component unmounts;
10
+ * created elsewhere, call `destroy()` yourself.
11
+ */
12
+ export function createCanvasExplosionState(options = {}) {
13
+ const controller = createCanvasExplosionStateController(options);
14
+ let snapshot = $state(controller.getSnapshot());
15
+ controller.subscribe(() => {
16
+ snapshot = controller.getSnapshot();
17
+ });
18
+ try {
19
+ $effect(() => () => controller.destroy());
20
+ }
21
+ catch {
22
+ // Not inside a component or effect: the caller owns destroy().
23
+ }
24
+ return {
25
+ controller,
26
+ get activeId() {
27
+ return snapshot.activeId;
28
+ },
29
+ get collapsingId() {
30
+ return snapshot.collapsingId;
31
+ },
32
+ get isExplodingOrCollapsing() {
33
+ return snapshot.activeId !== null || snapshot.collapsingId !== null;
34
+ },
35
+ isExploded: (nodeId) => snapshot.activeId === nodeId,
36
+ isCollapsing: (nodeId) => snapshot.collapsingId === nodeId,
37
+ shouldRenderChildren: (nodeId) => snapshot.activeId === nodeId || snapshot.collapsingId === nodeId,
38
+ explode: (nodeId) => controller.explode(nodeId),
39
+ collapse: (nodeId) => controller.collapse(nodeId),
40
+ toggle: (nodeId) => controller.toggle(nodeId),
41
+ finishCollapse: () => controller.finishCollapse(),
42
+ destroy: () => controller.destroy()
43
+ };
44
+ }
@@ -6,7 +6,8 @@ export { createCanvasDocking, type CreateCanvasDockingOptions, type DockStrategy
6
6
  export { createCanvasShortcuts } from './createCanvasShortcuts.js';
7
7
  export { createCanvasInteractions, defaultSvelteFlowPreset, miroCompatiblePreset, restorePanelPointerEvents, isolateCanvasGestures, type CreateCanvasInteractionsOptions } from './createCanvasInteractions.svelte.js';
8
8
  export { linearTrajectory, linearPositionTrajectory, createFanOutTrajectory, createBezierTrajectory, runMultiNodeTransition } from './createCanvasTrajectory.js';
9
- export { computeNodesBoundingBox, calculateDirectionalDisplacement, calculateReflowDisplacement } from './createCanvasDisplacement.js';
9
+ export { computeNodesBoundingBox, nodeSizeOf, calculateDirectionalDisplacement, calculateReflowDisplacement, calculateDagreReflowDisplacement, computeCanvasExplosionLayout, explosionEdgeId, createCanvasExplosionStateController, createCanvasExplosionToolProvider, canvasExplosionToolTarget, type ComputeCanvasExplosionLayoutParams, type CanvasExplosionLayoutResult, type CanvasExplosionStateController, type CanvasExplosionStateSnapshot, type CanvasExplosionToolTarget, type CanvasExplosionToolProviderOptions } from '@pixerate/editor/canvas';
10
+ export { createCanvasExplosionState, type CanvasExplosionState, type CanvasExplosionStateOptions, type CanvasExplosionStateRune } from './createCanvasExplosionState.svelte.js';
10
11
  export { createCanvasExplosion, type CanvasGraphTarget, type CreateCanvasExplosionOptions } from './createCanvasExplosion.svelte.js';
11
12
  export { createCanvasNodeSync, preserveNodeMeasurements, normalizeNodeHandles, snapshotCanvasGraph, type HandleConfig, type NodeMeasurement, type CreateCanvasNodeSyncOptions, type CanvasGraphSnapshotInput } from './createCanvasNodeSync.svelte.js';
12
13
  export { createCanvasMultiDrag, type MultiDragState, type MultiDragFollowerOffset, type CreateCanvasMultiDragOptions, type FollowerTransform } from './createCanvasMultiDrag.svelte.js';
@@ -14,9 +14,11 @@ export { createCanvasShortcuts } from './createCanvasShortcuts.js';
14
14
  export { createCanvasInteractions, defaultSvelteFlowPreset, miroCompatiblePreset, restorePanelPointerEvents, isolateCanvasGestures } from './createCanvasInteractions.svelte.js';
15
15
  // Trajectory calculation & multi-node transitions
16
16
  export { linearTrajectory, linearPositionTrajectory, createFanOutTrajectory, createBezierTrajectory, runMultiNodeTransition } from './createCanvasTrajectory.js';
17
- // Spatial layout displacement
18
- export { computeNodesBoundingBox, calculateDirectionalDisplacement, calculateReflowDisplacement } from './createCanvasDisplacement.js';
19
- // Node explosion & collapse rune
17
+ // Spatial layout displacement & pure explosion layout (core)
18
+ export { computeNodesBoundingBox, nodeSizeOf, calculateDirectionalDisplacement, calculateReflowDisplacement, calculateDagreReflowDisplacement, computeCanvasExplosionLayout, explosionEdgeId, createCanvasExplosionStateController, createCanvasExplosionToolProvider, canvasExplosionToolTarget } from '@pixerate/editor/canvas';
19
+ // Declarative explosion state rune
20
+ export { createCanvasExplosionState } from './createCanvasExplosionState.svelte.js';
21
+ // Imperative explosion coordinator rune
20
22
  export { createCanvasExplosion } from './createCanvasExplosion.svelte.js';
21
23
  // Node synchronization & handle normalization
22
24
  export { createCanvasNodeSync, preserveNodeMeasurements, normalizeNodeHandles, snapshotCanvasGraph } from './createCanvasNodeSync.svelte.js';
@@ -1,4 +1,5 @@
1
1
  import type { Node, Edge, XYPosition, ColorMode } from '@xyflow/svelte';
2
+ import type { DirectionalDisplacementOptions, ExplosionDisplacementStrategy, ReflowDisplacementOptions } from '@pixerate/editor/canvas';
2
3
  /**
3
4
  * Generic node interface representing an element on the canvas.
4
5
  */
@@ -120,26 +121,7 @@ export interface NodeTransition<TNode extends CanvasNode = CanvasNode> {
120
121
  index?: number;
121
122
  total?: number;
122
123
  }
123
- /**
124
- * Displacement axis / direction.
125
- */
126
- export type DisplacementDirection = 'right' | 'left' | 'down' | 'up' | 'vertical';
127
- /**
128
- * Options for directional displacement calculation.
129
- */
130
- export interface DirectionalDisplacementOptions {
131
- direction?: DisplacementDirection;
132
- gap?: number;
133
- spreadSiblingLanes?: boolean;
134
- siblingTolerance?: number;
135
- minY?: number;
136
- }
137
- /**
138
- * Options for Dagre reflow displacement calculation.
139
- */
140
- export interface ReflowDisplacementOptions extends CanvasLayoutOptions {
141
- anchorNodeId: string;
142
- }
124
+ export type { DisplacementDirection, DirectionalDisplacementOptions, ReflowDisplacementOptions, ExplosionDisplacementStrategy } from '@pixerate/editor/canvas';
143
125
  /**
144
126
  * Snapshot of canvas graph state prior to node explosion, enabling exact reversibility.
145
127
  */
@@ -160,8 +142,7 @@ export interface ExplodeNodeOptions<TNode extends CanvasNode = CanvasNode, TEdge
160
142
  childNodes: TNode[];
161
143
  childEdges?: TEdge[];
162
144
  connectParentToChildren?: boolean | 'first' | 'all';
163
- connectChildrenToDownstream?: boolean;
164
- displacementStrategy?: 'directional' | 'dagre' | 'none';
145
+ displacementStrategy?: ExplosionDisplacementStrategy;
165
146
  directionalOptions?: DirectionalDisplacementOptions;
166
147
  reflowOptions?: Partial<ReflowDisplacementOptions>;
167
148
  trajectory?: TrajectoryFunction;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pixerate/editor-svelte",
3
- "version": "0.120.0",
3
+ "version": "0.121.0",
4
4
  "description": "Svelte bindings and prompt/rich-text components for @pixerate/editor",
5
5
  "author": "Pixerate",
6
6
  "license": "MIT",
@@ -168,7 +168,7 @@
168
168
  "@tiptap/extension-bubble-menu": "^2.27.3",
169
169
  "@tiptap/extension-placeholder": "^2.27.3",
170
170
  "@tiptap/starter-kit": "^2.27.3",
171
- "@pixerate/editor": "0.163.0"
171
+ "@pixerate/editor": "0.164.0"
172
172
  },
173
173
  "peerDependencies": {
174
174
  "@dagrejs/dagre": "^1.1.4",
@@ -1,31 +0,0 @@
1
- import type { Rect, XYPosition } from '@xyflow/svelte';
2
- import type { CanvasEdge, CanvasLayoutOptions, CanvasNode, DirectionalDisplacementOptions } from './types.js';
3
- /**
4
- * Calculates a bounding rectangle for a set of nodes if not provided by getNodesBounds.
5
- */
6
- export declare function computeNodesBoundingBox<TNode extends CanvasNode = CanvasNode>(nodes: TNode[], defaultWidth?: number, defaultHeight?: number): Rect;
7
- /**
8
- * Pure directional displacement calculation.
9
- * Shifts downstream or surrounding nodes along an axis to clear space for newly inserted child nodes.
10
- */
11
- export declare function calculateDirectionalDisplacement<TNode extends CanvasNode = CanvasNode>(params: {
12
- existingNodes: TNode[];
13
- originNode: TNode;
14
- childNodes: TNode[];
15
- getNodesBounds?: (nodes: TNode[]) => Rect;
16
- options?: DirectionalDisplacementOptions;
17
- }): Map<string, XYPosition>;
18
- /**
19
- * Pure hierarchical Dagre reflow displacement calculation.
20
- * Calculates new coordinates for surrounding nodes using Dagre hierarchical layout,
21
- * anchoring the origin node at its current position to eliminate layout jumping.
22
- */
23
- export declare function calculateReflowDisplacement<TNode extends CanvasNode = CanvasNode, TEdge extends CanvasEdge = CanvasEdge>(params: {
24
- existingNodes: TNode[];
25
- existingEdges: TEdge[];
26
- originNode: TNode;
27
- childNodes: TNode[];
28
- childEdges?: TEdge[];
29
- getNodesBounds?: (nodes: TNode[]) => Rect;
30
- options?: CanvasLayoutOptions;
31
- }): Map<string, XYPosition>;
@@ -1,170 +0,0 @@
1
- import dagre from '@dagrejs/dagre';
2
- /**
3
- * Calculates a bounding rectangle for a set of nodes if not provided by getNodesBounds.
4
- */
5
- export function computeNodesBoundingBox(nodes, defaultWidth = 200, defaultHeight = 60) {
6
- if (nodes.length === 0) {
7
- return { x: 0, y: 0, width: 0, height: 0 };
8
- }
9
- let minX = Infinity;
10
- let minY = Infinity;
11
- let maxX = -Infinity;
12
- let maxY = -Infinity;
13
- for (const node of nodes) {
14
- const width = node.measured?.width ?? node.width ?? defaultWidth;
15
- const height = node.measured?.height ?? node.height ?? defaultHeight;
16
- minX = Math.min(minX, node.position.x);
17
- minY = Math.min(minY, node.position.y);
18
- maxX = Math.max(maxX, node.position.x + width);
19
- maxY = Math.max(maxY, node.position.y + height);
20
- }
21
- return {
22
- x: minX,
23
- y: minY,
24
- width: maxX - minX,
25
- height: maxY - minY
26
- };
27
- }
28
- /**
29
- * Pure directional displacement calculation.
30
- * Shifts downstream or surrounding nodes along an axis to clear space for newly inserted child nodes.
31
- */
32
- export function calculateDirectionalDisplacement(params) {
33
- const { existingNodes, originNode, childNodes, getNodesBounds, options = {} } = params;
34
- const { direction = 'right', gap = 40, spreadSiblingLanes = false, siblingTolerance = 50, minY } = options;
35
- const displacedMap = new Map();
36
- if (childNodes.length === 0 || existingNodes.length === 0) {
37
- return displacedMap;
38
- }
39
- const childBounds = getNodesBounds
40
- ? getNodesBounds(childNodes)
41
- : computeNodesBoundingBox(childNodes);
42
- const originWidth = originNode.measured?.width ?? originNode.width ?? 200;
43
- const originHeight = originNode.measured?.height ?? originNode.height ?? 60;
44
- // The delta space required along primary axis
45
- const deltaPrimary = (direction === 'right' || direction === 'left')
46
- ? childBounds.width + gap
47
- : childBounds.height + gap;
48
- // Vertical displacement parameters: upward and downward row clearance
49
- const deltaUp = Math.max(0, originNode.position.y - childBounds.y + gap);
50
- const deltaDown = Math.max(0, childBounds.y + childBounds.height - (originNode.position.y + originHeight) + gap);
51
- // Both above and below displace equally so the row expands symmetrically
52
- const equalDelta = Math.max(deltaUp, deltaDown);
53
- for (const node of existingNodes) {
54
- if (node.id === originNode.id)
55
- continue;
56
- let newX = node.position.x;
57
- let newY = node.position.y;
58
- let moved = false;
59
- if (direction === 'right') {
60
- // Downstream nodes strictly to the right of the origin
61
- if (node.position.x >= originNode.position.x + originWidth * 0.5) {
62
- newX += deltaPrimary;
63
- moved = true;
64
- }
65
- else if (spreadSiblingLanes) {
66
- // Sibling nodes occupying the same vertical space as the exploded cluster
67
- const isVerticallyOverlapping = node.position.y + (node.height ?? 60) >= childBounds.y - gap &&
68
- node.position.y <= childBounds.y + childBounds.height + gap;
69
- if (isVerticallyOverlapping && Math.abs(node.position.x - originNode.position.x) <= siblingTolerance) {
70
- const pushDirection = node.position.y >= originNode.position.y ? 1 : -1;
71
- newY += pushDirection * (childBounds.height * 0.5 + gap);
72
- moved = true;
73
- }
74
- }
75
- }
76
- else if (direction === 'left') {
77
- if (node.position.x <= originNode.position.x) {
78
- newX -= deltaPrimary;
79
- moved = true;
80
- }
81
- }
82
- else if (direction === 'down') {
83
- if (node.position.y >= originNode.position.y + originHeight * 0.5) {
84
- newY += deltaPrimary;
85
- moved = true;
86
- }
87
- }
88
- else if (direction === 'up') {
89
- if (node.position.y <= originNode.position.y) {
90
- newY -= deltaPrimary;
91
- moved = true;
92
- }
93
- }
94
- else if (direction === 'vertical') {
95
- // Row grows vertically:
96
- // Nodes strictly above the origin node move up by equalDelta
97
- // Nodes strictly below the origin node move down by equalDelta
98
- // Both above and below displace equally; horizontal position (x) is strictly preserved
99
- if (node.position.y < originNode.position.y) {
100
- if (equalDelta > 0) {
101
- newY -= equalDelta;
102
- moved = true;
103
- }
104
- }
105
- else if (node.position.y >= originNode.position.y + originHeight * 0.5) {
106
- if (equalDelta > 0) {
107
- newY += equalDelta;
108
- moved = true;
109
- }
110
- }
111
- }
112
- if (moved) {
113
- displacedMap.set(node.id, { x: newX, y: newY });
114
- }
115
- }
116
- return displacedMap;
117
- }
118
- /**
119
- * Pure hierarchical Dagre reflow displacement calculation.
120
- * Calculates new coordinates for surrounding nodes using Dagre hierarchical layout,
121
- * anchoring the origin node at its current position to eliminate layout jumping.
122
- */
123
- export function calculateReflowDisplacement(params) {
124
- const { existingNodes, existingEdges, originNode, childNodes, childEdges = [], options = {} } = params;
125
- const { direction = 'LR', ranksep = 80, nodesep = 30, defaultNodeWidth = 200, defaultNodeHeight = 60 } = options;
126
- const displacedMap = new Map();
127
- if (existingNodes.length === 0)
128
- return displacedMap;
129
- const allNodes = [...existingNodes, ...childNodes];
130
- const allEdges = [...existingEdges, ...childEdges];
131
- const dagreGraph = new dagre.graphlib.Graph();
132
- dagreGraph.setDefaultEdgeLabel(() => ({}));
133
- dagreGraph.setGraph({ rankdir: direction, ranksep, nodesep });
134
- const allNodeIds = new Set(allNodes.map((n) => n.id));
135
- allNodes.forEach((node) => {
136
- const nodeWidth = node.measured?.width ?? node.width ?? defaultNodeWidth;
137
- const nodeHeight = node.measured?.height ?? node.height ?? defaultNodeHeight;
138
- dagreGraph.setNode(node.id, { width: nodeWidth, height: nodeHeight });
139
- });
140
- allEdges.forEach((edge) => {
141
- if (allNodeIds.has(edge.source) && allNodeIds.has(edge.target)) {
142
- dagreGraph.setEdge(edge.source, edge.target);
143
- }
144
- });
145
- dagre.layout(dagreGraph);
146
- const dagreOrigin = dagreGraph.node(originNode.id);
147
- if (!dagreOrigin)
148
- return displacedMap;
149
- const originWidth = originNode.measured?.width ?? originNode.width ?? defaultNodeWidth;
150
- const originHeight = originNode.measured?.height ?? originNode.height ?? defaultNodeHeight;
151
- // Calculate offset so origin node remains anchored at its exact initial coordinates
152
- const anchorOffsetX = originNode.position.x - (dagreOrigin.x - originWidth / 2);
153
- const anchorOffsetY = originNode.position.y - (dagreOrigin.y - originHeight / 2);
154
- existingNodes.forEach((node) => {
155
- if (node.id === originNode.id)
156
- return;
157
- const dagreNode = dagreGraph.node(node.id);
158
- if (!dagreNode)
159
- return;
160
- const nodeWidth = node.measured?.width ?? node.width ?? defaultNodeWidth;
161
- const nodeHeight = node.measured?.height ?? node.height ?? defaultNodeHeight;
162
- const targetX = dagreNode.x - nodeWidth / 2 + anchorOffsetX;
163
- const targetY = dagreNode.y - nodeHeight / 2 + anchorOffsetY;
164
- // Only include if position actually shifted
165
- if (Math.abs(targetX - node.position.x) > 0.5 || Math.abs(targetY - node.position.y) > 0.5) {
166
- displacedMap.set(node.id, { x: targetX, y: targetY });
167
- }
168
- });
169
- return displacedMap;
170
- }