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
//! Node rendering: the positioned wrapper, connection handles, and the
//! default node view.

use dioxus::prelude::*;

use crate::state::{ConnectionState, DragState, FlowCore, Interaction};
use crate::types::{HandleGeom, HandleKey, HandleKind, Id, Node, Point, Side, Size};

/// Context available to custom node views.
#[derive(Clone, PartialEq)]
pub struct NodeViewCtx<T: Clone + PartialEq + 'static> {
    pub node: Node<T>,
    /// Whether this node is currently being dragged.
    pub dragging: bool,
}

/// Identifies the node that a [`Handle`] belongs to. Provided by the node
/// wrapper, consumed by handles rendered anywhere inside the node's view.
#[derive(Clone, PartialEq)]
pub(crate) struct NodeScope {
    pub id: Id,
}

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

/// The positioned, draggable wrapper around each node's content.
#[component]
pub(crate) fn NodeItem<T: Clone + PartialEq + 'static>(
    nodes: Signal<Vec<Node<T>>>,
    node: Node<T>,
    /// Origin of the tile this node is rendered in — its containing block, so
    /// the node's own offset is measured from here rather than from the canvas.
    #[props(default)]
    origin: Point,
    node_view: Option<Callback<NodeViewCtx<T>, Element>>,
    on_node_click: Option<EventHandler<Id>>,
) -> Element {
    let core = use_context::<FlowCore>();
    use_context_provider(|| NodeScope {
        id: node.id.clone(),
    });

    // Subscribes only to gesture start/end, not per-frame drag state.
    let dragging = *core.interaction.read() == Interaction::DragNode
        && core.drag.peek().grabs.iter().any(|(id, _)| id == &node.id);

    let class = format!(
        "df-node{}{}{}",
        if node.selected { " df-selected" } else { "" },
        if dragging { " df-dragging" } else { "" },
        node.class
            .as_deref()
            .map(|c| format!(" {c}"))
            .unwrap_or_default(),
    );
    let size_style = node
        .size
        .map(|s| format!("width:{}px;height:{}px;", s.width, s.height))
        .unwrap_or_default();
    let style = format!(
        "transform:translate({}px,{}px);z-index:{};{}{}",
        node.position.x - origin.x,
        node.position.y - origin.y,
        if dragging || node.selected { 1000 } else { 0 },
        size_style,
        node.style.as_deref().unwrap_or_default(),
    );

    let id_for_drag = node.id.clone();
    let id_for_resize = node.id.clone();
    let id_for_keys = node.id.clone();
    let draggable = node.draggable;
    let selectable = node.selectable;
    let label = node.label.clone();

    let content = match node_view {
        Some(view) => view.call(NodeViewCtx {
            node: node.clone(),
            dragging,
        }),
        None => rsx! {
            DefaultNodeView::<T> {
                ctx: NodeViewCtx { node: node.clone(), dragging },
            }
        },
    };

    rsx! {
        div {
            class,
            style,
            tabindex: "0",
            role: "group",
            aria_label: "{label}",
            onpointerdown: move |evt| {
                node_pointer_down(core, nodes, &id_for_drag, draggable, selectable, &on_node_click, evt)
            },
            onkeydown: move |evt| {
                node_key_down(core, nodes, &id_for_keys, draggable, selectable, evt)
            },
            onresize: move |evt| {
                if let Ok(size) = evt.data().get_border_box_size() {
                    store_measured(core, nodes, &id_for_resize, Size::new(size.width, size.height));
                }
            },
            {content}
        }
    }
}

/// Keyboard access to the pointer gestures: Enter/Space (toggle-)selects,
/// arrows nudge the focused node — or the whole selection when it belongs to
/// one — by 10px (1px with Shift). Delete bubbles up to the flow's handler.
fn node_key_down<T: Clone + PartialEq + 'static>(
    core: FlowCore,
    mut nodes: Signal<Vec<Node<T>>>,
    id: &Id,
    draggable: bool,
    selectable: bool,
    evt: Event<KeyboardData>,
) {
    let step = if evt.modifiers().shift() { 1.0 } else { 10.0 };
    let delta = match evt.key() {
        Key::ArrowUp => Point::new(0.0, -step),
        Key::ArrowDown => Point::new(0.0, step),
        Key::ArrowLeft => Point::new(-step, 0.0),
        Key::ArrowRight => Point::new(step, 0.0),
        Key::Enter => {
            evt.prevent_default();
            select_node(core, nodes, id, selectable, evt.modifiers().shift());
            return;
        }
        Key::Character(c) if c == " " => {
            evt.prevent_default();
            select_node(core, nodes, id, selectable, evt.modifiers().shift());
            return;
        }
        _ => return,
    };
    if !(draggable && core.config.peek().nodes_draggable) {
        return;
    }
    evt.prevent_default();
    core.cancel_animations();
    let focused_selected = nodes
        .peek()
        .iter()
        .find(|n| &n.id == id)
        .map(|n| n.selected)
        .unwrap_or(false);
    nodes.with_mut(|nodes| {
        for node in nodes.iter_mut() {
            let moves = if focused_selected {
                node.selected && node.draggable
            } else {
                &node.id == id
            };
            if moves {
                node.position = node.position + delta;
            }
        }
    });
}

fn select_node<T: Clone + PartialEq + 'static>(
    core: FlowCore,
    mut nodes: Signal<Vec<Node<T>>>,
    id: &Id,
    selectable: bool,
    toggle: bool,
) {
    if !selectable {
        return;
    }
    if toggle {
        nodes.with_mut(|nodes| {
            if let Some(node) = nodes.iter_mut().find(|n| &n.id == id) {
                node.selected = !node.selected;
            }
        });
    } else {
        nodes.with_mut(|nodes| {
            for node in nodes.iter_mut() {
                node.selected = &node.id == id;
            }
        });
        crate::flow::deselect_edges(core.edges);
    }
}

/// Record a node's measured size. Sizes are batched into one `nodes` write
/// per frame: resize events arrive once per node, and letting each of them
/// re-render the graph makes mounting N nodes O(N²).
fn store_measured<T: Clone + PartialEq + 'static>(
    core: FlowCore,
    mut nodes: Signal<Vec<Node<T>>>,
    id: &Id,
    size: Size,
) {
    // A node in a tile the browser has skipped has no box at all, and reports
    // itself as empty. Believing that would collapse the node's rect and drag
    // every edge that lands on it to a point — so an empty measurement is
    // taken as "not measurable right now", not as a size. Real nodes are never
    // empty; the measurement arrives again when the tile comes back.
    if !(size.width > 0.0 && size.height > 0.0) {
        return;
    }
    let changed = nodes
        .peek()
        .iter()
        .find(|n| &n.id == id)
        .map(|n| match n.measured {
            Some(m) => (m.width - size.width).abs() > 0.5 || (m.height - size.height).abs() > 0.5,
            None => true,
        })
        .unwrap_or(false);
    if !changed {
        return;
    }
    core.pending_sizes.clone().write().push((id.clone(), size));
    let mut queued = core.size_flush_queued;
    if *queued.peek() {
        return;
    }
    queued.set(true);
    // Owned by the canvas, so removing the enqueuing node cannot cancel
    // the flush, and unmounting the canvas cancels it safely.
    core.spawn(async move {
        crate::anim::sleep_ms(0).await;
        core.size_flush_queued.clone().set(false);
        let sizes = std::mem::take(&mut *core.pending_sizes.clone().write());
        if sizes.is_empty() {
            return;
        }
        let map: std::collections::HashMap<Id, Size> = sizes.into_iter().collect();
        let mut nodes = nodes.write();
        for node in nodes.iter_mut() {
            if let Some(size) = map.get(&node.id) {
                node.measured = Some(*size);
            }
        }
    });
}

#[allow(clippy::too_many_arguments)]
fn node_pointer_down<T: Clone + PartialEq + 'static>(
    core: FlowCore,
    mut nodes: Signal<Vec<Node<T>>>,
    id: &Id,
    draggable: bool,
    selectable: bool,
    on_node_click: &Option<EventHandler<Id>>,
    evt: Event<PointerData>,
) {
    // A handle inside this node may have claimed the pointer already.
    if *core.interaction.peek() != Interaction::None {
        return;
    }
    core.cancel_animations();
    let shift = evt.modifiers().shift();

    if selectable {
        let already_selected = nodes
            .peek()
            .iter()
            .find(|n| &n.id == id)
            .map(|n| n.selected)
            .unwrap_or(false);
        if shift {
            nodes.with_mut(|nodes| {
                if let Some(node) = nodes.iter_mut().find(|n| &n.id == id) {
                    node.selected = !node.selected;
                }
            });
        } else if !already_selected {
            nodes.with_mut(|nodes| {
                for node in nodes.iter_mut() {
                    node.selected = &node.id == id;
                }
            });
            crate::flow::deselect_edges(core.edges);
        }
    }
    if let Some(handler) = on_node_click {
        handler.call(id.clone());
    }

    let config = *core.config.peek();
    if !(draggable && config.nodes_draggable) {
        core.interaction.clone().set(Interaction::Pressed);
        return;
    }

    let cursor_flow = core.client_to_flow(client_point(evt.client_coordinates()));
    // Drag every selected draggable node as a group; always include the
    // pressed node itself.
    let grabs: Vec<(Id, Point)> = nodes
        .peek()
        .iter()
        .filter(|n| (n.selected && n.draggable) || &n.id == id)
        .map(|n| (n.id.clone(), cursor_flow - n.position))
        .collect();
    let client = client_point(evt.client_coordinates());
    let mut drag = core.drag;
    {
        let mut state = drag.write();
        *state = DragState {
            pointer_id: Some(evt.pointer_id()),
            origin_client: client,
            last_client: client,
            moved: false,
            suppress_click: false,
            grabs,
        };
    }
    core.interaction.clone().set(Interaction::DragNode);
}

/// A connection point on a node. Place handles anywhere inside a custom node
/// view; edges anchor to them and new connections can be dragged out of them.
#[component]
pub fn Handle(
    /// Whether edges start (`Source`) or end (`Target`) here.
    kind: HandleKind,
    /// Which side of the node the handle sits on.
    position: ReadSignal<Side>,
    /// Optional handle id, referenced by `Edge::source_handle` /
    /// `Edge::target_handle`. Needed when a node has multiple handles of the
    /// same kind.
    id: Option<String>,
    /// Fraction (0..=1) along the side, defaults to centered.
    #[props(default = 0.5)]
    offset: f64,
    /// Extra classes (e.g. Tailwind utilities) for the handle dot.
    class: Option<String>,
) -> Element {
    let core = use_context::<FlowCore>();
    let scope = use_context::<NodeScope>();
    let key = use_hook(|| HandleKey {
        node: scope.id.clone(),
        kind,
        id: id.clone().unwrap_or_default(),
    });

    // Keep the registry in sync with (possibly reactive) geometry props.
    // Writes are queued and flushed in one batch per frame via the core.
    {
        let key = key.clone();
        use_effect(move || {
            let geom = HandleGeom {
                side: *position.read(),
                offset,
            };
            if core.handles.peek().get(&key) != Some(&geom) {
                core.queue_handle_write(key.clone(), Some(geom));
            }
        });
    }
    {
        let key = key.clone();
        use_drop(move || {
            core.queue_handle_write(key, None);
        });
    }

    // Narrow memos: these only change on connection start/end and snap
    // enter/leave, not on every pointer move.
    let connect_from = core.connect_from.read();
    let is_snap_target = core.snap_key.read().as_ref() == Some(&key);
    let is_connect_source = connect_from.as_ref() == Some(&key);
    let is_valid_target = connect_from
        .as_ref()
        .map(|from| from.kind != kind && from.node != key.node)
        .unwrap_or(false);

    let side = *position.read();
    let class = format!(
        "df-handle df-handle-{} df-handle-{}{}{}{}{}",
        match kind {
            HandleKind::Source => "source",
            HandleKind::Target => "target",
        },
        side.class_name(),
        if is_connect_source {
            " df-connecting-from"
        } else {
            ""
        },
        if is_valid_target {
            " df-valid-target"
        } else {
            ""
        },
        if is_snap_target { " df-snap" } else { "" },
        class
            .as_deref()
            .map(|c| format!(" {c}"))
            .unwrap_or_default(),
    );
    let pct = offset * 100.0;
    let style = match side {
        Side::Top => format!("left:{pct}%;top:0;"),
        Side::Bottom => format!("left:{pct}%;top:100%;"),
        Side::Left => format!("left:0;top:{pct}%;"),
        Side::Right => format!("left:100%;top:{pct}%;"),
    };

    let key_for_down = key.clone();
    rsx! {
        div {
            class,
            style,
            onpointerdown: move |evt| {
                if *core.interaction.peek() != Interaction::None {
                    return;
                }
                core.cancel_animations();
                let client = client_point(evt.client_coordinates());
                let cursor = core.client_to_flow(client);
                {
                    let mut drag = core.drag;
                    let mut state = drag.write();
                    *state = DragState {
                        pointer_id: Some(evt.pointer_id()),
                        origin_client: client,
                        last_client: client,
                        moved: false,
                        suppress_click: false,
                        grabs: Vec::new(),
                    };
                }
                core.connection.clone().set(Some(ConnectionState {
                    from: key_for_down.clone(),
                    cursor,
                    snap: None,
                }));
                core.interaction.clone().set(Interaction::Connect);
                if let Some(handler) = &core.on_connect_start {
                    handler.call(key_for_down.clone());
                }
            },
        }
    }
}

/// The built-in node view: a simple labeled box. Nodes typed `"input"` omit
/// the target handle, `"output"` omits the source handle.
///
/// Custom `node_view` callbacks can delegate to this for node types they
/// don't handle.
#[component]
pub fn DefaultNodeView<T: Clone + PartialEq + 'static>(ctx: NodeViewCtx<T>) -> Element {
    let node = &ctx.node;
    let is_input = node.node_type.as_deref() == Some("input");
    let is_output = node.node_type.as_deref() == Some("output");
    rsx! {
        div { class: "df-node-default",
            if !is_input {
                Handle { kind: HandleKind::Target, position: node.target_side }
            }
            span { class: "df-node-label", "{node.label}" }
            if !is_output {
                Handle { kind: HandleKind::Source, position: node.source_side }
            }
        }
    }
}

#[cfg(test)]
mod lifecycle_tests;