-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathFlowCanvas.svelte
More file actions
1127 lines (983 loc) · 37.3 KB
/
FlowCanvas.svelte
File metadata and controls
1127 lines (983 loc) · 37.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<script lang="ts">
import { get } from 'svelte/store';
import { onDestroy, untrack } from 'svelte';
import {
SvelteFlow,
Background,
BackgroundVariant,
type Node,
type Edge,
type Connection as FlowConnection,
type NodeTypes,
type EdgeTypes
} from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
import { isInputFocused } from '$lib/utils/focus';
import BaseNode from './nodes/BaseNode.svelte';
import EventNode from './nodes/EventNode.svelte';
import AnnotationNode from './nodes/AnnotationNode.svelte';
import OrthogonalEdge from './edges/OrthogonalEdge.svelte';
import FlowUpdater from './FlowUpdater.svelte';
import { graphStore } from '$lib/stores/graph';
import { eventStore, setEventSelection } from '$lib/stores/events';
import { selectedNodeIds as graphSelectedNodeIds } from '$lib/stores/graph/state';
import { historyStore } from '$lib/stores/history';
import { routingStore, buildRoutingContext, type PortInfo } from '$lib/stores/routing';
import { HANDLE_OFFSET, ARROW_INSET, type Direction, type PortStub } from '$lib/routing';
import { themeStore, type Theme } from '$lib/stores/theme';
import { clearSelectionTrigger, nudgeTrigger, selectNodeTrigger, registerHasSelection, triggerFitView } from '$lib/stores/viewActions';
import { screenToFlow } from '$lib/utils/viewUtils';
import { dropTargetBridge } from '$lib/stores/dropTargetBridge';
import { contextMenuStore } from '$lib/stores/contextMenu';
import { nodeUpdatesStore } from '$lib/stores/nodeUpdates';
import { nodeRegistry } from '$lib/nodes';
import { NODE_TYPES } from '$lib/constants/nodeTypes';
import { GRID_SIZE, SNAP_GRID, BACKGROUND_GAP } from '$lib/constants/grid';
import type { NodeInstance, Connection, Annotation } from '$lib/nodes/types';
import type { EventInstance } from '$lib/events/types';
// Canvas utilities
import {
toFlowEdge,
toEventNode,
toAnnotationNode,
rotateSelectedNodes,
flipSelectedNodesHorizontal,
flipSelectedNodesVertical,
findFirstAvailableInputPort
} from './canvas';
// Theme for SvelteFlow
let colorMode = $state<Theme>('dark');
const unsubscribeTheme = themeStore.subscribe((theme) => {
colorMode = theme;
});
// Debounced routing context update — coalesces rapid connection changes
// (e.g. paste, undo, bulk delete) into a single recalculation
let routingContextTimer: ReturnType<typeof setTimeout> | null = null;
function scheduleRoutingUpdate() {
if (routingContextTimer !== null) clearTimeout(routingContextTimer);
routingContextTimer = setTimeout(() => {
routingContextTimer = null;
updateRoutingContext();
}, 0);
}
// Track mouse position for waypoint placement
let mousePosition = { x: 0, y: 0 };
function handleMouseMove(event: MouseEvent) {
mousePosition = { x: event.clientX, y: event.clientY };
}
// Keyboard shortcuts for node manipulation
function handleKeydown(event: KeyboardEvent) {
if (isInputFocused(event)) return;
// Handle Delete key (SvelteFlow's deleteKeyCode doesn't work reliably for 'Delete')
if (event.key === 'Delete') {
const selectedNodes = nodes.filter(n => n.selected);
const selectedEdges = edges.filter(e => e.selected);
if (selectedNodes.length > 0 || selectedEdges.length > 0) {
event.preventDefault();
handleDelete({ nodes: selectedNodes, edges: selectedEdges });
}
return;
}
// Handle backslash key - add waypoint to selected edge
if (event.key === '\\') {
const selectedEdge = edges.find(e => e.selected);
if (selectedEdge) {
event.preventDefault();
// Convert screen position to flow coordinates
const flowPos = screenToFlow(mousePosition);
// Snap to grid
const gridSize = 10;
const snappedX = Math.round(flowPos.x / gridSize) * gridSize;
const snappedY = Math.round(flowPos.y / gridSize) * gridSize;
// Pass getPortInfo for immediate single-route recalculation (no full recalc needed)
routingStore.addUserWaypoint(selectedEdge.id, { x: snappedX, y: snappedY }, getPortInfo);
}
return;
}
const hasSelection = nodes.some((n) => n.selected);
if (!hasSelection) return;
let updatedNodes: string[] = [];
if (event.key === 'r' || event.key === 'R') {
event.preventDefault();
updatedNodes = rotateSelectedNodes(nodes);
} else if (event.key === 'x' || event.key === 'X') {
event.preventDefault();
updatedNodes = flipSelectedNodesHorizontal(nodes);
} else if (event.key === 'y' || event.key === 'Y') {
event.preventDefault();
updatedNodes = flipSelectedNodesVertical(nodes);
}
if (updatedNodes.length > 0) {
pendingNodeUpdates = [...updatedNodes];
// Recalculate routes for rotated/flipped nodes after FlowUpdater processes
setTimeout(() => {
const connections = get(graphStore.connections);
routingStore.recalculateRoutesForNodes(new Set(updatedNodes), connections, getPortInfo);
}, 0);
}
}
// Track port counts to detect changes - used to force node re-renders
let portCounts = new Map<string, { inputs: number; outputs: number }>();
// Track nodes that need internal updates (will be processed by FlowUpdater)
let pendingNodeUpdates: string[] = $state([]);
// Subscribe to external node updates (e.g., from context menu rotation)
const unsubscribeNodeUpdates = nodeUpdatesStore.subscribe((updates) => {
if (updates.length > 0) {
pendingNodeUpdates = [...pendingNodeUpdates, ...updates];
nodeUpdatesStore.clear();
}
});
// Register hasSelection function so +page.svelte can check SvelteFlow's selection state
registerHasSelection(() => nodes.some(n => n.selected));
// Subscribe to clear selection trigger - clears selection in SvelteFlow's nodes and edges
let lastClearSelectionTrigger = 0;
const unsubscribeClearSelection = clearSelectionTrigger.subscribe((trigger) => {
if (trigger > lastClearSelectionTrigger) {
lastClearSelectionTrigger = trigger;
// Clear selection on all nodes and edges
nodes = nodes.map(n => ({ ...n, selected: false }));
edges = edges.map(e => ({ ...e, selected: false }));
// Also clear store selection state using direct setters
graphSelectedNodeIds.set(new Set());
setEventSelection(new Set());
}
});
// Subscribe to nudge trigger - nudges all selected nodes and syncs to stores
let lastNudgeTrigger = 0;
const unsubscribeNudge = nudgeTrigger.subscribe((trigger) => {
if (trigger.id > lastNudgeTrigger) {
lastNudgeTrigger = trigger.id;
const delta = { x: trigger.x, y: trigger.y };
// Update positions in SvelteFlow's nodes array
nodes = nodes.map(n => {
if (n.selected) {
return { ...n, position: { x: n.position.x + delta.x, y: n.position.y + delta.y } };
}
return n;
});
// Sync positions to appropriate stores (as a single undoable action)
historyStore.mutate(() => {
nodes.forEach(n => {
if (n.selected) {
if (n.type === 'eventNode') {
if (graphStore.isAtRoot()) {
eventStore.updateEventPosition(n.id, n.position);
} else {
graphStore.updateSubsystemEventPosition(n.id, n.position);
}
} else if (n.type === 'annotation') {
graphStore.updateAnnotationPosition(n.id, n.position);
} else {
graphStore.updateNodePosition(n.id, n.position);
}
}
});
});
}
});
// Subscribe to select node trigger - selects specific nodes in SvelteFlow
let lastSelectNodeTrigger = 0;
const unsubscribeSelectNode = selectNodeTrigger.subscribe((trigger) => {
if (trigger.id > lastSelectNodeTrigger) {
lastSelectNodeTrigger = trigger.id;
const nodeIdsToSelect = new Set(trigger.nodeIds);
// Update selection in SvelteFlow's nodes array
nodes = nodes.map(n => {
if (nodeIdsToSelect.has(n.id)) {
return { ...n, selected: true };
} else if (!trigger.addToSelection) {
return { ...n, selected: false };
}
return n;
});
// Clear edge selection when selecting nodes
if (!trigger.addToSelection) {
edges = edges.map(e => ({ ...e, selected: false }));
}
// Sync to stores - note: we update stores directly here to avoid triggering again
syncSelectionToStores();
}
});
// Helper to sync SvelteFlow selection state to stores
// Uses direct setters to avoid triggering the selection trigger (which would loop)
function syncSelectionToStores() {
const selectedNodes = nodes.filter(n => n.selected);
// Build sets of selected IDs by type
const selectedBlockIds = new Set<string>();
const selectedEventIdSet = new Set<string>();
selectedNodes.forEach((node) => {
if (node.type === 'eventNode') {
selectedEventIdSet.add(node.id);
} else if (node.type !== 'annotation') {
selectedBlockIds.add(node.id);
}
});
// Update stores directly (bypasses trigger-based functions)
graphSelectedNodeIds.set(selectedBlockIds);
setEventSelection(selectedEventIdSet);
}
// Cleanup function - will add subscriptions as they're defined
const cleanups: (() => void)[] = [unsubscribeTheme, unsubscribeNodeUpdates, unsubscribeClearSelection, unsubscribeNudge, unsubscribeSelectNode];
onDestroy(() => {
cleanups.forEach(fn => fn());
if (routingContextTimer !== null) clearTimeout(routingContextTimer);
});
function clearPendingUpdates() {
pendingNodeUpdates = [];
}
// Helper to get port position and direction in world coordinates
// Returns handle tip position (accounting for handle offset from block edge)
// For inputs, also accounts for arrowhead so stub starts within arrow
function getPortInfo(nodeId: string, portIndex: number, isOutput: boolean): PortInfo | null {
const node = nodeMap.get(nodeId);
if (!node) return null;
const nodeData = node.data as NodeInstance;
const ports = isOutput ? nodeData.outputs : nodeData.inputs;
if (portIndex >= ports.length) return null;
const rotation = (nodeData.params?.['_rotation'] as number) || 0;
const width = node.measured?.width ?? node.width ?? 80;
const height = node.measured?.height ?? node.height ?? 40;
// Calculate port offset from center based on rotation
const portCount = ports.length;
const portSpacing = 20; // G.x2
const span = (portCount - 1) * portSpacing;
const offsetFromCenter = -span / 2 + portIndex * portSpacing;
let x = node.position.x;
let y = node.position.y;
let direction: Direction;
// Additional offset: handle tip is HANDLE_OFFSET outside block edge
// For inputs (targets), add ARROW_INSET so stub starts within arrowhead
const extraOffset = isOutput ? HANDLE_OFFSET : (HANDLE_OFFSET + ARROW_INSET);
// Position and direction based on rotation (output = right side for rotation 0)
if (isOutput) {
switch (rotation) {
case 1: // outputs at bottom
x += offsetFromCenter;
y += height / 2 + extraOffset;
direction = 'down';
break;
case 2: // outputs at left
x -= width / 2 + extraOffset;
y += offsetFromCenter;
direction = 'left';
break;
case 3: // outputs at top
x += offsetFromCenter;
y -= height / 2 + extraOffset;
direction = 'up';
break;
default: // rotation 0 - outputs at right
x += width / 2 + extraOffset;
y += offsetFromCenter;
direction = 'right';
break;
}
} else {
// Inputs are opposite to outputs
switch (rotation) {
case 1: // inputs at top
x += offsetFromCenter;
y -= height / 2 + extraOffset;
direction = 'up';
break;
case 2: // inputs at right
x += width / 2 + extraOffset;
y += offsetFromCenter;
direction = 'right';
break;
case 3: // inputs at bottom
x += offsetFromCenter;
y += height / 2 + extraOffset;
direction = 'down';
break;
default: // rotation 0 - inputs at left
x -= width / 2 + extraOffset;
y += offsetFromCenter;
direction = 'left';
break;
}
}
return { position: { x, y }, direction };
}
// Update routing context and recalculate all routes
function updateRoutingContext() {
// Only include block nodes (not events or annotations) for routing
const blockNodesForRouting = nodes.filter(n => n.type === 'pathview');
if (blockNodesForRouting.length === 0) {
routingStore.clearRoutes();
return;
}
const { nodeBounds, canvasBounds } = buildRoutingContext(blockNodesForRouting);
// Collect all port stubs for obstacle marking
const portStubs: PortStub[] = [];
for (const node of blockNodesForRouting) {
const nodeData = node.data as NodeInstance;
// Collect input port stubs
for (let i = 0; i < nodeData.inputs.length; i++) {
const info = getPortInfo(node.id, i, false);
if (info) portStubs.push({ position: info.position, direction: info.direction });
}
// Collect output port stubs
for (let i = 0; i < nodeData.outputs.length; i++) {
const info = getPortInfo(node.id, i, true);
if (info) portStubs.push({ position: info.position, direction: info.direction });
}
}
routingStore.setContext(nodeBounds, canvasBounds, portStubs);
// Recalculate all routes
const connections = get(graphStore.connections);
routingStore.recalculateAllRoutes(connections, getPortInfo);
}
// Custom node types - will add more for different shapes
const nodeTypes: NodeTypes = {
pathview: BaseNode,
eventNode: EventNode,
annotation: AnnotationNode
};
// Custom edge types - orthogonal routing with arrow
const edgeTypes: EdgeTypes = {
orthogonal: OrthogonalEdge
};
// SvelteFlow state - this is the source of truth for visual state
// Block nodes from graphStore
let blockNodes = $state<Node[]>([]);
// Event nodes from eventStore
let eventNodes = $state<Node[]>([]);
// Annotation nodes from graphStore
let annotationNodes = $state<Node[]>([]);
// Combined nodes for SvelteFlow
let nodes = $state<Node[]>([]);
let edges = $state<Edge[]>([]);
// O(1) node lookup map — kept in sync with nodes array via $effect
let nodeMap = $derived(new Map(nodes.map(n => [n.id, n])));
// Merge block, event, and annotation nodes when any changes
// Preserve position and selection from SvelteFlow's current state (except during undo/redo)
$effect(() => {
const currentNodes = untrack(() => new Map(nodes.map(n => [n.id, n])));
const restoring = historyStore.isRestoringState();
nodes = [...blockNodes, ...eventNodes, ...annotationNodes].map(n => {
const existing = currentNodes.get(n.id);
if (existing && !restoring) {
// Preserve SvelteFlow-managed state (position during drag, selection)
return { ...n, position: existing.position, selected: existing.selected };
}
return n;
});
});
// Track if we're currently syncing to prevent loops
let isSyncing = false;
// Track if initial load is complete (positions from graph store should be used until first render)
let initialLoadComplete = false;
// Track previous node IDs to detect deletions via binding
let prevNodeIds = new Set<string>();
// Watch for node deletions (SvelteFlow updates nodes via binding, not always via callback)
// Only delete nodes that are truly gone - not just filtered out by subsystem navigation
$effect(() => {
const currentNodeIds = new Set(nodes.map(n => n.id));
// Find nodes that disappeared from view
const disappearedIds = [...prevNodeIds].filter(id => !currentNodeIds.has(id));
if (disappearedIds.length > 0 && !isSyncing) {
isSyncing = true;
// Only remove if the node is truly deleted (not in full store)
// Nodes that are just filtered out by navigation should NOT be removed
disappearedIds.forEach(id => {
const stillInGraphStore = graphStore.getNode(id);
const stillInEventStore = eventStore.getEvent(id);
if (!stillInGraphStore && !stillInEventStore) {
// Node was actually deleted by SvelteFlow, clean up
portCounts.delete(id);
}
});
isSyncing = false;
}
// Update previous node IDs
prevNodeIds = currentNodeIds;
});
// Sync annotation dimensions when NodeResizer updates them
$effect(() => {
if (isSyncing) return;
nodes.forEach(node => {
if (node.type === 'annotation' && node.width && node.height) {
const annotation = graphStore.getAnnotation(node.id);
if (annotation && (annotation.width !== node.width || annotation.height !== node.height)) {
isSyncing = true;
graphStore.updateAnnotation(node.id, {
width: node.width,
height: node.height
});
isSyncing = false;
}
}
});
});
// Subscribe to current nodes (filtered by current navigation context)
cleanups.push(graphStore.nodes.subscribe((graphNodesMap: Map<string, NodeInstance>) => {
if (isSyncing) return;
// Convert Map to array for processing
const filteredGraphNodes = Array.from(graphNodesMap.values());
// Track nodes that need handle updates (port count changed)
const nodesToUpdate: string[] = [];
// Create a map of current nodes for quick lookup
const currentNodesMap = new Map(nodes.map(n => [n.id, n]));
// Find nodes to add, update, or remove
const newNodeIds = new Set(filteredGraphNodes.map(n => n.id));
const currentNodeIds = new Set(nodes.map(n => n.id));
// Check if there are actual changes
const hasAdditions = filteredGraphNodes.some(gn => !currentNodeIds.has(gn.id));
const hasRemovals = nodes.some(n => !newNodeIds.has(n.id));
const hasDataChanges = filteredGraphNodes.some(gn => {
const current = currentNodesMap.get(gn.id);
if (!current) return false;
const currentData = current.data as NodeInstance;
// Check if data actually changed (params, ports, name, color, pinnedParams)
const prevCounts = portCounts.get(gn.id);
const newCounts = { inputs: gn.inputs.length, outputs: gn.outputs.length };
if (prevCounts && (prevCounts.inputs !== newCounts.inputs || prevCounts.outputs !== newCounts.outputs)) {
return true;
}
if (currentData.name !== gn.name) return true;
if (currentData.color !== gn.color) return true;
if (JSON.stringify(currentData.params) !== JSON.stringify(gn.params)) return true;
if (JSON.stringify(currentData.pinnedParams) !== JSON.stringify(gn.pinnedParams)) return true;
return false;
});
// Only rebuild if there are actual changes
if (!hasAdditions && !hasRemovals && !hasDataChanges && initialLoadComplete) {
return;
}
// Build updated nodes array, preserving existing node objects where possible
const updatedNodes = filteredGraphNodes.map((graphNode) => {
const existingNode = currentNodesMap.get(graphNode.id);
// Check if port counts changed
const prevCounts = portCounts.get(graphNode.id);
const newCounts = { inputs: graphNode.inputs.length, outputs: graphNode.outputs.length };
if (prevCounts && (prevCounts.inputs !== newCounts.inputs || prevCounts.outputs !== newCounts.outputs)) {
nodesToUpdate.push(graphNode.id);
}
portCounts.set(graphNode.id, newCounts);
// Check if rotation changed - need to update internals for handle positions
if (existingNode) {
const existingData = existingNode.data as NodeInstance;
const oldRotation = existingData?.params?.['_rotation'] ?? 0;
const newRotation = graphNode.params?.['_rotation'] ?? 0;
if (oldRotation !== newRotation) {
nodesToUpdate.push(graphNode.id);
}
}
// Use store position when restoring (undo/redo), otherwise preserve existing position
const position = (existingNode && !historyStore.isRestoringState())
? existingNode.position
: { ...graphNode.position };
// Interface blocks are not deletable
const isInterface = graphNode.type === NODE_TYPES.INTERFACE;
// Don't set explicit width/height - let SvelteFlow auto-measure from DOM
// BaseNode controls its size via CSS, SvelteFlow reads it via updateNodeInternals
// If node exists, update data but don't preserve selection here
// Selection is managed by SvelteFlow, trigger subscriptions, and merge effect
if (existingNode) {
return {
id: existingNode.id,
type: existingNode.type,
position,
data: graphNode,
// Explicit center origin for correct bounds calculation
origin: [0.5, 0.5] as [number, number],
selectable: existingNode.selectable,
draggable: existingNode.draggable,
deletable: !isInterface
// NOTE: selected is intentionally NOT preserved here to avoid stale selection
} as Node<NodeInstance>;
}
// New node
return {
id: graphNode.id,
type: 'pathview',
position,
data: graphNode,
// Explicit center origin for correct bounds calculation
origin: [0.5, 0.5] as [number, number],
selectable: true,
draggable: true,
deletable: !isInterface
} as Node<NodeInstance>;
});
// Clean up port counts for removed nodes
for (const id of portCounts.keys()) {
if (!newNodeIds.has(id)) {
portCounts.delete(id);
}
}
blockNodes = updatedNodes;
// Queue node internal updates for nodes with changed ports/rotation
if (nodesToUpdate.length > 0) {
pendingNodeUpdates = [...nodesToUpdate];
// Recalculate routes for affected nodes after FlowUpdater processes
setTimeout(() => {
const connections = get(graphStore.connections);
routingStore.recalculateRoutesForNodes(new Set(nodesToUpdate), connections, getPortInfo);
}, 0);
}
// Mark initial load as complete after first non-empty sync
if (filteredGraphNodes.length > 0 && !initialLoadComplete) {
setTimeout(() => {
initialLoadComplete = true;
}, 100);
}
}));
// Track current path and events
let currentPath: string[] = [];
let rootEvents: EventInstance[] = [];
let subsystemEvents: EventInstance[] = [];
// Update event nodes - show root events at root, subsystem events inside subsystems
// Note: No isSyncing check here - this only updates eventNodes array,
// doesn't write to stores, so no risk of infinite loops
function updateEventNodes() {
const events = currentPath.length === 0 ? rootEvents : subsystemEvents;
eventNodes = events.map(toEventNode);
}
// Subscribe to path changes
cleanups.push(graphStore.currentPath.subscribe((path) => {
currentPath = path;
updateEventNodes();
// Clear grid and routes when navigating - forces full rebuild for new context
routingStore.clearContext();
}));
// Subscribe to root-level events (eventStore)
cleanups.push(eventStore.eventsArray.subscribe((events: EventInstance[]) => {
rootEvents = events;
updateEventNodes();
}));
// Subscribe to subsystem events (graphStore)
cleanups.push(graphStore.subsystemEvents.subscribe((eventsMap: Map<string, EventInstance>) => {
subsystemEvents = Array.from(eventsMap.values());
updateEventNodes();
}));
// Subscribe to annotations (filtered by current navigation context)
cleanups.push(graphStore.annotations.subscribe((annotationsMap: Map<string, Annotation>) => {
annotationNodes = Array.from(annotationsMap.values()).map(toAnnotationNode);
}));
// Subscribe to current connections (filtered by current navigation context)
cleanups.push(graphStore.connections.subscribe((connections: Connection[]) => {
if (isSyncing) return;
// Preserve selection state from existing edges
const currentEdgeSelection = new Map(edges.map(e => [e.id, e.selected]));
edges = connections.map(conn => {
const edge = toFlowEdge(conn);
// Preserve selection state
const wasSelected = currentEdgeSelection.get(conn.id);
if (wasSelected) {
edge.selected = true;
}
return edge;
});
// Recalculate routes when connections change
// Debounced to coalesce rapid changes (paste, undo, bulk operations)
scheduleRoutingUpdate();
}));
// Track last snapped positions during drag for discrete routing updates
let lastDraggedPositions = new Map<string, { x: number; y: number }>();
// Handle node drag start - capture state for undo
function handleNodeDragStart({ nodes: draggedNodes }: { nodes: Node[] }) {
historyStore.beginDrag();
// Initialize last positions for all dragged nodes
lastDraggedPositions.clear();
for (const node of draggedNodes) {
const snappedX = Math.round(node.position.x / GRID_SIZE) * GRID_SIZE;
const snappedY = Math.round(node.position.y / GRID_SIZE) * GRID_SIZE;
lastDraggedPositions.set(node.id, { x: snappedX, y: snappedY });
}
}
// Handle node drag - reroute at discrete grid positions (only affected routes)
function handleNodeDrag({ nodes: draggedNodes }: { nodes: Node[] }) {
// Check if any node moved to a new grid position
const changedNodeIds = new Set<string>();
for (const node of draggedNodes) {
// Skip non-block nodes (events, annotations don't affect routing)
if (node.type !== 'pathview') continue;
const snappedX = Math.round(node.position.x / GRID_SIZE) * GRID_SIZE;
const snappedY = Math.round(node.position.y / GRID_SIZE) * GRID_SIZE;
const lastPos = lastDraggedPositions.get(node.id);
if (!lastPos || lastPos.x !== snappedX || lastPos.y !== snappedY) {
lastDraggedPositions.set(node.id, { x: snappedX, y: snappedY });
changedNodeIds.add(node.id);
// Incrementally update grid obstacle for this node
const width = node.measured?.width ?? node.width ?? 80;
const height = node.measured?.height ?? node.height ?? 40;
routingStore.updateNodeBounds(node.id, {
x: snappedX - width / 2,
y: snappedY - height / 2,
width,
height
});
}
}
// Only recalculate routes connected to moved nodes
if (changedNodeIds.size > 0) {
const connections = get(graphStore.connections);
routingStore.recalculateRoutesForNodes(changedNodeIds, connections, getPortInfo);
}
}
// Handle node drag end - sync position back to store and finalize undo entry
function handleNodeDragStop({ targetNode }: { targetNode: Node | null; nodes: Node[]; event: MouseEvent | TouchEvent }) {
// Clear drag position tracking
lastDraggedPositions.clear();
if (targetNode?.id && targetNode?.position) {
isSyncing = true;
// Check node type and update appropriate store
if (targetNode.type === 'eventNode') {
if (graphStore.isAtRoot()) {
eventStore.updateEventPosition(targetNode.id, targetNode.position);
} else {
graphStore.updateSubsystemEventPosition(targetNode.id, targetNode.position);
}
} else if (targetNode.type === 'annotation') {
graphStore.updateAnnotationPosition(targetNode.id, targetNode.position);
} else {
graphStore.updateNodePosition(targetNode.id, targetNode.position);
}
isSyncing = false;
}
historyStore.endDrag();
// Update routing context and recalculate routes (final)
updateRoutingContext();
}
// Handle node and edge delete
function handleDelete({ nodes: deletedNodes, edges: deletedEdges }: { nodes: Node[]; edges: Edge[] }) {
if (deletedNodes.length === 0 && deletedEdges.length === 0) return;
isSyncing = true;
// Wrap in historyStore.mutate for undo/redo support
historyStore.mutate(() => {
// Handle deleted nodes - distinguish between blocks, events, and annotations
// Only remove if the item actually exists in the store (guards against false deletions from navigation)
deletedNodes.forEach((node) => {
if (node.type === 'eventNode') {
if (graphStore.isAtRoot()) {
if (eventStore.getEvent(node.id)) {
eventStore.removeEvent(node.id);
}
} else {
if (graphStore.getSubsystemEvent(node.id)) {
graphStore.removeSubsystemEvent(node.id);
}
}
} else if (node.type === 'annotation') {
if (graphStore.getAnnotation(node.id)) {
graphStore.removeAnnotation(node.id);
}
} else {
if (graphStore.getNode(node.id)) {
graphStore.removeNode(node.id);
portCounts.delete(node.id);
}
}
});
// Handle deleted edges
deletedEdges.forEach((edge) => {
const currentConnections = get(graphStore.connections);
let conn = currentConnections.find((c) => c.id === edge.id);
// If ID doesn't match, try to find by source/target handles
if (!conn && edge.sourceHandle && edge.targetHandle) {
const sourceMatch = edge.sourceHandle.match(/-output-(\d+)$/);
const targetMatch = edge.targetHandle.match(/-input-(\d+)$/);
if (sourceMatch && targetMatch) {
const sourcePortIndex = parseInt(sourceMatch[1], 10);
const targetPortIndex = parseInt(targetMatch[1], 10);
conn = currentConnections.find(
(c) =>
c.sourceNodeId === edge.source &&
c.sourcePortIndex === sourcePortIndex &&
c.targetNodeId === edge.target &&
c.targetPortIndex === targetPortIndex
);
}
}
if (conn) {
graphStore.removeConnection(conn.id);
}
});
});
// Filter out deleted nodes from current node arrays
const deletedIds = new Set(deletedNodes.map(n => n.id));
blockNodes = blockNodes.filter(n => !deletedIds.has(n.id));
eventNodes = eventNodes.filter(n => !deletedIds.has(n.id));
annotationNodes = annotationNodes.filter(n => !deletedIds.has(n.id));
// Force sync edges from store after deletion
const afterConnections = get(graphStore.connections);
edges = afterConnections.map(toFlowEdge);
isSyncing = false;
}
// Handle new connections
function handleConnect(connection: FlowConnection) {
if (!connection.source || !connection.target) return;
if (!connection.sourceHandle || !connection.targetHandle) return;
const sourceMatch = connection.sourceHandle.match(/-output-(\d+)$/);
const targetMatch = connection.targetHandle.match(/-input-(\d+)$/);
if (sourceMatch && targetMatch) {
historyStore.mutate(() => {
const sourcePortIndex = parseInt(sourceMatch[1], 10);
let targetPortIndex = parseInt(targetMatch[1], 10);
// Check if the target port is already connected
const currentConnections = get(graphStore.connections);
const isPortOccupied = currentConnections.some(
(c) => c.targetNodeId === connection.target && c.targetPortIndex === targetPortIndex
);
if (isPortOccupied) {
// Find the first available port instead
const availablePort = findFirstAvailableInputPort(connection.target);
if (availablePort !== null) {
// Use the first available port
targetPortIndex = availablePort;
} else {
// No available port - check if we can create a new one
const graphNodes = get(graphStore.nodesArray);
const targetNode = graphNodes.find((n) => n.id === connection.target);
if (!targetNode) return;
const typeDef = nodeRegistry.get(targetNode.type);
if (!typeDef || typeDef.ports.maxInputs !== null) {
// Can't create new port, abort
return;
}
// Create a new port and use it
graphStore.addInputPort(connection.target);
targetPortIndex = targetNode.inputs.length; // The new port index
}
}
// addConnection uses current navigation context automatically
graphStore.addConnection(
connection.source,
sourcePortIndex,
connection.target,
targetPortIndex
);
});
}
}
// Handle selection changes - sync from SvelteFlow to stores
// Uses direct setters to avoid triggering back to SvelteFlow
function handleSelectionChange({ nodes: selectedNodes }: { nodes: Node[]; edges: Edge[] }) {
const selectedBlockIds = new Set<string>();
const selectedEventIdSet = new Set<string>();
selectedNodes?.forEach((node) => {
if (node.type === 'eventNode') {
selectedEventIdSet.add(node.id);
} else {
// Both regular nodes and annotations go into selectedBlockIds
selectedBlockIds.add(node.id);
}
});
// Update stores directly (bypasses trigger-based functions)
graphSelectedNodeIds.set(selectedBlockIds);
setEventSelection(selectedEventIdSet);
}
// Track file drag state for drop zone indicator
let isFileDragOver = $state(false);
let dragCounter = 0; // Counter to handle nested elements
function hasFiles(event: DragEvent): boolean {
return event.dataTransfer?.types.includes('Files') ?? false;
}
function handleDragEnter(event: DragEvent) {
if (hasFiles(event)) {
dragCounter++;
isFileDragOver = true;
}
}
function handleDragLeave(event: DragEvent) {
if (hasFiles(event)) {
dragCounter--;
if (dragCounter === 0) {
isFileDragOver = false;
}
}
}
// Handle drop from node library - delegates to registered handler inside SvelteFlow context
function handleDrop(event: DragEvent) {
event.preventDefault();
// Reset file drag state
dragCounter = 0;
isFileDragOver = false;
dropTargetBridge.handleDrop(event);
}
function handleDragOver(event: DragEvent) {
event.preventDefault();
if (event.dataTransfer) {
event.dataTransfer.dropEffect = 'copy';
}
}
// Reference to flow canvas for coordinate conversion
let canvasEl: HTMLDivElement;
// Context menu handlers - SvelteFlow passes { event, node/edge } objects
function handleNodeContextMenu({ event, node }: { event: MouseEvent; node: Node }) {
event.preventDefault();
// Check if this is an event node
if (node.type === 'eventNode') {
contextMenuStore.openForEvent(node.id, { x: event.clientX, y: event.clientY });
return;
}
// Check if this is an annotation
if (node.type === 'annotation') {
contextMenuStore.openForAnnotation(node.id, { x: event.clientX, y: event.clientY });
return;
}
// Check if there are multiple selected nodes
const selectedNodes = nodes.filter(n => n.selected);
if (selectedNodes.length > 1 && selectedNodes.some(n => n.id === node.id)) {
// Multiple selection - show selection context menu
contextMenuStore.openForSelection(
selectedNodes.map(n => n.id),
{ x: event.clientX, y: event.clientY }
);
} else {
// Single node context menu
contextMenuStore.openForNode(node.id, { x: event.clientX, y: event.clientY });
}
}
function handleEdgeContextMenu({ event, edge }: { event: MouseEvent; edge: Edge }) {
event.preventDefault();
contextMenuStore.openForEdge(edge.id, { x: event.clientX, y: event.clientY });
}
function handlePaneContextMenu({ event }: { event: MouseEvent }) {
event.preventDefault();
contextMenuStore.openForCanvas({ x: event.clientX, y: event.clientY });
}
function handleCanvasDoubleClick(event: MouseEvent) {
// Only trigger fit view if clicking on the canvas background (not on nodes/edges)
const target = event.target as HTMLElement;
if (target.closest('.svelte-flow__pane')) {
triggerFitView();
}
}
</script>
<svelte:window onkeydown={handleKeydown} />
<div
bind:this={canvasEl}
class="flow-canvas"
role="application"
aria-label="Flow canvas"
ondragover={handleDragOver}
ondragenter={handleDragEnter}
ondragleave={handleDragLeave}
ondblclick={handleCanvasDoubleClick}
onmousemove={handleMouseMove}
>
{#if isFileDragOver}
<div class="drop-zone-overlay">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
<polyline points="7 10 12 15 17 10"/>
<line x1="12" y1="15" x2="12" y2="3"/>
</svg>
</div>