Skip to main content

slint_node_editor/
groups.rs

1//! Host-side group helpers.
2//!
3//! A group is an association of nodes rendered as a backing sheet behind its
4//! members. It is not a node: it has no pins and cannot be linked. Like
5//! selection, groups are model data and the editor holds none of it:
6//! membership is the `group_id` on each node row ([`GroupMember`]), and each
7//! group is a row with authoritative bounds, `collapsed` and `selected`
8//! ([`GroupModel`], implemented for the Slint `GroupData` struct).
9//!
10//! [`GroupLogic`] holds the operations on those rows as plain functions over
11//! models. One rule decides what a drag moves ([`GroupLogic::moves`]) whether
12//! it started on a node or a sheet ([`Dragged`]); the editor asks the host the
13//! same rule for its live preview. The movement and collapse contracts are
14//! spelled out once, in `docs/component-reference.md` under BaseGroup.
15
16use crate::graph::{GraphLogic, MovableNode};
17use crate::hit_test::NodeGeometry;
18use crate::selection::project_selection;
19use crate::state::GeometryCache;
20use slint::{Model, VecModel};
21use std::collections::HashSet;
22
23/// A node row that can belong to a group.
24///
25/// `group_id` is the node's membership: the id of its group, or 0 for none. It
26/// sits on the row for the same reason `selected` does — a drag commits the
27/// members of a moving group, reading them from the rows the editor renders
28/// from. There are no defaults: a host that uses groups implements both, and
29/// a host that does not never names this trait.
30pub trait GroupMember: MovableNode {
31    /// The group this node belongs to, or 0 for none.
32    fn group_id(&self) -> i32;
33    /// Change the node's membership.
34    fn set_group_id(&mut self, group_id: i32);
35}
36
37/// A group row: authoritative bounds, collapse and selection.
38///
39/// Implemented for the Slint `GroupData` struct. Implement it for your own
40/// row type to keep extra fields alongside.
41pub trait GroupModel: Clone + 'static {
42    fn id(&self) -> i32;
43    /// The authoritative bounds in world coordinates.
44    fn bounds(&self) -> Bounds;
45    fn set_bounds(&mut self, bounds: Bounds);
46    fn selected(&self) -> bool;
47    fn collapsed(&self) -> bool;
48    fn set_collapsed(&mut self, collapsed: bool);
49}
50
51impl GroupModel for crate::nodeeditor::GroupData {
52    fn id(&self) -> i32 {
53        self.id
54    }
55    fn bounds(&self) -> Bounds {
56        Bounds {
57            x: self.x,
58            y: self.y,
59            width: self.width,
60            height: self.height,
61        }
62    }
63    fn set_bounds(&mut self, bounds: Bounds) {
64        self.x = bounds.x;
65        self.y = bounds.y;
66        self.width = bounds.width;
67        self.height = bounds.height;
68    }
69    fn selected(&self) -> bool {
70        self.selected
71    }
72    fn collapsed(&self) -> bool {
73        self.collapsed
74    }
75    fn set_collapsed(&mut self, collapsed: bool) {
76        self.collapsed = collapsed;
77    }
78}
79
80/// What a drag gesture started on.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Dragged {
83    /// A node drag; the value is the dragged node's id.
84    Node(i32),
85    /// A sheet drag; the value is the dragged group's id.
86    Group(i32),
87}
88
89impl Dragged {
90    /// Build from the ids the editor's drag state carries: a group drag sets
91    /// the group id and leaves the node id 0.
92    pub fn from_ids(dragged_node_id: i32, dragged_group_id: i32) -> Self {
93        if dragged_group_id != 0 {
94            Dragged::Group(dragged_group_id)
95        } else {
96            Dragged::Node(dragged_node_id)
97        }
98    }
99}
100
101/// A world-space rectangle.
102#[derive(Clone, Copy, Debug, PartialEq)]
103pub struct Bounds {
104    pub x: f32,
105    pub y: f32,
106    pub width: f32,
107    pub height: f32,
108}
109
110impl Bounds {
111    /// The rectangle enclosing every `(x, y, width, height)` given, grown by
112    /// `padding` on every side. `None` for an empty iterator.
113    ///
114    /// [`GroupLogic::fit_bounds`] feeds it cached rectangles; a host that
115    /// knows its node sizes can feed it model rows directly and fit a group
116    /// synchronously in its drag commit, before the geometry reports arrive.
117    pub fn enclosing(
118        rects: impl IntoIterator<Item = (f32, f32, f32, f32)>,
119        padding: f32,
120    ) -> Option<Self> {
121        let mut min_x = f32::INFINITY;
122        let mut min_y = f32::INFINITY;
123        let mut max_x = f32::NEG_INFINITY;
124        let mut max_y = f32::NEG_INFINITY;
125        let mut any = false;
126        for (x, y, w, h) in rects {
127            min_x = min_x.min(x);
128            min_y = min_y.min(y);
129            max_x = max_x.max(x + w);
130            max_y = max_y.max(y + h);
131            any = true;
132        }
133        any.then_some(Bounds {
134            x: min_x - padding,
135            y: min_y - padding,
136            width: max_x - min_x + 2.0 * padding,
137            height: max_y - min_y + 2.0 * padding,
138        })
139    }
140
141    /// This rectangle shifted by a delta.
142    pub fn offset(self, dx: f32, dy: f32) -> Self {
143        Bounds {
144            x: self.x + dx,
145            y: self.y + dy,
146            ..self
147        }
148    }
149}
150
151/// Operations on group rows and node membership.
152pub struct GroupLogic;
153
154impl GroupLogic {
155    // ------------------------------------------------------------------
156    // Movement
157    // ------------------------------------------------------------------
158
159    /// Does this group row move with a drag that started on `dragged`?
160    ///
161    /// Yes when its own sheet is being dragged, or when it is selected while a
162    /// node or another sheet is. This is the one movement rule: the commit
163    /// uses it for every group, and [`Self::group_moves`] answers the editor's
164    /// live-preview question with it.
165    pub fn moves<G: GroupModel>(group: &G, dragged: Dragged) -> bool {
166        group.selected() || dragged == Dragged::Group(group.id())
167    }
168
169    /// [`Self::moves`] for a group looked up by id; unknown groups (and 0) do
170    /// not move. This is the predicate behind
171    /// `NodeEditorComputations.group-in-drag`; `wire_groups!` installs it.
172    pub fn group_moves<G: GroupModel>(
173        groups: &impl Model<Data = G>,
174        group_id: i32,
175        dragged: Dragged,
176    ) -> bool {
177        group_id != 0
178            && Self::find_group(groups, group_id).is_some_and(|(_, g)| Self::moves(&g, dragged))
179    }
180
181    /// The ids of the groups a drag moves.
182    pub fn moving_groups<G: GroupModel>(
183        groups: &impl Model<Data = G>,
184        dragged: Dragged,
185    ) -> Vec<i32> {
186        ids_where(groups, |g| Self::moves(g, dragged), G::id)
187    }
188
189    /// Commit a finished drag into one node model.
190    ///
191    /// A row moves if it is the dragged node, if it is selected and
192    /// [`draggable`](MovableNode::draggable), or if it is a member of a group
193    /// that moves. A member keeps its place in a moving group whether or not
194    /// it is draggable: left behind, it would sit outside the sheet it still
195    /// belongs to. Call once per node model when nodes are split across
196    /// several; the dragged node lives in exactly one of them.
197    pub fn commit_node_drag<T, G>(
198        nodes: &VecModel<T>,
199        groups: &impl Model<Data = G>,
200        dragged: Dragged,
201        delta_x: f32,
202        delta_y: f32,
203    ) where
204        T: GroupMember,
205        G: GroupModel,
206    {
207        let moving: HashSet<i32> = Self::moving_groups(groups, dragged).into_iter().collect();
208        update_rows(nodes, |node| {
209            let moves = dragged == Dragged::Node(node.id())
210                || GraphLogic::carried_by_selection(node)
211                || (node.group_id() != 0 && moving.contains(&node.group_id()));
212            if moves {
213                node.set_x(node.x() + delta_x);
214                node.set_y(node.y() + delta_y);
215            }
216            moves
217        });
218    }
219
220    /// Commit a finished drag into the group rows: every group that
221    /// [`Self::moves`] shifts by the delta. Call once per drag.
222    pub fn commit_group_drag<G: GroupModel>(
223        groups: &VecModel<G>,
224        dragged: Dragged,
225        delta_x: f32,
226        delta_y: f32,
227    ) {
228        update_rows(groups, |group| {
229            let moves = Self::moves(group, dragged);
230            if moves {
231                group.set_bounds(group.bounds().offset(delta_x, delta_y));
232            }
233            moves
234        });
235    }
236
237    /// Commit a finished drag into one node model and the group rows.
238    ///
239    /// The single-model convenience over [`Self::commit_node_drag`] and
240    /// [`Self::commit_group_drag`]: install it with
241    /// [`NodeEditorSetup::with_drag_commit`](crate::NodeEditorSetup::with_drag_commit)
242    /// and both gestures share one rule.
243    pub fn commit_drag<T, G>(
244        nodes: &VecModel<T>,
245        groups: &VecModel<G>,
246        dragged: Dragged,
247        delta_x: f32,
248        delta_y: f32,
249    ) where
250        T: GroupMember,
251        G: GroupModel,
252    {
253        Self::commit_node_drag(nodes, groups, dragged, delta_x, delta_y);
254        Self::commit_group_drag(groups, dragged, delta_x, delta_y);
255    }
256
257    // ------------------------------------------------------------------
258    // Collapse
259    // ------------------------------------------------------------------
260
261    /// Whether `group_id` is collapsed. Unknown groups are expanded. This is
262    /// the predicate behind `NodeEditorComputations.group-collapsed`.
263    pub fn is_collapsed<G: GroupModel>(groups: &impl Model<Data = G>, group_id: i32) -> bool {
264        Self::find_group(groups, group_id).is_some_and(|(_, g)| g.collapsed())
265    }
266
267    /// Set a group's collapsed state. Returns whether the row changed.
268    ///
269    /// Collapsing deselects the members it hides, through the same row
270    /// projection every other selection write uses (`selected` is the row's
271    /// flag, handed back by `selected`), so no later gesture acts on invisible
272    /// nodes. Expanding does not restore that selection. The sheet reacts to
273    /// the row change: members re-evaluate their visibility, and an active
274    /// drag is cancelled.
275    pub fn set_collapsed<T, G>(
276        groups: &VecModel<G>,
277        nodes: &VecModel<T>,
278        group_id: i32,
279        collapsed: bool,
280        selected: impl Fn(&mut T) -> &mut bool,
281    ) -> bool
282    where
283        T: GroupMember,
284        G: GroupModel,
285    {
286        let Some((index, mut group)) = Self::find_group(groups, group_id) else {
287            return false;
288        };
289        if group.collapsed() == collapsed {
290            return false;
291        }
292        group.set_collapsed(collapsed);
293        groups.set_row_data(index, group);
294        if collapsed {
295            project_selection(
296                nodes,
297                |n| n.selected() && n.group_id() != group_id,
298                selected,
299            );
300        }
301        true
302    }
303
304    // ------------------------------------------------------------------
305    // Membership
306    // ------------------------------------------------------------------
307
308    /// The ids of the nodes that belong to `group_id`, in row order.
309    pub fn members<T: GroupMember>(nodes: &impl Model<Data = T>, group_id: i32) -> Vec<i32> {
310        ids_where(nodes, |n| n.group_id() == group_id, T::id)
311    }
312
313    /// The selected nodes that belong to no group yet: the candidates for a
314    /// new group. A node belongs to at most one group, so selected members of
315    /// another group are left out rather than reassigned.
316    pub fn selected_ungrouped<T: GroupMember>(nodes: &impl Model<Data = T>) -> Vec<i32> {
317        ids_where(nodes, |n| n.selected() && n.group_id() == 0, T::id)
318    }
319
320    /// Make `node_ids` members of `group_id`, replacing any previous
321    /// membership. Unknown ids are ignored.
322    pub fn assign_members<T: GroupMember>(nodes: &VecModel<T>, node_ids: &[i32], group_id: i32) {
323        update_rows(nodes, |node| {
324            let assign = node_ids.contains(&node.id()) && node.group_id() != group_id;
325            if assign {
326                node.set_group_id(group_id);
327            }
328            assign
329        });
330    }
331
332    /// Take `node_id` out of its group. Returns the group it left, or `None`
333    /// if the node was unknown or ungrouped. The node stays where it is and no
334    /// longer moves with the group. When the group is now empty the caller
335    /// decides whether to keep or dissolve it ([`Self::members`]).
336    pub fn remove_member<T: GroupMember>(nodes: &VecModel<T>, node_id: i32) -> Option<i32> {
337        let (index, mut node) = GraphLogic::find_node_by_id(nodes, node_id, T::id)?;
338        let former = node.group_id();
339        if former == 0 {
340            return None;
341        }
342        node.set_group_id(0);
343        nodes.set_row_data(index, node);
344        Some(former)
345    }
346
347    /// Dissolve a group: its members become ungrouped and stay where they are,
348    /// and the row is removed. Returns whether a row was removed.
349    ///
350    /// The sheet's projected geometry is the editor's: call
351    /// `NodeEditorInternalCallbacks.remove-group(id)` on the Slint side as
352    /// well, as for a removed node.
353    pub fn dissolve_group<T, G>(nodes: &VecModel<T>, groups: &VecModel<G>, group_id: i32) -> bool
354    where
355        T: GroupMember,
356        G: GroupModel,
357    {
358        update_rows(nodes, |node| {
359            let member = node.group_id() == group_id;
360            if member {
361                node.set_group_id(0);
362            }
363            member
364        });
365        match Self::find_group(groups, group_id) {
366            Some((index, _)) => {
367                groups.remove(index);
368                true
369            }
370            None => false,
371        }
372    }
373
374    // ------------------------------------------------------------------
375    // Bounds
376    // ------------------------------------------------------------------
377
378    /// The rectangle enclosing the cached rectangles of `node_ids`, grown by
379    /// `padding` on every side. `None` when none of them has geometry yet.
380    pub fn fit_bounds<N: NodeGeometry + Copy>(
381        cache: &GeometryCache<N>,
382        node_ids: &[i32],
383        padding: f32,
384    ) -> Option<Bounds> {
385        Bounds::enclosing(
386            node_ids
387                .iter()
388                .filter_map(|id| cache.node_rects.get(id))
389                .map(|node| node.rect()),
390            padding,
391        )
392    }
393
394    /// Write `bounds` into a group row. Returns whether the row changed.
395    pub fn set_bounds<G: GroupModel>(groups: &VecModel<G>, group_id: i32, bounds: Bounds) -> bool {
396        let Some((index, mut group)) = Self::find_group(groups, group_id) else {
397            return false;
398        };
399        if group.bounds() == bounds {
400            return false;
401        }
402        group.set_bounds(bounds);
403        groups.set_row_data(index, group);
404        true
405    }
406
407    /// Find a group row by id.
408    pub fn find_group<G: GroupModel>(
409        groups: &impl Model<Data = G>,
410        group_id: i32,
411    ) -> Option<(usize, G)> {
412        GraphLogic::find_node_by_id(groups, group_id, G::id)
413    }
414}
415
416/// The ids of the rows matching `pred`, in row order.
417fn ids_where<T: Clone + 'static>(
418    model: &impl Model<Data = T>,
419    pred: impl Fn(&T) -> bool,
420    id: impl Fn(&T) -> i32,
421) -> Vec<i32> {
422    (0..model.row_count())
423        .filter_map(|i| model.row_data(i))
424        .filter(|row| pred(row))
425        .map(|row| id(&row))
426        .collect()
427}
428
429/// Run `f` over every row and write back the rows it reports changed.
430fn update_rows<T: Clone + 'static>(model: &VecModel<T>, mut f: impl FnMut(&mut T) -> bool) {
431    for i in 0..model.row_count() {
432        let Some(mut row) = model.row_data(i) else {
433            continue;
434        };
435        if f(&mut row) {
436            model.set_row_data(i, row);
437        }
438    }
439}
440
441#[cfg(test)]
442mod tests {
443    use super::*;
444    use std::rc::Rc;
445
446    #[derive(Clone, Debug, PartialEq)]
447    struct Node {
448        id: i32,
449        x: f32,
450        y: f32,
451        selected: bool,
452        group_id: i32,
453        draggable: bool,
454    }
455
456    impl MovableNode for Node {
457        fn id(&self) -> i32 {
458            self.id
459        }
460        fn x(&self) -> f32 {
461            self.x
462        }
463        fn y(&self) -> f32 {
464            self.y
465        }
466        fn selected(&self) -> bool {
467            self.selected
468        }
469        fn set_x(&mut self, x: f32) {
470            self.x = x;
471        }
472        fn set_y(&mut self, y: f32) {
473            self.y = y;
474        }
475        fn draggable(&self) -> bool {
476            self.draggable
477        }
478    }
479
480    impl GroupMember for Node {
481        fn group_id(&self) -> i32 {
482            self.group_id
483        }
484        fn set_group_id(&mut self, group_id: i32) {
485            self.group_id = group_id;
486        }
487    }
488
489    #[derive(Clone, Debug, PartialEq)]
490    struct Group {
491        id: i32,
492        bounds: Bounds,
493        selected: bool,
494        collapsed: bool,
495    }
496
497    impl GroupModel for Group {
498        fn id(&self) -> i32 {
499            self.id
500        }
501        fn bounds(&self) -> Bounds {
502            self.bounds
503        }
504        fn set_bounds(&mut self, bounds: Bounds) {
505            self.bounds = bounds;
506        }
507        fn selected(&self) -> bool {
508            self.selected
509        }
510        fn collapsed(&self) -> bool {
511            self.collapsed
512        }
513        fn set_collapsed(&mut self, collapsed: bool) {
514            self.collapsed = collapsed;
515        }
516    }
517
518    fn node(id: i32, group_id: i32, selected: bool) -> Node {
519        Node {
520            id,
521            x: 10.0 * id as f32,
522            y: 0.0,
523            selected,
524            group_id,
525            draggable: true,
526        }
527    }
528
529    fn undraggable(node: Node) -> Node {
530        Node {
531            draggable: false,
532            ..node
533        }
534    }
535
536    fn group(id: i32, selected: bool) -> Group {
537        Group {
538            id,
539            bounds: Bounds {
540                x: 0.0,
541                y: 0.0,
542                width: 100.0,
543                height: 100.0,
544            },
545            selected,
546            collapsed: false,
547        }
548    }
549
550    fn positions(nodes: &VecModel<Node>) -> Vec<(i32, f32)> {
551        (0..nodes.row_count())
552            .filter_map(|i| nodes.row_data(i))
553            .map(|n| (n.id, n.x))
554            .collect()
555    }
556
557    fn collapse(
558        groups: &VecModel<Group>,
559        nodes: &VecModel<Node>,
560        id: i32,
561        collapsed: bool,
562    ) -> bool {
563        GroupLogic::set_collapsed(groups, nodes, id, collapsed, |n| &mut n.selected)
564    }
565
566    // ------------------------------------------------------------------
567    // Movement set
568    // ------------------------------------------------------------------
569
570    #[test]
571    fn dragging_a_sheet_moves_its_members_and_nothing_else() {
572        let nodes = Rc::new(VecModel::from(vec![
573            node(1, 7, false),
574            node(2, 7, false),
575            node(3, 0, false),
576            node(4, 8, false),
577        ]));
578        let groups = Rc::new(VecModel::from(vec![group(7, false), group(8, false)]));
579
580        GroupLogic::commit_drag(&nodes, &groups, Dragged::Group(7), 5.0, 0.0);
581
582        assert_eq!(
583            positions(&nodes),
584            vec![(1, 15.0), (2, 25.0), (3, 30.0), (4, 40.0)]
585        );
586        assert_eq!(groups.row_data(0).unwrap().bounds.x, 5.0);
587        assert_eq!(groups.row_data(1).unwrap().bounds.x, 0.0);
588    }
589
590    #[test]
591    fn dragging_a_node_moves_selected_groups_with_their_members() {
592        let nodes = Rc::new(VecModel::from(vec![
593            node(1, 7, false),
594            node(2, 0, false),
595            node(3, 0, true),
596        ]));
597        let groups = Rc::new(VecModel::from(vec![group(7, true)]));
598
599        // Node 2 is dragged: it moves, the selected node 3 moves, and the
600        // selected group 7 moves with its unselected member 1.
601        GroupLogic::commit_drag(&nodes, &groups, Dragged::Node(2), 0.0, 3.0);
602
603        let ys: Vec<f32> = (0..3).map(|i| nodes.row_data(i).unwrap().y).collect();
604        assert_eq!(ys, vec![3.0, 3.0, 3.0]);
605        assert_eq!(groups.row_data(0).unwrap().bounds.y, 3.0);
606    }
607
608    #[test]
609    fn a_selected_member_of_a_dragged_group_moves_once() {
610        let nodes = Rc::new(VecModel::from(vec![node(1, 7, true)]));
611        let groups = Rc::new(VecModel::from(vec![group(7, false)]));
612
613        GroupLogic::commit_drag(&nodes, &groups, Dragged::Group(7), 5.0, 0.0);
614
615        assert_eq!(nodes.row_data(0).unwrap().x, 15.0);
616    }
617
618    #[test]
619    fn a_selected_undraggable_node_stays_when_another_node_is_dragged() {
620        let nodes = Rc::new(VecModel::from(vec![
621            node(1, 0, true),
622            undraggable(node(2, 0, true)),
623        ]));
624        let groups = Rc::new(VecModel::from(Vec::<Group>::new()));
625
626        GroupLogic::commit_drag(&nodes, &groups, Dragged::Node(1), 5.0, 0.0);
627
628        assert_eq!(positions(&nodes), vec![(1, 15.0), (2, 20.0)]);
629    }
630
631    #[test]
632    fn an_undraggable_member_moves_with_its_group() {
633        // Its own sheet dragged, then its selected group carried by a node
634        // drag: either way the member keeps its place in the group, selected
635        // or not.
636        for (dragged, group_selected) in [(Dragged::Group(7), false), (Dragged::Node(3), true)] {
637            let nodes = Rc::new(VecModel::from(vec![
638                undraggable(node(1, 7, false)),
639                undraggable(node(2, 7, true)),
640                node(3, 0, true),
641            ]));
642            let groups = Rc::new(VecModel::from(vec![group(7, group_selected)]));
643
644            GroupLogic::commit_drag(&nodes, &groups, dragged, 5.0, 0.0);
645
646            assert_eq!(
647                positions(&nodes)[..2],
648                [(1, 15.0), (2, 25.0)],
649                "{dragged:?}"
650            );
651        }
652    }
653
654    #[test]
655    fn group_moves_answers_the_preview_the_same_way_as_the_commit() {
656        let groups = Rc::new(VecModel::from(vec![group(7, true), group(8, false)]));
657
658        assert!(GroupLogic::group_moves(&*groups, 7, Dragged::Node(1)));
659        assert!(!GroupLogic::group_moves(&*groups, 8, Dragged::Node(1)));
660        assert!(GroupLogic::group_moves(&*groups, 8, Dragged::Group(8)));
661        assert!(!GroupLogic::group_moves(&*groups, 0, Dragged::Group(0)));
662        assert!(!GroupLogic::group_moves(&*groups, 99, Dragged::Node(1)));
663        assert_eq!(
664            GroupLogic::moving_groups(&*groups, Dragged::Group(8)),
665            vec![7, 8]
666        );
667        assert_eq!(Dragged::from_ids(0, 8), Dragged::Group(8));
668        assert_eq!(Dragged::from_ids(3, 0), Dragged::Node(3));
669    }
670
671    #[test]
672    fn node_drag_commit_across_two_models_moves_the_group_once() {
673        let a = Rc::new(VecModel::from(vec![node(1, 7, false)]));
674        let b = Rc::new(VecModel::from(vec![node(2, 7, false)]));
675        let groups = Rc::new(VecModel::from(vec![group(7, false)]));
676
677        GroupLogic::commit_node_drag(&a, &*groups, Dragged::Group(7), 1.0, 0.0);
678        GroupLogic::commit_node_drag(&b, &*groups, Dragged::Group(7), 1.0, 0.0);
679        GroupLogic::commit_group_drag(&groups, Dragged::Group(7), 1.0, 0.0);
680
681        assert_eq!(a.row_data(0).unwrap().x, 11.0);
682        assert_eq!(b.row_data(0).unwrap().x, 21.0);
683        assert_eq!(groups.row_data(0).unwrap().bounds.x, 1.0);
684    }
685
686    // ------------------------------------------------------------------
687    // Collapse
688    // ------------------------------------------------------------------
689
690    #[test]
691    fn collapsing_deselects_members_and_is_idempotent() {
692        let nodes = Rc::new(VecModel::from(vec![node(1, 7, true), node(2, 0, true)]));
693        let groups = Rc::new(VecModel::from(vec![group(7, false)]));
694
695        assert!(collapse(&groups, &nodes, 7, true));
696        assert!(GroupLogic::is_collapsed(&*groups, 7));
697        assert!(
698            !nodes.row_data(0).unwrap().selected,
699            "hidden member deselected"
700        );
701        assert!(nodes.row_data(1).unwrap().selected, "outsider untouched");
702
703        assert!(!collapse(&groups, &nodes, 7, true));
704        assert!(!collapse(&groups, &nodes, 99, true));
705        assert!(!GroupLogic::is_collapsed(&*groups, 99));
706    }
707
708    #[test]
709    fn expanding_does_not_restore_the_selection() {
710        let nodes = Rc::new(VecModel::from(vec![node(1, 7, true)]));
711        let groups = Rc::new(VecModel::from(vec![group(7, false)]));
712
713        collapse(&groups, &nodes, 7, true);
714        collapse(&groups, &nodes, 7, false);
715
716        assert!(!groups.row_data(0).unwrap().collapsed);
717        assert!(!nodes.row_data(0).unwrap().selected);
718    }
719
720    // ------------------------------------------------------------------
721    // Membership
722    // ------------------------------------------------------------------
723
724    #[test]
725    fn new_group_candidates_exclude_members_of_other_groups() {
726        let nodes = Rc::new(VecModel::from(vec![
727            node(1, 0, true),
728            node(2, 5, true),
729            node(3, 0, false),
730        ]));
731
732        assert_eq!(GroupLogic::selected_ungrouped(&*nodes), vec![1]);
733        GroupLogic::assign_members(&nodes, &[1, 42], 9);
734        assert_eq!(GroupLogic::members(&*nodes, 9), vec![1]);
735        assert_eq!(nodes.row_data(1).unwrap().group_id, 5);
736    }
737
738    #[test]
739    fn removing_a_member_leaves_it_in_place_and_reports_its_group() {
740        let nodes = Rc::new(VecModel::from(vec![node(1, 7, false), node(2, 7, false)]));
741
742        assert_eq!(GroupLogic::remove_member(&nodes, 1), Some(7));
743        assert_eq!(GroupLogic::remove_member(&nodes, 1), None);
744        assert_eq!(GroupLogic::remove_member(&nodes, 99), None);
745        assert_eq!(nodes.row_data(0).unwrap().x, 10.0);
746        assert_eq!(GroupLogic::members(&*nodes, 7), vec![2]);
747    }
748
749    #[test]
750    fn dissolving_ungroups_members_and_removes_the_row() {
751        let nodes = Rc::new(VecModel::from(vec![node(1, 7, false), node(2, 8, false)]));
752        let groups = Rc::new(VecModel::from(vec![group(7, false), group(8, false)]));
753
754        assert!(GroupLogic::dissolve_group(&nodes, &groups, 7));
755        assert!(!GroupLogic::dissolve_group(&nodes, &groups, 7));
756
757        assert_eq!(nodes.row_data(0).unwrap().group_id, 0);
758        assert_eq!(nodes.row_data(1).unwrap().group_id, 8);
759        assert_eq!(groups.row_count(), 1);
760        assert_eq!(groups.row_data(0).unwrap().id, 8);
761    }
762
763    // ------------------------------------------------------------------
764    // Bounds
765    // ------------------------------------------------------------------
766
767    #[test]
768    fn fit_bounds_is_the_padded_union_of_cached_member_rects() {
769        let mut cache = GeometryCache::new();
770        cache.update_node_rect(1, 100.0, 100.0, 50.0, 20.0);
771        cache.update_node_rect(2, 200.0, 50.0, 10.0, 100.0);
772
773        assert_eq!(
774            GroupLogic::fit_bounds(&cache, &[1, 2, 3], 10.0),
775            Some(Bounds {
776                x: 90.0,
777                y: 40.0,
778                width: 130.0,
779                height: 120.0
780            })
781        );
782        assert_eq!(GroupLogic::fit_bounds(&cache, &[3], 10.0), None);
783        assert_eq!(GroupLogic::fit_bounds(&cache, &[], 10.0), None);
784    }
785
786    #[test]
787    fn set_bounds_writes_the_row_only_when_it_changes() {
788        let groups = Rc::new(VecModel::from(vec![group(7, false)]));
789        let fitted = Bounds {
790            x: 5.0,
791            y: -5.0,
792            width: 40.0,
793            height: 40.0,
794        };
795
796        assert!(GroupLogic::set_bounds(&groups, 7, fitted));
797        assert_eq!(groups.row_data(0).unwrap().bounds, fitted);
798        assert!(!GroupLogic::set_bounds(&groups, 7, fitted));
799        assert!(!GroupLogic::set_bounds(&groups, 8, fitted));
800        assert_eq!(
801            fitted.offset(1.0, 2.0),
802            Bounds {
803                x: 6.0,
804                y: -3.0,
805                ..fitted
806            }
807        );
808    }
809}