leptos-node-graph 0.2.2

A reactive node graph editor component for Leptos
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
use std::{collections::HashSet, marker::PhantomData};

use leptos::prelude::*;

use crate::registry::EditorRegistry;
use crate::theme::GroupStyle;
use crate::types::*;

/// Defines a visual group box around a set of nodes.
#[derive(Clone, Debug)]
pub struct GroupBox<N: NodeId> {
    /// Unique group identifier.
    pub id: String,
    /// Node IDs contained in this group.
    pub node_ids: Vec<N>,
    /// Optional label displayed above the group.
    pub label: Option<String>,
    /// Group color as a CSS color string (e.g. "#8b5cf6").
    pub color: Option<String>,
    /// Whether the group is in an error state.
    pub error: bool,
}

/// Computed bounding box for a group.
#[derive(Clone, Debug)]
pub struct GroupBounds {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

impl GroupBounds {
    pub fn contains(&self, point: Position) -> bool {
        point.x >= self.x
            && point.x <= self.x + self.width
            && point.y >= self.y
            && point.y <= self.y + self.height
    }
}

/// Events emitted by the group overlay.
#[derive(Clone, Debug)]
pub enum GroupEvent<N: NodeId> {
    /// Group label was renamed.
    Renamed { group_id: String, new_label: String },
    /// Group membership changed after an alt-drag gesture.
    ///
    /// The complete member list is emitted once per affected group so consumers
    /// can persist the gesture atomically even when their reactive state updates
    /// asynchronously or the drag moves several selected nodes.
    MembersChanged { group_id: String, node_ids: Vec<N> },
    /// The group color chip was cycled.
    ColorChanged { group_id: String, new_color: String },
}

/// Renders group box overlays. Groups are visual containers around nodes.
///
/// - Double-click a label to rename it inline
/// - Alt+drag an empty canvas: creates a group from the enclosed nodes.
/// - Alt+drag a node: immediately removes it from its group. Dropping onto
///   another group adds it there.
/// - Ctrl+G: creates a group from the current selection.
#[component]
pub fn GroupBoxOverlay<N, P, C, T>(
    /// Reactive list of group definitions.
    groups: Signal<Vec<GroupBox<N>>>,
    /// Callback for group events (rename, add/remove node).
    #[prop(optional, into)]
    on_event: Option<Callback<GroupEvent<N>>>,
    /// Padding around the group bounding box in pixels.
    #[prop(optional, into)]
    padding: Option<f64>,
    /// PhantomData for unused type parameters.
    #[prop(optional)]
    _marker: PhantomData<(P, C, T)>,
    /// Optional callback for custom header rendering per group.
    #[prop(optional)]
    header: Option<Callback<(GroupBox<N>, GroupBounds), AnyView>>,
    /// Optional action for removing a group.
    #[prop(optional)]
    on_ungroup: Option<Callback<String>>,
    /// Optional action for selecting every member of a group.
    #[prop(optional)]
    on_select_all: Option<Callback<Vec<N>>>,
) -> impl IntoView
where
    N: NodeId,
    P: PortId,
    C: ConnectionId,
    T: PortType,
{
    let registry = expect_context::<EditorRegistry<N, P, C, T>>();
    let padding = padding.unwrap_or(16.0);
    // Keep the library's selection state in sync with the consumer callback.
    // Nodes render their highlight from this registry signal; updating only a
    // consumer-owned selection signal makes the action appear to do nothing.
    let on_select_all_nodes = on_select_all.map(|callback| {
        let registry = registry.clone();
        Callback::new(move |node_ids: Vec<N>| {
            registry
                .selected_nodes
                .set(node_ids.iter().cloned().collect());
            callback.run(node_ids);
        })
    });

    // Track which group the alt-dragged node is hovering over (for visual feedback)
    let hover_group: RwSignal<Option<String>> = RwSignal::new(None);
    // Track every node moved by the previous alt-drag. A normal node drag can
    // move the whole selection, so membership must follow the gesture batch.
    let prev_alt_drag: RwSignal<Option<Vec<N>>> = RwSignal::new(None);

    let reg_drag = registry.clone();
    let on_event_drag = on_event;
    Effect::new(move || {
        let drag = reg_drag.drag_state.get();
        let prev = prev_alt_drag.get_untracked();

        match (&drag, &prev) {
            // Alt-drag just started
            (Some(ds), None) if ds.alt_key => {
                let mut node_ids: Vec<N> = ds.start_positions.keys().cloned().collect();
                if node_ids.is_empty() {
                    node_ids.push(ds.node_id.clone());
                }
                prev_alt_drag.set(Some(node_ids.clone()));

                // Membership is previewed locally during the drag and persisted
                // only on mouse-up. That keeps one gesture to one complete update
                // per affected group, even for asynchronous consumers.
            }
            // Non-alt drag started — ignore
            (Some(_), None) => {}
            // Alt-drag ended — add each moved node to the first group containing
            // its center, batching the final membership once per target group.
            (None, Some(node_ids)) => {
                prev_alt_drag.set(None);
                hover_group.set(None);

                if let Some(ref on_ev) = on_event_drag {
                    let moved: HashSet<N> = node_ids.iter().cloned().collect();
                    let current_groups = groups.get_untracked();
                    let nodes_map = reg_drag.nodes.get_untracked();
                    let live_positions = reg_drag.live_positions.get_untracked();
                    let base_members: Vec<Vec<N>> = current_groups
                        .iter()
                        .map(|group| members_without(&group.node_ids, &moved))
                        .collect();
                    let mut additions = vec![Vec::new(); current_groups.len()];

                    for node_id in node_ids {
                        let Some(node) = nodes_map.get(node_id) else {
                            continue;
                        };
                        let center = Position::new(
                            node.position.x + node.size.width / 2.0,
                            node.position.y + node.size.height / 2.0,
                        );
                        for (index, members) in base_members.iter().enumerate() {
                            if let Some(bounds) =
                                compute_bounds(members, &nodes_map, &live_positions, padding)
                                && bounds.contains(center)
                            {
                                additions[index].push(node_id.clone());
                                break;
                            }
                        }
                    }

                    for ((group, mut members), added) in
                        current_groups.iter().zip(base_members).zip(additions)
                    {
                        for node_id in added {
                            if !members.contains(&node_id) {
                                members.push(node_id);
                            }
                        }
                        if members != group.node_ids {
                            on_ev.run(GroupEvent::MembersChanged {
                                group_id: group.id.clone(),
                                node_ids: members,
                            });
                        }
                    }
                }
            }
            _ => {}
        }

        // Update hover highlight during alt-drag.
        // We read nodes reactively here so this re-runs as the node moves.
        if let Some(ref ds) = drag {
            if ds.alt_key {
                let dragged_id = ds.node_id.clone();
                let moved: HashSet<N> = ds.start_positions.keys().cloned().collect();
                let all_nodes = reg_drag.nodes.get(); // reactive — triggers on position change
                let node_center = all_nodes.get(&dragged_id).map(|n| {
                    Position::new(
                        n.position.x + n.size.width / 2.0,
                        n.position.y + n.size.height / 2.0,
                    )
                });

                if let Some(center) = node_center {
                    let current_groups = groups.get_untracked();
                    let live_positions = reg_drag.live_positions.get();
                    let mut found = None;
                    for group in &current_groups {
                        let members = members_without(&group.node_ids, &moved);
                        if let Some(bounds) =
                            compute_bounds(&members, &all_nodes, &live_positions, padding)
                            && bounds.contains(center)
                        {
                            found = Some(group.id.clone());
                            break;
                        }
                    }
                    hover_group.set(found);
                }
            }
        } else {
            hover_group.set(None);
        }
    });

    // Render groups
    move || {
        let groups = groups.get();
        // `compute_bounds` reads each node's live consumer-owned position
        // signal, while this map read tracks membership and measured sizes.
        let nodes = registry.nodes.get();
        let live_positions = registry.live_positions.get();
        let hovered = hover_group.get();
        let moved: HashSet<N> = prev_alt_drag
            .get()
            .unwrap_or_default()
            .into_iter()
            .collect();

        groups
            .into_iter()
            .filter_map(|group| {
                let members = members_without(&group.node_ids, &moved);
                let bounds = compute_bounds(&members, &nodes, &live_positions, padding)?;

                let has_label = group.label.is_some();
                let header_height = if has_label { 24.0 } else { padding };

                let final_bounds = GroupBounds {
                    x: bounds.x,
                    // `bounds` already reserves `padding` above the first node.
                    // The header replaces that top padding instead of stacking
                    // another row above it.
                    y: bounds.y + padding - header_height,
                    width: bounds.width,
                    height: bounds.height + header_height - padding,
                };

                let gs = use_context::<GroupStyle>().unwrap_or_default();
                let color = group
                    .color
                    .clone()
                    .unwrap_or_else(|| gs.default_color.clone());
                // The original slate default is too bright as a translucent
                // group fill; normalize it for existing persisted groups too.
                let color = if color.eq_ignore_ascii_case("#64748b") {
                    "#3f4752".to_string()
                } else {
                    color
                };
                let is_error = group.error;
                let is_hovered = hovered.as_ref() == Some(&group.id);

                let (border_color, bg_color) = if is_error {
                    (gs.error_border.clone(), gs.error_background.clone())
                } else if is_hovered {
                    (
                        format!("color-mix(in srgb, {color} 80%, transparent)"),
                        format!("color-mix(in srgb, {color} 20%, transparent)"),
                    )
                } else {
                    (
                        format!("color-mix(in srgb, {color} 50%, transparent)"),
                        format!("color-mix(in srgb, {color} 10%, transparent)"),
                    )
                };

                let border_style = if is_hovered { "solid" } else { "dashed" };
                let glow = if is_hovered {
                    format!(
                        "box-shadow: 0 0 0 2px color-mix(in srgb, {color} 70%, transparent), 0 0 22px color-mix(in srgb, {color} 45%, transparent);"
                    )
                } else {
                    String::new()
                };

                let box_style = format!(
                    "position: absolute; left: {}px; top: {}px; width: {}px; height: {}px; \
                     pointer-events: none; z-index: 0; \
                     background: {bg_color}; border: 1px {border_style} {border_color}; \
                     border-radius: {}; {glow} transition: background 0.15s, border 0.15s, box-shadow 0.15s;",
                    final_bounds.x,
                    final_bounds.y,
                    final_bounds.width,
                    final_bounds.height,
                    gs.border_radius,
                );

                let header_view = if let Some(ref header_cb) = header {
                    Some(header_cb.run((group.clone(), final_bounds.clone())))
                } else {
                    group.label.clone().map(|label| {
                        let label_color = if is_error {
                            gs.error_label_color.clone()
                        } else {
                            format!("color-mix(in srgb, {color} 70%, white)")
                        };

                        let group_id = group.id.clone();
                        let group_color = color.clone();
                        let on_event_rename = on_event;

                        view! {
                            <GroupLabel
                                label=label
                                color=label_color
                                group_color=group_color
                                group_id=group_id
                                on_rename=on_event_rename
                                on_ungroup=on_ungroup
                                on_select_all=on_select_all_nodes
                                node_ids=group.node_ids.clone()
                            />
                        }
                        .into_any()
                    })
                };

                Some(view! {
                    <div style=box_style role="presentation">
                        {header_view}
                    </div>
                })
            })
            .collect_view()
    }
}

/// Editable group label.
#[component]
fn GroupLabel<N: NodeId>(
    label: String,
    color: String,
    group_color: String,
    group_id: String,
    on_rename: Option<Callback<GroupEvent<N>>>,
    on_ungroup: Option<Callback<String>>,
    on_select_all: Option<Callback<Vec<N>>>,
    node_ids: Vec<N>,
) -> impl IntoView {
    let (text, set_text) = signal(label.clone());

    let gs = use_context::<GroupStyle>().unwrap_or_default();

    let header_style = Signal::derive(move || {
        format!(
            "position:absolute; top:4px; left:10px; right:4px; z-index:2; height:16px; \
         display:flex; align-items:center; gap:6px; min-width:0; \
         font-size: {}; font-weight: {}; text-transform: uppercase; \
         letter-spacing:0.05em; color:{}; background:transparent; \
         line-height:16px; white-space:nowrap; \
         pointer-events: auto; cursor: default;",
            gs.label_font_size, gs.label_font_weight, color
        )
    });

    let input_style = "flex:1 1 auto; min-width:0; height:18px; margin:0; padding:0 4px; \
         box-sizing:border-box; border:0; outline:none; border-radius:3px; \
         background:transparent; color:inherit; font:inherit; line-height:18px; \
         text-transform:uppercase; letter-spacing:0.05em; pointer-events:auto;";

    let group_id_commit = group_id.clone();
    let on_rename_commit = on_rename;
    let on_color = on_rename;
    let commit = move || {
        let new_label = text.get_untracked();
        if let Some(ref cb) = on_rename_commit {
            cb.run(GroupEvent::Renamed {
                group_id: group_id_commit.clone(),
                new_label,
            });
        }
    };

    let commit_blur = commit.clone();
    let commit_key = commit.clone();
    view! {
        <div
            style=header_style
            title="Ctrl+G with nodes selected creates a group. Alt-drag removes this node; drop onto another group to add it."
            on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
            on:click=|ev: web_sys::MouseEvent| ev.stop_propagation()
        >
            <button
                type="button"
                title="Change group color"
                aria-label="Change group color"
                style=format!("flex:0 0 10px; width:10px; height:10px; margin:0; padding:0; border:0; border-radius:50%; background:{}; cursor:pointer; pointer-events:auto;", group_color)
                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
                on:dblclick=|ev: web_sys::MouseEvent| ev.stop_propagation()
                on:click={
                    let group_id = group_id.clone();
                    let current = group_color.clone();
                    move |ev: web_sys::MouseEvent| {
                        ev.stop_propagation();
                        if let Some(ref callback) = on_color {
                            callback.run(GroupEvent::ColorChanged {
                                group_id: group_id.clone(),
                                new_color: next_group_color(&current),
                            });
                        }
                    }
                }
            ></button>
            <input
                type="text"
                style=input_style
                prop:value=move || text.get()
                aria-label="Group title"
                on:input=move |ev| {
                    use leptos::wasm_bindgen::JsCast;
                    let t = ev.target().unwrap().unchecked_into::<web_sys::HtmlInputElement>();
                    set_text.set(t.value());
                }
                on:blur=move |_| { commit_blur(); }
                on:keydown=move |ev: web_sys::KeyboardEvent| {
                    ev.stop_propagation();
                    if ev.key() == "Enter" {
                        commit_key();
                    } else if ev.key() == "Escape" {
                        set_text.set(label.clone());
                        ev.prevent_default();
                    }
                }
                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
            />
            <span style="display:flex; flex:0 0 auto; align-items:center; gap:6px; height:16px;">
                    {on_select_all.map(|callback| {
                        let node_ids = node_ids.clone();
                        view! {
                            <button
                                type="button"
                                title="Select all in group"
                                style="display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px; margin:0; padding:0; pointer-events:auto; cursor:pointer; background:transparent; border:0; color:inherit; opacity:0.7;"
                                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
                                on:click=move |ev: web_sys::MouseEvent| {
                                    ev.stop_propagation();
                                    callback.run(node_ids.clone());
                                }
                            >
                                <MaterialIcon icon=md_icons::outlined::ICON_SELECT_ALL />
                            </button>
                        }
                    })}
                    {on_ungroup.map(|callback| {
                        let group_id = group_id.clone();
                        view! {
                            <button
                                type="button"
                                title="Ungroup"
                                style="display:inline-flex; align-items:center; justify-content:center; width:16px; height:16px; margin:0; padding:0; pointer-events:auto; cursor:pointer; background:transparent; border:0; color:inherit; opacity:0.7;"
                                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
                                on:click=move |ev: web_sys::MouseEvent| {
                                    ev.stop_propagation();
                                    callback.run(group_id.clone());
                                }
                            >
                                <MaterialIcon icon=md_icons::outlined::ICON_CLOSE />
                            </button>
                        }
                    })}
            </span>
        </div>
    }
}

#[component]
fn MaterialIcon(icon: &'static str) -> impl IntoView {
    let mut svg = icon.to_string();
    if let Some(position) = svg.find("<svg") {
        svg.insert_str(
            position.saturating_add(4),
            " style=\"width:100%;height:100%;display:block;fill:currentColor\" aria-hidden=\"true\" focusable=\"false\"",
        );
    }

    view! {
        <span
            aria-hidden="true"
            style="width:14px;height:14px;display:inline-flex;flex:none;"
            inner_html=svg
        />
    }
}

fn next_group_color(current: &str) -> String {
    const COLORS: [&str; 7] = [
        "#3f4752", "#EF476F", "#F78C6B", "#FFD166", "#06D6A0", "#118AB2", "#073B4C",
    ];
    let index = COLORS
        .iter()
        .position(|color| *color == current)
        .unwrap_or(0);
    COLORS[(index + 1) % COLORS.len()].to_string()
}

fn members_without<N: NodeId>(node_ids: &[N], excluded: &HashSet<N>) -> Vec<N> {
    node_ids
        .iter()
        .filter(|node_id| !excluded.contains(*node_id))
        .cloned()
        .collect()
}

/// Compute bounding box from a set of node IDs.
fn compute_bounds<N: NodeId>(
    node_ids: &[N],
    nodes: &std::collections::HashMap<N, crate::registry::NodeEntry<N>>,
    live_positions: &std::collections::HashMap<N, Position>,
    padding: f64,
) -> Option<GroupBounds> {
    let mut min_x = f64::MAX;
    let mut min_y = f64::MAX;
    let mut max_x = f64::MIN;
    let mut max_y = f64::MIN;
    let mut found = false;

    for node_id in node_ids {
        let Some(entry) = nodes.get(node_id) else {
            // A group with a stale membership should not render a misleading
            // box. The consumer can remove the missing node and the group will
            // recover on the next reactive update.
            return None;
        };
        // Use a conservative fallback until the node's first measurement
        // arrives. The overlay must exist during that initial frame; measured
        // dimensions replace these values reactively as soon as they land.
        let w = entry.size.width.max(160.0);
        let h = entry.size.height.max(80.0);
        // The registry position is the live interaction position. The
        // consumer-owned signal may be backed by resolved/persisted state and
        // only catch up when the drag is committed, so using it here makes
        // group bounds update only on drop.
        let position = live_positions
            .get(node_id)
            .copied()
            .unwrap_or(entry.position);
        let x = position.x;
        let y = position.y;
        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x + w);
        max_y = max_y.max(y + h);
        found = true;
    }

    if !found {
        return None;
    }

    Some(GroupBounds {
        x: min_x - padding,
        y: min_y - padding,
        width: (max_x - min_x) + padding * 2.0,
        height: (max_y - min_y) + padding * 2.0,
    })
}

#[cfg(test)]
mod tests {
    use std::collections::{HashMap, HashSet};

    use super::*;
    use crate::registry::NodeEntry;

    #[test]
    fn removes_a_drag_batch_with_one_membership_update() {
        let members = vec!["a".to_string(), "b".to_string(), "c".to_string()];
        let moved = HashSet::from(["a".to_string(), "c".to_string()]);

        assert_eq!(members_without(&members, &moved), vec!["b".to_string()]);
    }

    #[test]
    fn drop_bounds_do_not_follow_the_dragged_member() {
        let dragged = "dragged".to_string();
        let anchor = "anchor".to_string();
        let members = vec![dragged.clone(), anchor.clone()];
        let moved = HashSet::from([dragged.clone()]);
        let remaining = members_without(&members, &moved);
        let nodes = HashMap::from([
            (
                dragged.clone(),
                NodeEntry {
                    id: dragged,
                    position: Position::new(1_000.0, 1_000.0),
                    size: Size {
                        width: 100.0,
                        height: 100.0,
                    },
                    position_signal: None,
                },
            ),
            (
                anchor.clone(),
                NodeEntry {
                    id: anchor,
                    position: Position::new(0.0, 0.0),
                    size: Size {
                        width: 100.0,
                        height: 100.0,
                    },
                    position_signal: None,
                },
            ),
        ]);
        let live_positions = nodes
            .iter()
            .map(|(id, node)| (id.clone(), node.position))
            .collect();

        let bounds = compute_bounds(&remaining, &nodes, &live_positions, 16.0).unwrap();
        assert!(!bounds.contains(Position::new(1_050.0, 1_050.0)));
    }
}