dioxus-flow 0.1.3

A react-flow-like node graph component library for Dioxus
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! The [`Canvas`] and [`Flow`] components: canvas, pan/zoom, pointer state
//! machine, and the node/edge render layers.
//!
//! [`Canvas`] is the lower layer: a pannable/zoomable surface with the shared
//! [`FlowCore`] context, the pane gesture state machine, and nothing drawn on
//! it. [`Flow`] builds the node/edge layers, connection gesture defaults and
//! keyboard handling on top. Applications with their own node/edge rendering
//! (custom editors, seat-based ports…) can use [`Canvas`] directly and draw
//! into its `world` slot.

use std::collections::HashMap;
use std::rc::Rc;
use std::sync::atomic::{AtomicUsize, Ordering};

use dioxus::html::geometry::WheelDelta;
use dioxus::html::input_data::MouseButton;
use dioxus::prelude::*;

use crate::edge::{EdgeItem, EdgeMarkers, EdgeViewCtx, HANDLE_RIM};
use crate::node::{NodeItem, NodeViewCtx};
use crate::path::connection_path;
use crate::state::{
    orient_connection, ConnectionState, DragState, FlowApi, FlowConfig, FlowCore, FlowHandle,
    Interaction,
};
use crate::types::{
    AnchorMode, ConnectEnd, Connection, DeleteRequest, Edge, HandleKey, HandleKind, Id, Node,
    NodeGeom, Point, Rect, Viewport,
};

/// The component styles [`Canvas`] injects at runtime, public so that tests
/// and server-side renderers can install the same sheet themselves.
pub static STYLE: &str = include_str!("style.css");

static NEXT_IID: AtomicUsize = AtomicUsize::new(0);

fn client_point(coords: dioxus::html::geometry::ClientPoint) -> Point {
    Point::new(coords.x, coords.y)
}

/// How a wheel notch converts to pixels, per delta unit. A notch reports
/// lines on Firefox and pixels on Chromium; without the conversion one notch
/// moves the canvas by three pixels.
fn wheel_pixels(delta: WheelDelta, page: f64) -> Point {
    match delta {
        WheelDelta::Pixels(v) => Point::new(v.x, v.y),
        WheelDelta::Lines(v) => Point::new(v.x * 16.0, v.y * 16.0),
        WheelDelta::Pages(v) => {
            let scale = page.max(240.0);
            Point::new(v.x * scale, v.y * scale)
        }
    }
}

/// Exponent per scrolled pixel while pinch-zooming (ctrl/meta + wheel, which
/// is also what browsers report for a trackpad pinch).
const PINCH_ZOOM_SENSITIVITY: f64 = 0.0025;

/// Properties for [`Canvas`].
#[derive(Clone, PartialEq, Props)]
pub struct CanvasProps {
    #[props(default = 0.25)]
    pub min_zoom: f64,
    #[props(default = 4.0)]
    pub max_zoom: f64,
    /// Pan the canvas by dragging empty space.
    #[props(default = true)]
    pub pan_on_drag: bool,
    /// Zoom with the mouse wheel / trackpad. Only consulted when
    /// `pan_on_scroll` is off.
    #[props(default = true)]
    pub zoom_on_scroll: bool,
    /// Scrolling pans instead of zooming (shift swaps the axis, ctrl/meta —
    /// a trackpad pinch included — zooms about the pointer). On by default, so
    /// a two-finger trackpad drag pans. Takes precedence over
    /// `zoom_on_scroll`; set it to `false` for wheel-zoom.
    #[props(default = true)]
    pub pan_on_scroll: bool,
    /// Master switch for node dragging (read by [`Flow`]'s node layer).
    #[props(default = true)]
    pub nodes_draggable: bool,
    /// How far (screen px) a press on a node must travel before it moves the
    /// node, so a sloppy click never nudges one.
    #[props(default = 0.0)]
    pub drag_threshold: f64,
    /// Snap radius (screen px) for completing a connection near a handle.
    #[props(default = 28.0)]
    pub connection_radius: f64,
    #[props(default = 0.12)]
    pub fit_view_padding: f64,
    /// `id` attribute for the root element, so applications can find, focus,
    /// measure, or capture pointers to the canvas by id.
    pub id: Option<String>,
    /// Accessible name for the canvas.
    #[props(default = "Node graph".to_string())]
    pub aria_label: String,
    /// Extra classes for the root element.
    pub class: Option<String>,
    /// A primary press reaching the pane, before the pane decides to pan:
    /// the hook for application-level pane gestures (marquee selection,
    /// pulling a connection from a node border…). A handler that starts one
    /// claims the pointer with [`FlowCore::claim_pointer`]; the pane then
    /// leaves this press alone.
    pub on_pane_press: Option<Callback<Event<PointerData>>>,
    /// The caller's edges, when it has any (the [`Flow`] layers and the
    /// default connect behavior read and write these through the core).
    pub edges: Option<Signal<Vec<Edge>>>,
    /// Node geometry snapshot, when the caller renders nodes ([`Flow`] passes
    /// its memo; standalone canvases leave it empty).
    pub geoms: Option<Memo<Vec<NodeGeom>>>,
    /// Type-erased "deselect all nodes" for pane clicks and edge selection,
    /// provided by [`Flow`] which knows the node type.
    pub deselect_nodes: Option<Callback<()>>,
    /// Called when the user completes a connection between two handles. When
    /// absent, the edge is added to `edges` automatically.
    pub on_connect: Option<EventHandler<Connection>>,
    /// A connection drag has left a handle (started, not completed).
    pub on_connect_start: Option<EventHandler<HandleKey>>,
    /// A connection drag ended — wherever it ended. `connection` is `None`
    /// when the release was over nothing, and the point says where: the hook
    /// for "drop on empty canvas to create the node there".
    pub on_connect_end: Option<EventHandler<ConnectEnd>>,
    /// The application's say over which connections may complete. A target
    /// that fails is never offered as a snap and never completes.
    pub is_valid_connection: Option<Callback<Connection, bool>>,
    /// A node drag actually began (the press travelled past
    /// `drag_threshold`), with the ids being dragged: the moment to snapshot
    /// for undo.
    pub on_node_drag_start: Option<EventHandler<Vec<Id>>>,
    /// A node drag ended, with the ids that were dragged. Positions are
    /// already final in the node list: the moment to snap, settle, persist.
    pub on_node_drag_stop: Option<EventHandler<Vec<Id>>>,
    /// Click on empty canvas; the point is in flow coordinates. Fires only
    /// when the press neither travelled nor was claimed by content.
    pub on_pane_click: Option<EventHandler<Point>>,
    /// Double-click on the canvas; the point is in flow coordinates. The
    /// pane cannot tell content from paper here — an application that must
    /// can hit-test the client point itself before acting.
    pub on_pane_double_click: Option<EventHandler<Point>>,
    /// Keyboard events reaching the canvas root, after the canvas's own
    /// Escape handling. [`Flow`] wires Delete/Backspace through this.
    pub on_canvas_key_down: Option<Callback<Event<KeyboardData>>>,
    /// Pointer moves while a node drag is in flight, in flow coordinates.
    /// [`Flow`] applies the drag to its typed node list through this.
    pub on_drag_move: Option<Callback<Point>>,
    /// Content drawn inside the viewport transform, in flow coordinates.
    pub world: Option<Element>,
    /// Overlays drawn over the canvas in screen coordinates ([`Background`],
    /// [`Controls`], [`MiniMap`], or your own — they can call [`use_flow`]).
    ///
    /// [`Background`]: crate::Background
    /// [`Controls`]: crate::Controls
    /// [`MiniMap`]: crate::MiniMap
    /// [`use_flow`]: crate::use_flow
    pub children: Element,
}

/// The pannable/zoomable surface every flow is drawn on.
///
/// Owns the [`FlowCore`] context, the container geometry, and the pane
/// gestures: pan (drag or scroll), zoom (scroll or pinch), pane clicks, and
/// the in-flight connection state machine that [`crate::Handle`]s feed.
/// Draws nothing itself: [`Flow`] passes its node/edge layers through the
/// `world` slot, and an application using [`Canvas`] directly renders its own
/// content there (in flow coordinates) and overlays as `children` (in screen
/// coordinates).
///
/// An application-level gesture that starts on content inside the canvas can
/// take the pointer away from the pane with [`FlowCore::claim_pointer`]; the
/// pane then neither pans nor reports a pane click for that press.
#[allow(non_snake_case)]
pub fn Canvas(props: CanvasProps) -> Element {
    let core = props.use_core();
    props.render(core)
}

impl CanvasProps {
    // Both Canvas and Flow call these hooks in their own scope. Flow must own
    // the state its effects and event handlers read, rather than borrow it
    // from a child Canvas that can be dropped first.
    fn use_core(&self) -> FlowCore {
        let viewport = use_signal(Viewport::default);
        let container = use_signal(|| Rect::ZERO);
        let interaction = use_signal(Interaction::default);
        let connection = use_signal(|| None::<ConnectionState>);
        let handles = use_signal(HashMap::new);
        let config = use_signal(FlowConfig::default);
        let drag = use_signal(DragState::default);
        let epoch = use_signal(|| 0u64);
        let pending_sizes = use_signal(Vec::new);
        let size_flush_queued = use_signal(|| false);
        let pending_handles = use_signal(Vec::new);
        let handle_flush_queued = use_signal(|| false);
        let snap_key = use_memo(move || {
            connection
                .read()
                .as_ref()
                .and_then(|c| c.snap.as_ref())
                .map(|s| s.key.clone())
        });
        let connect_from = use_memo(move || connection.read().as_ref().map(|c| c.from.clone()));
        let overlay_insets = use_signal(HashMap::new);
        let own_edges = use_signal(Vec::new);
        let edges = self.edges.unwrap_or(own_edges);
        let empty_geoms = use_memo(Vec::new);
        let geoms = self.geoms.unwrap_or(empty_geoms);
        let noop_deselect = use_callback(move |_: ()| {});
        let deselect_nodes = self.deselect_nodes.unwrap_or(noop_deselect);

        let core = use_hook(|| FlowCore {
            iid: NEXT_IID.fetch_add(1, Ordering::Relaxed),
            viewport,
            container,
            interaction,
            connection,
            handles,
            edges,
            geoms,
            config,
            drag,
            epoch,
            snap_key,
            connect_from,
            deselect_nodes,
            overlay_insets,
            pending_sizes,
            size_flush_queued,
            pending_handles,
            handle_flush_queued,
            on_connect_start: self.on_connect_start,
            valid_connection: self.is_valid_connection,
        });
        use_context_provider(|| core);

        core
    }

    fn render(self, core: FlowCore) -> Element {
        let Self {
            min_zoom,
            max_zoom,
            fit_view_padding,
            pan_on_drag,
            zoom_on_scroll,
            pan_on_scroll,
            nodes_draggable,
            drag_threshold,
            connection_radius,
            id,
            aria_label,
            class,
            on_pane_press,
            on_connect,
            on_connect_end,
            on_node_drag_start,
            on_node_drag_stop,
            on_pane_click,
            on_pane_double_click,
            on_canvas_key_down,
            on_drag_move,
            world,
            children,
            ..
        } = self;
        let FlowCore {
            viewport,
            container,
            interaction,
            connection,
            mut config,
            drag,
            edges,
            deselect_nodes,
            ..
        } = core;

        // Mirror config props into the shared config signal.
        let cfg = FlowConfig {
            min_zoom,
            max_zoom,
            pan_on_drag,
            zoom_on_scroll,
            pan_on_scroll,
            nodes_draggable,
            drag_threshold,
            connection_radius,
            fit_view_padding,
        };
        if *config.peek() != cfg {
            config.set(cfg);
        }

        // Container geometry tracking.
        let mounted: Signal<Option<Rc<MountedData>>> = use_signal(|| None);
        let refresh_rect = use_callback(move |_: ()| {
            let element = mounted.peek().clone();
            let mut container = container;
            if let Some(element) = element {
                spawn(async move {
                    if let Ok(rect) = element.get_client_rect().await {
                        let rect =
                            Rect::new(rect.origin.x, rect.origin.y, rect.width(), rect.height());
                        if *container.peek() != rect {
                            container.set(rect);
                        }
                    }
                });
            }
        });

        // ---- Pointer state machine ----------------------------------------

        let end_gesture = use_callback(move |_: ()| {
            let mut interaction = interaction;
            let mut connection = connection;
            if *interaction.peek() != Interaction::None {
                interaction.set(Interaction::None);
            }
            if connection.peek().is_some() {
                connection.set(None);
            }
            let mut drag = drag;
            let mut state = drag.write();
            state.pointer_id = None;
            state.suppress_click = false;
        });

        let on_pointer_down = move |evt: Event<PointerData>| {
            refresh_rect.call(());
            core.cancel_animations();
            // A node, handle, edge or overlay may have claimed this pointer
            // already (children's handlers run first while bubbling).
            if *interaction.peek() != Interaction::None {
                return;
            }
            if evt.trigger_button() != Some(MouseButton::Primary) {
                return;
            }
            // Offer the press to the application first; it may claim the pointer
            // for a gesture of its own, in which case the pane stays out of it.
            if let Some(handler) = &on_pane_press {
                handler.call(evt.clone());
                if *interaction.peek() != Interaction::None {
                    return;
                }
            }
            let client = client_point(evt.client_coordinates());
            {
                let mut drag = drag;
                let mut state = drag.write();
                state.pointer_id = Some(evt.pointer_id());
                state.origin_client = client;
                state.last_client = client;
                state.moved = false;
                state.suppress_click = false;
                state.grabs.clear();
            }
            let mut interaction = interaction;
            if pan_on_drag {
                interaction.set(Interaction::Pan);
            } else {
                interaction.set(Interaction::PanePressed);
            }
        };

        let on_pointer_move = move |evt: Event<PointerData>| {
            let current = *interaction.peek();
            if current == Interaction::None {
                return;
            }
            // A gesture belongs to the pointer that started it: a second finger
            // must not steer the first one's pan.
            if drag
                .peek()
                .pointer_id
                .is_some_and(|id| id != evt.pointer_id())
            {
                return;
            }
            // Self-heal: if the pointer was released outside the container we
            // never saw the pointerup.
            if evt.held_buttons().is_empty() {
                end_gesture.call(());
                return;
            }
            let client = client_point(evt.client_coordinates());
            match current {
                Interaction::Pan => {
                    let delta = {
                        let mut drag = drag;
                        let mut state = drag.write();
                        let delta = client - state.last_client;
                        state.last_client = client;
                        state.moved = true;
                        delta
                    };
                    let mut viewport = viewport;
                    let vp = *viewport.peek();
                    viewport.set(vp.panned(delta));
                }
                Interaction::DragNode => {
                    // The press has to travel before it moves anything, so a
                    // sloppy click never nudges a node. Crossing the threshold is
                    // the moment the drag really starts — the snapshot-for-undo
                    // moment — so that is when `on_node_drag_start` fires.
                    let began = {
                        let mut drag = drag;
                        let mut state = drag.write();
                        state.last_client = client;
                        let travelled = state.origin_client.distance(client);
                        let passed = state.moved || travelled >= config.peek().drag_threshold;
                        let began = passed && !state.moved;
                        if passed {
                            state.moved = true;
                        }
                        if !passed {
                            return;
                        }
                        began
                    };
                    if began {
                        if let Some(handler) = &on_node_drag_start {
                            let ids: Vec<Id> =
                                drag.peek().grabs.iter().map(|(id, _)| id.clone()).collect();
                            handler.call(ids);
                        }
                    }
                    let flow = core.client_to_flow(client);
                    if let Some(handler) = &on_drag_move {
                        handler.call(flow);
                    }
                }
                Interaction::Connect => {
                    let flow = core.client_to_flow(client);
                    let mut connection = connection;
                    let from = connection.peek().as_ref().map(|c| c.from.clone());
                    if let Some(from) = from {
                        let snap = core.find_snap(&from, flow);
                        connection.set(Some(ConnectionState {
                            from,
                            cursor: flow,
                            snap,
                        }));
                    }
                }
                _ => {}
            }
        };

        let on_pointer_up = move |evt: Event<PointerData>| {
            if drag
                .peek()
                .pointer_id
                .is_some_and(|id| id != evt.pointer_id())
            {
                return;
            }
            let current = *interaction.peek();
            match current {
                // A click on empty canvas (no pan movement happened).
                Interaction::Pan | Interaction::PanePressed => {
                    let state = drag.peek().clone();
                    let is_click = (current == Interaction::PanePressed || !state.moved)
                        && !state.suppress_click;
                    if is_click {
                        let client = client_point(evt.client_coordinates());
                        let flow = core.client_to_flow(client);
                        if !evt.modifiers().shift() {
                            deselect_nodes.call(());
                            deselect_edges(edges);
                        }
                        if let Some(handler) = &on_pane_click {
                            handler.call(flow);
                        }
                    }
                }
                Interaction::Connect => {
                    let done = connection.peek().clone();
                    if let Some(done) = done {
                        let completed = done
                            .snap
                            .as_ref()
                            .map(|snap| orient_connection(&done.from, &snap.key));
                        if let Some(conn) = completed.clone() {
                            match &on_connect {
                                Some(handler) => handler.call(conn),
                                None => add_edge_for_connection(edges, conn),
                            }
                        }
                        // However it ended: the release point plus what (if
                        // anything) completed. A `None` connection with a point is
                        // the drop-on-empty-canvas hook.
                        if let Some(handler) = &on_connect_end {
                            let client = client_point(evt.client_coordinates());
                            handler.call(ConnectEnd {
                                point: core.client_to_flow(client),
                                connection: completed,
                            });
                        }
                    }
                }
                Interaction::DragNode if drag.peek().moved => {
                    if let Some(handler) = &on_node_drag_stop {
                        let ids: Vec<Id> =
                            drag.peek().grabs.iter().map(|(id, _)| id.clone()).collect();
                        handler.call(ids);
                    }
                }
                _ => {}
            }
            end_gesture.call(());
        };

        let on_wheel = move |evt: Event<WheelData>| {
            let config = *config.peek();
            if !config.pan_on_scroll && !config.zoom_on_scroll {
                return;
            }
            evt.prevent_default();
            core.cancel_animations();
            let client = client_point(evt.client_coordinates());
            let page = container.peek().height;
            let delta = wheel_pixels(evt.delta(), page);
            let modifiers = evt.modifiers();
            // A pinch (or ctrl/meta scroll) zooms about the pointer in either
            // scroll mode.
            if config.pan_on_scroll {
                if modifiers.ctrl() || modifiers.meta() {
                    if delta.y != 0.0 {
                        let factor = (-delta.y * PINCH_ZOOM_SENSITIVITY).exp();
                        core.zoom_by(factor, Some(client), 0);
                    }
                    return;
                }
                let mut viewport = viewport;
                let vp = *viewport.peek();
                // Shift turns a vertical wheel into horizontal travel, as
                // everywhere else.
                let by = if modifiers.shift() && delta.x == 0.0 {
                    Point::new(-delta.y, 0.0)
                } else {
                    Point::new(-delta.x, -delta.y)
                };
                viewport.set(vp.panned(by));
                return;
            }
            if delta.y == 0.0 {
                return;
            }
            let factor = (-delta.y * 0.0022).exp().clamp(0.5, 2.0);
            core.zoom_by(factor, Some(client), 0);
        };

        let on_key_down = move |evt: Event<KeyboardData>| {
            if evt.key() == Key::Escape {
                end_gesture.call(());
            }
            if let Some(handler) = &on_canvas_key_down {
                handler.call(evt);
            }
        };

        // Reading `interaction` here keeps cursor feedback classes fresh; it only
        // changes on gesture start/end, never per pointer-move frame.
        let gesture = *interaction.read();
        let root_class = format!(
            "dioxus-flow{}{}",
            match gesture {
                Interaction::Pan => " df-panning",
                Interaction::Connect => " df-connecting",
                _ => "",
            },
            class
                .as_deref()
                .map(|c| format!(" {c}"))
                .unwrap_or_default()
        );

        rsx! {
            FlowStyles {}
            div {
                id,
                class: root_class,
                tabindex: "0",
                role: "application",
                aria_label,
                onmounted: move |evt| {
                    let mut mounted = mounted;
                    mounted.set(Some(evt.data()));
                    refresh_rect.call(());
                },
                onresize: move |_| refresh_rect.call(()),
                onpointerdown: on_pointer_down,
                onpointermove: on_pointer_move,
                onpointerup: on_pointer_up,
                onpointercancel: move |evt: Event<PointerData>| {
                    let owner = drag.peek().pointer_id;
                    if owner.is_none() || owner == Some(evt.pointer_id()) {
                        end_gesture.call(());
                    }
                },
                onwheel: on_wheel,
                ondoubleclick: move |evt: Event<MouseData>| {
                    if let Some(handler) = &on_pane_double_click {
                        let client = client_point(evt.client_coordinates());
                        handler.call(core.client_to_flow(client));
                    }
                },
                onkeydown: on_key_down,
                ViewportPane { {world} }
                {children}
            }
        }
    }
}

#[component]
fn FlowStyles() -> Element {
    rsx! { document::Style { "{STYLE}" } }
}

/// An interactive node-graph canvas, in the spirit of react-flow.
///
/// Nodes and edges are owned by the caller as signals; the flow mutates them
/// in response to user interaction (dragging, selection, connecting) and the
/// caller can mutate them at any time (adding nodes, changing data…).
///
/// ```ignore
/// let nodes = use_signal(|| vec![
///     Node::new("1", "Input", (0.0, 0.0)).node_type("input"),
///     Node::new("2", "Process", (0.0, 120.0)),
/// ]);
/// let edges = use_signal(|| vec![Edge::new("1", "2").animated(true)]);
/// rsx! {
///     Flow { nodes, edges, fit_view: true,
///         Background {}
///         Controls {}
///         MiniMap {}
///     }
/// }
/// ```
#[component]
pub fn Flow<T: Clone + PartialEq + 'static>(
    /// The nodes, owned by the caller.
    nodes: Signal<Vec<Node<T>>>,
    /// The edges, owned by the caller.
    edges: Signal<Vec<Edge>>,
    /// How edges find their endpoints: [`AnchorMode::Handles`] (default) or
    /// [`AnchorMode::Seats`] — solver-packed positions around each node's rim,
    /// drawn with rim-aware curves and beads.
    #[props(default)]
    anchor: AnchorMode,
    #[props(default = 0.25)] min_zoom: f64,
    #[props(default = 4.0)] max_zoom: f64,
    /// Pan the canvas by dragging empty space.
    #[props(default = true)]
    pan_on_drag: bool,
    /// Zoom with the mouse wheel / trackpad. Only consulted when
    /// `pan_on_scroll` is off.
    #[props(default = true)]
    zoom_on_scroll: bool,
    /// Scrolling pans instead of zooming (ctrl/meta or a pinch zooms). On by
    /// default, so a two-finger trackpad drag pans; set it to `false` for
    /// wheel-zoom.
    #[props(default = true)]
    pan_on_scroll: bool,
    /// Master switch for node dragging (individual nodes can also opt out).
    #[props(default = true)]
    nodes_draggable: bool,
    /// How far (screen px) a press on a node must travel before it moves the
    /// node, so a sloppy click never nudges one.
    #[props(default = 0.0)]
    drag_threshold: f64,
    /// Snap radius (screen px) for completing a connection near a handle.
    #[props(default = 28.0)]
    connection_radius: f64,
    /// Fit all nodes into view once nodes are measured after mount.
    #[props(default = false)]
    fit_view: bool,
    #[props(default = 0.12)] fit_view_padding: f64,
    /// Delete selected nodes/edges with Delete/Backspace.
    #[props(default = true)]
    delete_key: bool,
    /// `id` attribute for the root element.
    id: Option<String>,
    /// Extra classes for the root element.
    class: Option<String>,
    /// Custom renderer for node contents. Receives a [`NodeViewCtx`]; fall
    /// back to [`crate::DefaultNodeView`] for types you don't customize.
    node_view: Option<Callback<NodeViewCtx<T>, Element>>,
    /// Custom renderer for edges (SVG content).
    edge_view: Option<Callback<EdgeViewCtx, Element>>,
    /// Called when the user completes a connection between two handles. When
    /// absent, the edge is added automatically.
    on_connect: Option<EventHandler<Connection>>,
    /// A connection drag has left a handle (started, not completed).
    on_connect_start: Option<EventHandler<HandleKey>>,
    /// A connection drag ended — wherever it ended. `connection` is `None`
    /// when the release was over nothing, and the point says where: the hook
    /// for "drop on empty canvas to create the node there".
    on_connect_end: Option<EventHandler<ConnectEnd>>,
    /// The application's say over which connections may complete. A target
    /// that fails is never offered as a snap and never completes.
    is_valid_connection: Option<Callback<Connection, bool>>,
    /// A node drag actually began (the press travelled past
    /// `drag_threshold`), with the ids being dragged: the moment to snapshot
    /// for undo.
    on_node_drag_start: Option<EventHandler<Vec<Id>>>,
    /// A node drag ended, with the ids that were dragged. Positions are
    /// already final in the node list: the moment to snap, settle, persist.
    on_node_drag_stop: Option<EventHandler<Vec<Id>>>,
    /// Called when Delete/Backspace is pressed with a selection. When absent,
    /// the selection (plus connected edges) is deleted automatically; when
    /// present, nothing is deleted — call
    /// [`FlowHandle::delete_selected`](crate::FlowHandle::delete_selected)
    /// from the handler to perform the default cascade (after confirming,
    /// snapshotting for undo…).
    on_delete: Option<EventHandler<DeleteRequest>>,
    on_node_click: Option<EventHandler<Id>>,
    on_edge_click: Option<EventHandler<Id>>,
    /// Click on empty canvas; the point is in flow coordinates.
    on_pane_click: Option<EventHandler<Point>>,
    /// Double-click on the canvas; the point is in flow coordinates.
    on_pane_double_click: Option<EventHandler<Point>>,
    /// Attach a [`FlowHandle`] (from [`crate::use_flow_handle`]) for
    /// programmatic control: fit view, zoom, auto-layout…
    handle: Option<FlowHandle<T>>,
    /// Overlays such as [`crate::Background`], [`crate::Controls`],
    /// [`crate::MiniMap`], or your own (they can call [`crate::use_flow`]).
    children: Element,
) -> Element {
    let geoms = use_memo(move || {
        nodes
            .read()
            .iter()
            .map(|node| NodeGeom {
                id: node.id.clone(),
                rect: node.rect(),
                selected: node.selected,
                source_side: node.source_side,
                target_side: node.target_side,
                measured: node.size.is_some() || node.measured.is_some(),
            })
            .collect::<Vec<_>>()
    });
    let deselect_nodes = use_callback(move |_: ()| {
        if nodes.peek().iter().any(|n| n.selected) {
            nodes.clone().with_mut(|nodes| {
                for node in nodes.iter_mut() {
                    node.selected = false;
                }
            });
        }
    });

    let mut canvas = CanvasProps::builder()
        .min_zoom(min_zoom)
        .max_zoom(max_zoom)
        .pan_on_drag(pan_on_drag)
        .zoom_on_scroll(zoom_on_scroll)
        .pan_on_scroll(pan_on_scroll)
        .nodes_draggable(nodes_draggable)
        .drag_threshold(drag_threshold)
        .connection_radius(connection_radius)
        .fit_view_padding(fit_view_padding)
        .id(id)
        .class(class)
        .edges(edges)
        .geoms(geoms)
        .deselect_nodes(deselect_nodes)
        .on_connect(on_connect)
        .on_connect_start(on_connect_start)
        .on_connect_end(on_connect_end)
        .is_valid_connection(is_valid_connection)
        .on_node_drag_start(on_node_drag_start)
        .on_node_drag_stop(on_node_drag_stop)
        .on_pane_click(on_pane_click)
        .on_pane_double_click(on_pane_double_click)
        .world(rsx! {
            match anchor {
                AnchorMode::Handles => rsx! {
                    EdgesLayer { edge_view, on_edge_click }
                    NodesLayer { nodes, node_view, on_node_click }
                },
                AnchorMode::Seats => rsx! {
                    SeatGraphLayers {
                        nodes,
                        node_view,
                        on_node_click,
                        edge_view,
                        on_edge_click,
                    }
                },
            }
            ConnectionLine {}
        })
        .children(children)
        .build();
    let core = canvas.inner.use_core();

    // Attach the programmatic handle, if provided.
    use_effect(move || {
        if let Some(handle) = handle {
            let mut inner = handle.inner;
            if inner.peek().is_none() {
                inner.set(Some(FlowApi { core, nodes }));
            }
        }
    });

    use_drop(move || {
        if let Some(handle) = handle {
            let mut inner = handle.inner;
            if inner.peek().is_some_and(|api| api.core == core) {
                inner.set(None);
            }
        }
    });

    // Initial fit-view.
    //
    // This used to wait for every node to report a measured size, which cannot
    // work now that the node layer is tiled: a tile the viewport cannot see is
    // never laid out, so the nodes in it never measure, and the fit would wait
    // forever. (The same wait could already hang on a node that was simply
    // unmeasurable.) Instead, fit to the best rects available — `Node::rect`
    // falls back to a declared or default size — and fit again as real
    // measurements arrive, until the bounds stop moving.
    //
    // Re-fitting is bounded twice over: it stops as soon as the bounds settle,
    // and it never survives the first gesture, so it cannot fight the user for
    // control of the viewport.
    let mut fits = use_signal(|| 0u8);
    // Both inputs to the fit, so that either one still settling re-fits. The
    // container matters as much as the bounds: a canvas whose height arrives a
    // frame after its width would otherwise be fitted against, and kept at,
    // the wrong viewport.
    let mut fitted: Signal<Option<(Rect, Rect)>> = use_signal(|| None);
    let mut touched = use_signal(|| false);
    use_effect(move || {
        if *core.interaction.read() != Interaction::None {
            touched.set(true);
        }
    });
    use_effect(move || {
        if !fit_view || *touched.peek() {
            return;
        }
        let container = *core.container.read();
        let bounds = geoms
            .read()
            .iter()
            .map(|geom| geom.rect)
            .reduce(|acc, rect| acc.union(&rect));
        let Some(bounds) = bounds else { return };
        if container.width <= 0.0 || container.height <= 0.0 {
            return;
        }
        // A first fit, then again only while either input is still moving
        // under it. Twelve is far more than settling takes, and caps any
        // chance of a loop.
        let same = |a: Rect, b: Rect| {
            (a.x - b.x).abs() < 1.0
                && (a.y - b.y).abs() < 1.0
                && (a.width - b.width).abs() < 1.0
                && (a.height - b.height).abs() < 1.0
        };
        let settled = fitted
            .peek()
            .is_some_and(|(b, c)| same(b, bounds) && same(c, container));
        if settled || *fits.peek() >= 12 {
            return;
        }
        let done = *fits.peek();
        fitted.set(Some((bounds, container)));
        fits.set(done + 1);
        core.fit_view(0);
    });

    let on_drag_move = use_callback(move |flow: Point| {
        let grabs = core.drag.peek().grabs.clone();
        let mut nodes = nodes;
        nodes.with_mut(|nodes| {
            for (id, grab) in &grabs {
                if let Some(node) = nodes.iter_mut().find(|n| &n.id == id) {
                    node.position = flow - *grab;
                }
            }
        });
    });

    let on_canvas_key_down = use_callback(move |evt: Event<KeyboardData>| match evt.key() {
        Key::Delete | Key::Backspace if delete_key => {
            let request = delete_request(nodes, core.edges);
            if request.nodes.is_empty() && request.edges.is_empty() {
                return;
            }
            match &on_delete {
                Some(handler) => handler.call(request),
                None => delete_selected(nodes, core.edges),
            }
        }
        _ => {}
    });

    canvas.inner.on_drag_move = Some(on_drag_move);
    canvas.inner.on_canvas_key_down = Some(on_canvas_key_down);
    canvas.inner.render(core)
}

/// The node layer sandwiched between seat-anchored edges and their beads.
///
/// One component so the three share one solve: the edge curves render under
/// the nodes, but the beads — the dots where a connection meets a rim — sit
/// over them, because a bead is threaded on the rim, not tucked behind it.
#[component]
fn SeatGraphLayers<T: Clone + PartialEq + 'static>(
    nodes: Signal<Vec<Node<T>>>,
    node_view: Option<Callback<NodeViewCtx<T>, Element>>,
    on_node_click: Option<EventHandler<Id>>,
    edge_view: Option<Callback<EdgeViewCtx, Element>>,
    on_edge_click: Option<EventHandler<Id>>,
) -> Element {
    let core = use_context::<FlowCore>();
    // The one expensive step, behind a memo: re-solves when node geometry or
    // the edge list changes, never on pan or zoom. Applications with their
    // own gesture policy run this solve themselves and hand the result to
    // [`SeatEdges`]; here the edges signal is the whole story.
    let anchors = use_memo(move || {
        let geoms = core.geoms.read();
        let frames: std::collections::BTreeMap<Id, Rect> = geoms
            .iter()
            .map(|geom| (geom.id.clone(), geom.rect))
            .collect();
        let links: Vec<crate::ports::Link> = core
            .edges
            .read()
            .iter()
            .map(|edge| crate::ports::Link {
                id: edge.id.clone(),
                start: crate::ports::Terminal::Node(edge.source.clone()),
                end: crate::ports::Terminal::Node(edge.target.clone()),
                start_seat: edge.source_seat,
                end_seat: edge.target_seat,
            })
            .collect();
        crate::ports::solve_ports(&frames, &links)
    });

    // `Flow`'s `edge_view` speaks the handle-mode context; hand it the seat
    // geometry through the same shape. Views that want the full rim-aware
    // geometry use [`SeatEdges`] directly.
    let adapted_edge_view = edge_view.map(|view| {
        Callback::new(move |ctx: crate::edge::SeatEdgeViewCtx| {
            view.call(EdgeViewCtx {
                edge: ctx.edge.clone(),
                source: ctx.anchors.start.point(),
                source_side: ctx.anchors.start.side(),
                target: ctx.anchors.end.point(),
                target_side: ctx.anchors.end.side(),
                path: crate::path::EdgePath {
                    d: ctx.geometry.path.clone(),
                    label: ctx.geometry.label,
                },
                // Seat-mode arrowheads are drawn geometry, not markers.
                marker_end: None,
            })
        })
    });

    let edges = core.edges;
    let solved = anchors.read();
    rsx! {
        crate::edge::SeatEdges {
            edges,
            anchors,
            edge_view: adapted_edge_view,
            on_edge_click,
        }
        crate::edge::SeatEdgeLabels { edges, anchors }
        NodesLayer { nodes, node_view, on_node_click }
        // The beads, over the nodes they are threaded on.
        svg { class: "df-edges df-ports", "aria-hidden": "true",
            for edge in edges.read().iter() {
                if let Some(pair) = solved.get(&edge.id) {
                    g {
                        key: "{edge.id}",
                        class: if edge.selected { "df-selected" },
                        circle {
                            class: "df-port",
                            cx: pair.start.x,
                            cy: pair.start.y,
                            r: crate::ports::PORT_RADIUS,
                        }
                        circle {
                            class: "df-port",
                            cx: pair.end.x,
                            cy: pair.end.y,
                            r: crate::ports::PORT_RADIUS,
                        }
                    }
                }
            }
        }
    }
}

/// The pannable/zoomable transform layer. Isolated so per-frame viewport
/// updates re-render only this tiny component, not the node/edge layers.
#[component]
fn ViewportPane(children: Element) -> Element {
    let core = use_context::<FlowCore>();
    let vp = *core.viewport.read();
    rsx! {
        div {
            class: "df-viewport",
            style: "transform: translate({vp.x}px, {vp.y}px) scale({vp.zoom});",
            {children}
        }
    }
}

/// A layer inside the canvas that shares the viewport transform: children are
/// laid out in flow coordinates. Render as a child of [`Canvas`] or [`Flow`]
/// for world-space overlays (annotations, guides, custom edge layers…).
#[component]
pub fn WorldLayer(class: Option<String>, children: Element) -> Element {
    let core = use_context::<FlowCore>();
    let vp = *core.viewport.read();
    let class = format!(
        "df-world-layer{}",
        class
            .as_deref()
            .map(|c| format!(" {c}"))
            .unwrap_or_default()
    );
    rsx! {
        div {
            class,
            style: "transform: translate({vp.x}px, {vp.y}px) scale({vp.zoom});",
            {children}
        }
    }
}

/// The nodes, grouped into world tiles.
///
/// The grouping is what lets a browser skip the graph it cannot see: panning
/// costs the same with 60 nodes on screen as with 950, because the engine
/// walks every node subtree under the viewport transform either way. A tile
/// carries `content-visibility: auto`, so one box off screen stands in for
/// everything inside it. See [`crate::tile`].
#[component]
fn NodesLayer<T: Clone + PartialEq + 'static>(
    nodes: Signal<Vec<Node<T>>>,
    node_view: Option<Callback<NodeViewCtx<T>, Element>>,
    on_node_click: Option<EventHandler<Id>>,
) -> Element {
    let core = use_context::<FlowCore>();
    let tiles = use_memo(move || {
        let nodes = nodes.read();
        // A node that has to paint above the graph raises its tile, because
        // containment makes each tile a stacking context and a raised node can
        // otherwise only rise above its own tile's siblings. Read inside the
        // memo, not captured from the render: a memo's closure is built once,
        // so a value captured here would be the one it saw on first render
        // forever, and a dragged node would never raise its tile.
        let grabbed = (*core.interaction.read() == Interaction::DragNode)
            .then(|| core.drag.peek().grabs.clone());
        crate::tile::tiles(nodes.iter().map(|node| {
            let raised = node.selected
                || grabbed
                    .as_ref()
                    .is_some_and(|grabs| grabs.iter().any(|(id, _)| id == &node.id));
            (node.rect(), raised)
        }))
    });
    // One borrow for the whole layer rather than one per node.
    let all = nodes.read();
    rsx! {
        div { class: "df-nodes",
            for tile in tiles.read().iter() {
                div {
                    key: "{tile.cell.0},{tile.cell.1}",
                    class: if tile.raised { "df-tile df-raised" } else { "df-tile" },
                    style: tile_style(tile),
                    for node in tile.members.iter().filter_map(|&i| all.get(i)) {
                        NodeItem::<T> {
                            key: "{node.id}",
                            nodes,
                            node: node.clone(),
                            origin: tile.origin(),
                            node_view,
                            on_node_click,
                        }
                    }
                }
            }
        }
    }
}

/// A tile's box, and the promise that lets the engine skip it.
///
/// `contain-intrinsic-size` is the tile's own measured box rather than a
/// guess: a skipped tile then reserves exactly the space it will occupy once
/// it comes back, so scrolling past one never shifts the graph.
fn tile_style(tile: &crate::tile::Tile) -> String {
    format!(
        "transform:translate({}px,{}px);width:{}px;height:{}px;\
         contain-intrinsic-size:{}px {}px;",
        tile.rect.x,
        tile.rect.y,
        tile.rect.width,
        tile.rect.height,
        tile.rect.width,
        tile.rect.height,
    )
}

#[component]
fn EdgesLayer(
    edge_view: Option<Callback<EdgeViewCtx, Element>>,
    on_edge_click: Option<EventHandler<Id>>,
) -> Element {
    let core = use_context::<FlowCore>();
    let edges = core.edges.read();
    let geoms = core.geoms.read();
    let handles = core.handles.read();
    let geom_by_id: HashMap<&str, &NodeGeom> =
        geoms.iter().map(|geom| (geom.id.as_str(), geom)).collect();
    // Borrowed lookup index: this layer re-renders every frame while a node
    // is dragged, and going through `resolve_anchor` would clone two key
    // Strings per edge per frame.
    let handle_idx: HashMap<(&str, HandleKind, &str), &crate::types::HandleGeom> = handles
        .iter()
        .map(|(key, geom)| ((key.node.as_str(), key.kind, key.id.as_str()), geom))
        .collect();
    let anchor = |geom: &NodeGeom, kind: HandleKind, handle_id: &Option<Id>| {
        let key = (geom.id.as_str(), kind, handle_id.as_deref().unwrap_or(""));
        crate::state::anchor_from_geom(handle_idx.get(&key).copied(), geom, kind)
    };

    let items: Vec<_> = edges
        .iter()
        .filter_map(|edge| {
            let source_geom = geom_by_id.get(edge.source.as_str())?;
            let target_geom = geom_by_id.get(edge.target.as_str())?;
            let (source, source_side, source_on_handle) =
                anchor(source_geom, HandleKind::Source, &edge.source_handle);
            let (target, target_side, target_on_handle) =
                anchor(target_geom, HandleKind::Target, &edge.target_handle);
            // End the visible path at the handle's rim instead of its center
            // so arrowheads stay in front of the handle dot.
            let source = if source_on_handle {
                source + source_side.normal() * HANDLE_RIM
            } else {
                source
            };
            let target = if target_on_handle {
                target + target_side.normal() * HANDLE_RIM
            } else {
                target
            };
            Some((
                edge.clone(),
                source,
                source_side,
                target,
                target_side,
                source_geom.rect,
                target_geom.rect,
            ))
        })
        .collect();

    // Grouped into the same world tiles the nodes use, for the same reason:
    // one `<svg>` off screen stands in for everything drawn inside it. A tile
    // clips, so it is sized from `edge_bounds` — the box the curve is
    // guaranteed to stay inside, bulge included — rather than from the
    // anchors.
    let tiles = crate::tile::tiles(items.iter().map(|item| {
        let (edge, source, source_side, target, target_side, source_rect, target_rect) = item;
        let geo = crate::path::EdgeGeometry::new(*source, *source_side, *target, *target_side)
            .with_rects(*source_rect, *target_rect);
        (crate::path::edge_bounds(edge.kind, &geo), edge.selected)
    }));

    rsx! {
        // Decorative for assistive tech: nodes expose the graph's content,
        // and edge hit-paths are pointer-only.
        div { class: "df-edges", "aria-hidden": "true",
            // The markers live in their own zero-size svg: `url(#…)` resolves
            // across the whole document, so one copy serves every tile.
            svg { class: "df-edge-defs",
                defs { EdgeMarkers { iid: core.iid } }
            }
            for tile in tiles.iter() {
                svg {
                    key: "{tile.cell.0},{tile.cell.1}",
                    class: if tile.raised { "df-edge-tile df-raised" } else { "df-edge-tile" },
                    // A viewBox in world units means the paths inside need no
                    // rewriting: they stay in the coordinates everything else
                    // in the flow is expressed in.
                    view_box: "{tile.rect.x} {tile.rect.y} {tile.rect.width} {tile.rect.height}",
                    style: tile_style(tile),
                    for &i in tile.members.iter() {
                        if let Some((edge, source, source_side, target, target_side, source_rect, target_rect)) = items.get(i) {
                            EdgeItem {
                                key: "{edge.id}",
                                edge: edge.clone(),
                                source: *source,
                                source_side: *source_side,
                                target: *target,
                                target_side: *target_side,
                                source_rect: *source_rect,
                                target_rect: *target_rect,
                                edge_view,
                                on_edge_click,
                            }
                        }
                    }
                }
            }
        }
    }
}

/// The dashed preview while dragging a new connection from a handle.
#[component]
fn ConnectionLine() -> Element {
    let core = use_context::<FlowCore>();
    let connection = core.connection.read();
    let Some(conn) = connection.as_ref() else {
        return rsx! {};
    };
    let Some((from, from_side)) = core.anchor_of(&conn.from) else {
        return rsx! {};
    };
    let (to, to_side) = match &conn.snap {
        Some(snap) => (snap.point, Some(snap.side)),
        None => (conn.cursor, None),
    };
    let d = connection_path(from, from_side, to, to_side);
    rsx! {
        svg { class: "df-connection",
            path { class: "df-connection-path", d }
        }
    }
}

pub(crate) fn deselect_edges(mut edges: Signal<Vec<Edge>>) {
    if edges.peek().iter().any(|e| e.selected) {
        edges.with_mut(|edges| {
            for edge in edges.iter_mut() {
                edge.selected = false;
            }
        });
    }
}

/// Default behavior when no `on_connect` handler is given: add the edge,
/// skipping exact duplicates and de-duplicating the generated id.
fn add_edge_for_connection(mut edges: Signal<Vec<Edge>>, conn: Connection) {
    let duplicate = edges.peek().iter().any(|e| {
        e.source == conn.source
            && e.target == conn.target
            && e.source_handle == conn.source_handle
            && e.target_handle == conn.target_handle
    });
    if duplicate {
        return;
    }
    let mut edge = conn.into_edge();
    let base = edge.id.clone();
    let mut n = 2;
    while edges.peek().iter().any(|e| e.id == edge.id) {
        edge.id = format!("{base}-{n}");
        n += 1;
    }
    edges.with_mut(|edges| edges.push(edge));
}

/// What a delete keypress would remove, given the current selection.
fn delete_request<T: Clone + PartialEq + 'static>(
    nodes: Signal<Vec<Node<T>>>,
    edges: Signal<Vec<Edge>>,
) -> DeleteRequest {
    let removed: std::collections::HashSet<Id> = nodes
        .peek()
        .iter()
        .filter(|n| n.selected)
        .map(|n| n.id.clone())
        .collect();
    let edge_ids = edges
        .peek()
        .iter()
        .filter(|e| e.selected || removed.contains(&e.source) || removed.contains(&e.target))
        .map(|e| e.id.clone())
        .collect();
    DeleteRequest {
        nodes: removed.into_iter().collect(),
        edges: edge_ids,
    }
}

pub(crate) fn delete_selected<T: Clone + PartialEq + 'static>(
    mut nodes: Signal<Vec<Node<T>>>,
    mut edges: Signal<Vec<Edge>>,
) {
    let removed: std::collections::HashSet<Id> = nodes
        .peek()
        .iter()
        .filter(|n| n.selected)
        .map(|n| n.id.clone())
        .collect();
    let any_edges = edges
        .peek()
        .iter()
        .any(|e| e.selected || removed.contains(&e.source) || removed.contains(&e.target));
    if !removed.is_empty() {
        nodes.with_mut(|nodes| nodes.retain(|n| !n.selected));
    }
    if any_edges {
        edges.with_mut(|edges| {
            edges.retain(|e| {
                !e.selected && !removed.contains(&e.source) && !removed.contains(&e.target)
            })
        });
    }
}