Skip to main content

leptos_node_graph/
group.rs

1use std::{collections::HashSet, marker::PhantomData};
2
3use leptos::prelude::*;
4
5use crate::registry::EditorRegistry;
6use crate::theme::GroupStyle;
7use crate::types::*;
8
9/// Defines a visual group box around a set of nodes.
10#[derive(Clone, Debug)]
11pub struct GroupBox<N: NodeId> {
12    /// Unique group identifier.
13    pub id: String,
14    /// Node IDs contained in this group.
15    pub node_ids: Vec<N>,
16    /// Optional label displayed above the group.
17    pub label: Option<String>,
18    /// Group color as a CSS color string (e.g. "#8b5cf6").
19    pub color: Option<String>,
20    /// Whether the group is in an error state.
21    pub error: bool,
22}
23
24/// Computed bounding box for a group.
25#[derive(Clone, Debug)]
26pub struct GroupBounds {
27    pub x: f64,
28    pub y: f64,
29    pub width: f64,
30    pub height: f64,
31}
32
33impl GroupBounds {
34    pub fn contains(&self, point: Position) -> bool {
35        point.x >= self.x
36            && point.x <= self.x + self.width
37            && point.y >= self.y
38            && point.y <= self.y + self.height
39    }
40}
41
42/// Events emitted by the group overlay.
43#[derive(Clone, Debug)]
44pub enum GroupEvent<N: NodeId> {
45    /// Group label was renamed.
46    Renamed { group_id: String, new_label: String },
47    /// Group membership changed after an alt-drag gesture.
48    ///
49    /// The complete member list is emitted once per affected group so consumers
50    /// can persist the gesture atomically even when their reactive state updates
51    /// asynchronously or the drag moves several selected nodes.
52    MembersChanged { group_id: String, node_ids: Vec<N> },
53    /// The group color chip was cycled.
54    ColorChanged { group_id: String, new_color: String },
55}
56
57/// Renders group box overlays. Groups are visual containers around nodes.
58///
59/// - Double-click a label to rename it inline
60/// - Alt+drag an empty canvas: creates a group from the enclosed nodes.
61/// - Alt+drag a node: immediately removes it from its group. Dropping onto
62///   another group adds it there.
63/// - Ctrl+G: creates a group from the current selection.
64#[component]
65pub fn GroupBoxOverlay<N, P, C, T>(
66    /// Reactive list of group definitions.
67    groups: Signal<Vec<GroupBox<N>>>,
68    /// Callback for group events (rename, add/remove node).
69    #[prop(optional, into)]
70    on_event: Option<Callback<GroupEvent<N>>>,
71    /// Padding around the group bounding box in pixels.
72    #[prop(optional, into)]
73    padding: Option<f64>,
74    /// PhantomData for unused type parameters.
75    #[prop(optional)]
76    _marker: PhantomData<(P, C, T)>,
77    /// Optional callback for custom header rendering per group.
78    #[prop(optional)]
79    header: Option<Callback<(GroupBox<N>, GroupBounds), AnyView>>,
80    /// Optional action for removing a group.
81    #[prop(optional)]
82    on_ungroup: Option<Callback<String>>,
83    /// Optional action for selecting every member of a group.
84    #[prop(optional)]
85    on_select_all: Option<Callback<Vec<N>>>,
86) -> impl IntoView
87where
88    N: NodeId,
89    P: PortId,
90    C: ConnectionId,
91    T: PortType,
92{
93    let registry = expect_context::<EditorRegistry<N, P, C, T>>();
94    let padding = padding.unwrap_or(16.0);
95    // Keep the library's selection state in sync with the consumer callback.
96    // Nodes render their highlight from this registry signal; updating only a
97    // consumer-owned selection signal makes the action appear to do nothing.
98    let on_select_all_nodes = on_select_all.map(|callback| {
99        let registry = registry.clone();
100        Callback::new(move |node_ids: Vec<N>| {
101            registry
102                .selected_nodes
103                .set(node_ids.iter().cloned().collect());
104            callback.run(node_ids);
105        })
106    });
107
108    // Track which group the alt-dragged node is hovering over (for visual feedback)
109    let hover_group: RwSignal<Option<String>> = RwSignal::new(None);
110    // Track every node moved by the previous alt-drag. A normal node drag can
111    // move the whole selection, so membership must follow the gesture batch.
112    let prev_alt_drag: RwSignal<Option<Vec<N>>> = RwSignal::new(None);
113
114    let reg_drag = registry.clone();
115    let on_event_drag = on_event;
116    Effect::new(move || {
117        let drag = reg_drag.drag_state.get();
118        let prev = prev_alt_drag.get_untracked();
119
120        match (&drag, &prev) {
121            // Alt-drag just started
122            (Some(ds), None) if ds.alt_key => {
123                let mut node_ids: Vec<N> = ds.start_positions.keys().cloned().collect();
124                if node_ids.is_empty() {
125                    node_ids.push(ds.node_id.clone());
126                }
127                prev_alt_drag.set(Some(node_ids.clone()));
128
129                // Membership is previewed locally during the drag and persisted
130                // only on mouse-up. That keeps one gesture to one complete update
131                // per affected group, even for asynchronous consumers.
132            }
133            // Non-alt drag started — ignore
134            (Some(_), None) => {}
135            // Alt-drag ended — add each moved node to the first group containing
136            // its center, batching the final membership once per target group.
137            (None, Some(node_ids)) => {
138                prev_alt_drag.set(None);
139                hover_group.set(None);
140
141                if let Some(ref on_ev) = on_event_drag {
142                    let moved: HashSet<N> = node_ids.iter().cloned().collect();
143                    let current_groups = groups.get_untracked();
144                    let nodes_map = reg_drag.nodes.get_untracked();
145                    let live_positions = reg_drag.live_positions.get_untracked();
146                    let base_members: Vec<Vec<N>> = current_groups
147                        .iter()
148                        .map(|group| members_without(&group.node_ids, &moved))
149                        .collect();
150                    let mut additions = vec![Vec::new(); current_groups.len()];
151
152                    for node_id in node_ids {
153                        let Some(node) = nodes_map.get(node_id) else {
154                            continue;
155                        };
156                        let center = Position::new(
157                            node.position.x + node.size.width / 2.0,
158                            node.position.y + node.size.height / 2.0,
159                        );
160                        for (index, members) in base_members.iter().enumerate() {
161                            if let Some(bounds) =
162                                compute_bounds(members, &nodes_map, &live_positions, padding)
163                                && bounds.contains(center)
164                            {
165                                additions[index].push(node_id.clone());
166                                break;
167                            }
168                        }
169                    }
170
171                    for ((group, mut members), added) in
172                        current_groups.iter().zip(base_members).zip(additions)
173                    {
174                        for node_id in added {
175                            if !members.contains(&node_id) {
176                                members.push(node_id);
177                            }
178                        }
179                        if members != group.node_ids {
180                            on_ev.run(GroupEvent::MembersChanged {
181                                group_id: group.id.clone(),
182                                node_ids: members,
183                            });
184                        }
185                    }
186                }
187            }
188            _ => {}
189        }
190
191        // Update hover highlight during alt-drag.
192        // We read nodes reactively here so this re-runs as the node moves.
193        if let Some(ref ds) = drag {
194            if ds.alt_key {
195                let dragged_id = ds.node_id.clone();
196                let moved: HashSet<N> = ds.start_positions.keys().cloned().collect();
197                let all_nodes = reg_drag.nodes.get(); // reactive — triggers on position change
198                let node_center = all_nodes.get(&dragged_id).map(|n| {
199                    Position::new(
200                        n.position.x + n.size.width / 2.0,
201                        n.position.y + n.size.height / 2.0,
202                    )
203                });
204
205                if let Some(center) = node_center {
206                    let current_groups = groups.get_untracked();
207                    let live_positions = reg_drag.live_positions.get();
208                    let mut found = None;
209                    for group in &current_groups {
210                        let members = members_without(&group.node_ids, &moved);
211                        if let Some(bounds) =
212                            compute_bounds(&members, &all_nodes, &live_positions, padding)
213                            && bounds.contains(center)
214                        {
215                            found = Some(group.id.clone());
216                            break;
217                        }
218                    }
219                    hover_group.set(found);
220                }
221            }
222        } else {
223            hover_group.set(None);
224        }
225    });
226
227    // Render groups
228    move || {
229        let groups = groups.get();
230        // `compute_bounds` reads each node's live consumer-owned position
231        // signal, while this map read tracks membership and measured sizes.
232        let nodes = registry.nodes.get();
233        let live_positions = registry.live_positions.get();
234        let hovered = hover_group.get();
235        let moved: HashSet<N> = prev_alt_drag
236            .get()
237            .unwrap_or_default()
238            .into_iter()
239            .collect();
240
241        groups
242            .into_iter()
243            .filter_map(|group| {
244                let members = members_without(&group.node_ids, &moved);
245                let bounds = compute_bounds(&members, &nodes, &live_positions, padding)?;
246
247                let has_label = group.label.is_some();
248                let header_height = if has_label { 24.0 } else { padding };
249
250                let final_bounds = GroupBounds {
251                    x: bounds.x,
252                    // `bounds` already reserves `padding` above the first node.
253                    // The header replaces that top padding instead of stacking
254                    // another row above it.
255                    y: bounds.y + padding - header_height,
256                    width: bounds.width,
257                    height: bounds.height + header_height - padding,
258                };
259
260                let gs = use_context::<GroupStyle>().unwrap_or_default();
261                let color = group
262                    .color
263                    .clone()
264                    .unwrap_or_else(|| gs.default_color.clone());
265                // The original slate default is too bright as a translucent
266                // group fill; normalize it for existing persisted groups too.
267                let color = if color.eq_ignore_ascii_case("#64748b") {
268                    "#3f4752".to_string()
269                } else {
270                    color
271                };
272                let is_error = group.error;
273                let is_hovered = hovered.as_ref() == Some(&group.id);
274
275                let (border_color, bg_color) = if is_error {
276                    (gs.error_border.clone(), gs.error_background.clone())
277                } else if is_hovered {
278                    (
279                        format!("color-mix(in srgb, {color} 80%, transparent)"),
280                        format!("color-mix(in srgb, {color} 20%, transparent)"),
281                    )
282                } else {
283                    (
284                        format!("color-mix(in srgb, {color} 50%, transparent)"),
285                        format!("color-mix(in srgb, {color} 10%, transparent)"),
286                    )
287                };
288
289                let border_style = if is_hovered { "solid" } else { "dashed" };
290                let glow = if is_hovered {
291                    format!(
292                        "box-shadow: 0 0 0 2px color-mix(in srgb, {color} 70%, transparent), 0 0 22px color-mix(in srgb, {color} 45%, transparent);"
293                    )
294                } else {
295                    String::new()
296                };
297
298                let box_style = format!(
299                    "position: absolute; left: {}px; top: {}px; width: {}px; height: {}px; \
300                     pointer-events: none; z-index: 0; \
301                     background: {bg_color}; border: 1px {border_style} {border_color}; \
302                     border-radius: {}; {glow} transition: background 0.15s, border 0.15s, box-shadow 0.15s;",
303                    final_bounds.x,
304                    final_bounds.y,
305                    final_bounds.width,
306                    final_bounds.height,
307                    gs.border_radius,
308                );
309
310                let header_view = if let Some(ref header_cb) = header {
311                    Some(header_cb.run((group.clone(), final_bounds.clone())))
312                } else {
313                    group.label.clone().map(|label| {
314                        let label_color = if is_error {
315                            gs.error_label_color.clone()
316                        } else {
317                            format!("color-mix(in srgb, {color} 70%, white)")
318                        };
319
320                        let group_id = group.id.clone();
321                        let group_color = color.clone();
322                        let on_event_rename = on_event;
323
324                        view! {
325                            <GroupLabel
326                                label=label
327                                color=label_color
328                                group_color=group_color
329                                group_id=group_id
330                                on_rename=on_event_rename
331                                on_ungroup=on_ungroup
332                                on_select_all=on_select_all_nodes
333                                node_ids=group.node_ids.clone()
334                            />
335                        }
336                        .into_any()
337                    })
338                };
339
340                Some(view! {
341                    <div style=box_style role="presentation">
342                        {header_view}
343                    </div>
344                })
345            })
346            .collect_view()
347    }
348}
349
350/// Editable group label.
351#[component]
352fn GroupLabel<N: NodeId>(
353    label: String,
354    color: String,
355    group_color: String,
356    group_id: String,
357    on_rename: Option<Callback<GroupEvent<N>>>,
358    on_ungroup: Option<Callback<String>>,
359    on_select_all: Option<Callback<Vec<N>>>,
360    node_ids: Vec<N>,
361) -> impl IntoView {
362    let (text, set_text) = signal(label.clone());
363
364    let gs = use_context::<GroupStyle>().unwrap_or_default();
365
366    let header_style = Signal::derive(move || {
367        format!(
368            "position:absolute; top:4px; left:10px; right:4px; z-index:2; height:16px; \
369         display:flex; align-items:center; gap:6px; min-width:0; \
370         font-size: {}; font-weight: {}; text-transform: uppercase; \
371         letter-spacing:0.05em; color:{}; background:transparent; \
372         line-height:16px; white-space:nowrap; \
373         pointer-events: auto; cursor: default;",
374            gs.label_font_size, gs.label_font_weight, color
375        )
376    });
377
378    let input_style = "flex:1 1 auto; min-width:0; height:18px; margin:0; padding:0 4px; \
379         box-sizing:border-box; border:0; outline:none; border-radius:3px; \
380         background:transparent; color:inherit; font:inherit; line-height:18px; \
381         text-transform:uppercase; letter-spacing:0.05em; pointer-events:auto;";
382
383    let group_id_commit = group_id.clone();
384    let on_rename_commit = on_rename;
385    let on_color = on_rename;
386    let commit = move || {
387        let new_label = text.get_untracked();
388        if let Some(ref cb) = on_rename_commit {
389            cb.run(GroupEvent::Renamed {
390                group_id: group_id_commit.clone(),
391                new_label,
392            });
393        }
394    };
395
396    let commit_blur = commit.clone();
397    let commit_key = commit.clone();
398    view! {
399        <div
400            style=header_style
401            title="Ctrl+G with nodes selected creates a group. Alt-drag removes this node; drop onto another group to add it."
402            on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
403            on:click=|ev: web_sys::MouseEvent| ev.stop_propagation()
404        >
405            <button
406                type="button"
407                title="Change group color"
408                aria-label="Change group color"
409                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)
410                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
411                on:dblclick=|ev: web_sys::MouseEvent| ev.stop_propagation()
412                on:click={
413                    let group_id = group_id.clone();
414                    let current = group_color.clone();
415                    move |ev: web_sys::MouseEvent| {
416                        ev.stop_propagation();
417                        if let Some(ref callback) = on_color {
418                            callback.run(GroupEvent::ColorChanged {
419                                group_id: group_id.clone(),
420                                new_color: next_group_color(&current),
421                            });
422                        }
423                    }
424                }
425            ></button>
426            <input
427                type="text"
428                style=input_style
429                prop:value=move || text.get()
430                aria-label="Group title"
431                on:input=move |ev| {
432                    use leptos::wasm_bindgen::JsCast;
433                    let t = ev.target().unwrap().unchecked_into::<web_sys::HtmlInputElement>();
434                    set_text.set(t.value());
435                }
436                on:blur=move |_| { commit_blur(); }
437                on:keydown=move |ev: web_sys::KeyboardEvent| {
438                    ev.stop_propagation();
439                    if ev.key() == "Enter" {
440                        commit_key();
441                    } else if ev.key() == "Escape" {
442                        set_text.set(label.clone());
443                        ev.prevent_default();
444                    }
445                }
446                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
447            />
448            <span style="display:flex; flex:0 0 auto; align-items:center; gap:6px; height:16px;">
449                    {on_select_all.map(|callback| {
450                        let node_ids = node_ids.clone();
451                        view! {
452                            <button
453                                type="button"
454                                title="Select all in group"
455                                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;"
456                                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
457                                on:click=move |ev: web_sys::MouseEvent| {
458                                    ev.stop_propagation();
459                                    callback.run(node_ids.clone());
460                                }
461                            >
462                                <MaterialIcon icon=md_icons::outlined::ICON_SELECT_ALL />
463                            </button>
464                        }
465                    })}
466                    {on_ungroup.map(|callback| {
467                        let group_id = group_id.clone();
468                        view! {
469                            <button
470                                type="button"
471                                title="Ungroup"
472                                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;"
473                                on:mousedown=|ev: web_sys::MouseEvent| ev.stop_propagation()
474                                on:click=move |ev: web_sys::MouseEvent| {
475                                    ev.stop_propagation();
476                                    callback.run(group_id.clone());
477                                }
478                            >
479                                <MaterialIcon icon=md_icons::outlined::ICON_CLOSE />
480                            </button>
481                        }
482                    })}
483            </span>
484        </div>
485    }
486}
487
488#[component]
489fn MaterialIcon(icon: &'static str) -> impl IntoView {
490    let mut svg = icon.to_string();
491    if let Some(position) = svg.find("<svg") {
492        svg.insert_str(
493            position.saturating_add(4),
494            " style=\"width:100%;height:100%;display:block;fill:currentColor\" aria-hidden=\"true\" focusable=\"false\"",
495        );
496    }
497
498    view! {
499        <span
500            aria-hidden="true"
501            style="width:14px;height:14px;display:inline-flex;flex:none;"
502            inner_html=svg
503        />
504    }
505}
506
507fn next_group_color(current: &str) -> String {
508    const COLORS: [&str; 7] = [
509        "#3f4752", "#EF476F", "#F78C6B", "#FFD166", "#06D6A0", "#118AB2", "#073B4C",
510    ];
511    let index = COLORS
512        .iter()
513        .position(|color| *color == current)
514        .unwrap_or(0);
515    COLORS[(index + 1) % COLORS.len()].to_string()
516}
517
518fn members_without<N: NodeId>(node_ids: &[N], excluded: &HashSet<N>) -> Vec<N> {
519    node_ids
520        .iter()
521        .filter(|node_id| !excluded.contains(*node_id))
522        .cloned()
523        .collect()
524}
525
526/// Compute bounding box from a set of node IDs.
527fn compute_bounds<N: NodeId>(
528    node_ids: &[N],
529    nodes: &std::collections::HashMap<N, crate::registry::NodeEntry<N>>,
530    live_positions: &std::collections::HashMap<N, Position>,
531    padding: f64,
532) -> Option<GroupBounds> {
533    let mut min_x = f64::MAX;
534    let mut min_y = f64::MAX;
535    let mut max_x = f64::MIN;
536    let mut max_y = f64::MIN;
537    let mut found = false;
538
539    for node_id in node_ids {
540        let Some(entry) = nodes.get(node_id) else {
541            // A group with a stale membership should not render a misleading
542            // box. The consumer can remove the missing node and the group will
543            // recover on the next reactive update.
544            return None;
545        };
546        // Use a conservative fallback until the node's first measurement
547        // arrives. The overlay must exist during that initial frame; measured
548        // dimensions replace these values reactively as soon as they land.
549        let w = entry.size.width.max(160.0);
550        let h = entry.size.height.max(80.0);
551        // The registry position is the live interaction position. The
552        // consumer-owned signal may be backed by resolved/persisted state and
553        // only catch up when the drag is committed, so using it here makes
554        // group bounds update only on drop.
555        let position = live_positions
556            .get(node_id)
557            .copied()
558            .unwrap_or(entry.position);
559        let x = position.x;
560        let y = position.y;
561        min_x = min_x.min(x);
562        min_y = min_y.min(y);
563        max_x = max_x.max(x + w);
564        max_y = max_y.max(y + h);
565        found = true;
566    }
567
568    if !found {
569        return None;
570    }
571
572    Some(GroupBounds {
573        x: min_x - padding,
574        y: min_y - padding,
575        width: (max_x - min_x) + padding * 2.0,
576        height: (max_y - min_y) + padding * 2.0,
577    })
578}
579
580#[cfg(test)]
581mod tests {
582    use std::collections::{HashMap, HashSet};
583
584    use super::*;
585    use crate::registry::NodeEntry;
586
587    #[test]
588    fn removes_a_drag_batch_with_one_membership_update() {
589        let members = vec!["a".to_string(), "b".to_string(), "c".to_string()];
590        let moved = HashSet::from(["a".to_string(), "c".to_string()]);
591
592        assert_eq!(members_without(&members, &moved), vec!["b".to_string()]);
593    }
594
595    #[test]
596    fn drop_bounds_do_not_follow_the_dragged_member() {
597        let dragged = "dragged".to_string();
598        let anchor = "anchor".to_string();
599        let members = vec![dragged.clone(), anchor.clone()];
600        let moved = HashSet::from([dragged.clone()]);
601        let remaining = members_without(&members, &moved);
602        let nodes = HashMap::from([
603            (
604                dragged.clone(),
605                NodeEntry {
606                    id: dragged,
607                    position: Position::new(1_000.0, 1_000.0),
608                    size: Size {
609                        width: 100.0,
610                        height: 100.0,
611                    },
612                    position_signal: None,
613                },
614            ),
615            (
616                anchor.clone(),
617                NodeEntry {
618                    id: anchor,
619                    position: Position::new(0.0, 0.0),
620                    size: Size {
621                        width: 100.0,
622                        height: 100.0,
623                    },
624                    position_signal: None,
625                },
626            ),
627        ]);
628        let live_positions = nodes
629            .iter()
630            .map(|(id, node)| (id.clone(), node.position))
631            .collect();
632
633        let bounds = compute_bounds(&remaining, &nodes, &live_positions, 16.0).unwrap();
634        assert!(!bounds.contains(Position::new(1_050.0, 1_050.0)));
635    }
636}