Skip to main content

slint_node_editor/
selection.rs

1//! Host-side selection helpers.
2//!
3//! The editor holds no selection state. It reports gestures — a node or link
4//! was clicked, the background was clicked, a marquee was released — and
5//! renders the `selected` flag it finds on the rows of your models. Everything
6//! between those two ends is the host's, and this module is what the host
7//! needs to do it:
8//!
9//! - [`resolve_click`] and [`resolve_box`] hold the *policy*: what a click,
10//!   a shift-click, a marquee and a shift-marquee mean. They are pure — no
11//!   storage, no interior mutability — so the host is free to keep the
12//!   selection wherever it already keeps its state.
13//! - [`project_selection`] writes a selection back into the rows, and
14//!   [`selected_rows`] reads it back out, so a host that wants no separate
15//!   store can let the rows *be* the selection.
16//!
17//! # Contract
18//!
19//! Every intent resolves to an **absolute set**: the resolvers take the
20//! current selection and return the new one in full, never a delta. There is
21//! no "add" or "remove" call, and no reachable state in which a selection was
22//! half-applied.
23//!
24//! # Order
25//!
26//! Both resolvers are **order-stable**: surviving members keep their relative
27//! order and new members are appended. Order is presentation-stable and
28//! semantically meaningless — it is what an introspecting client sees, and
29//! nothing may interpret it. If you ever need a distinguished member (a paste
30//! anchor, a "primary" selection), that is an explicit concept to add, never a
31//! position in this vector.
32
33use slint::Model;
34
35/// Resolve a click on `item` against the current selection.
36///
37/// Without shift a click replaces the selection with `item`. With shift it
38/// toggles: an unselected item joins the end, a selected one drops out and
39/// the rest keep their order.
40pub fn resolve_click<T: Clone + PartialEq>(current: &[T], item: T, shift: bool) -> Vec<T> {
41    if !shift {
42        return vec![item];
43    }
44    if current.contains(&item) {
45        current.iter().filter(|x| **x != item).cloned().collect()
46    } else {
47        let mut extended = Vec::with_capacity(current.len() + 1);
48        extended.extend_from_slice(current);
49        extended.push(item);
50        extended
51    }
52}
53
54/// Resolve a released marquee against the current selection.
55///
56/// Without shift the hits become the selection. With shift the marquee
57/// extends it: the current selection keeps its order, and whichever hits
58/// aren't already in it are appended. Extending never toggles — a hit that is
59/// already selected stays selected.
60pub fn resolve_box<T: Clone + PartialEq>(current: &[T], hits: Vec<T>, shift: bool) -> Vec<T> {
61    if !shift {
62        return hits;
63    }
64    let mut extended = current.to_vec();
65    for hit in hits {
66        if !extended.contains(&hit) {
67            extended.push(hit);
68        }
69    }
70    extended
71}
72
73/// Project a selection into a model's per-row `selected` flag.
74///
75/// Rendering reads `selected` as model data, so every write to the host's
76/// selection must be followed by a projection into the rows. `wanted` decides
77/// whether a row should be selected; `flag` hands back the row's own flag,
78/// which is both read and written — one accessor, so the read and the write
79/// can never disagree about which field holds the answer.
80///
81/// Only rows whose flag actually changes are written back, so untouched rows
82/// don't re-render.
83///
84/// ```
85/// use slint::VecModel;
86/// use slint_node_editor::selection::project_selection;
87///
88/// #[derive(Clone)]
89/// struct Row { id: i32, selected: bool }
90/// let nodes = VecModel::from(vec![
91///     Row { id: 1, selected: false },
92///     Row { id: 2, selected: false },
93/// ]);
94/// let selection = [2];
95/// project_selection(
96///     &nodes,
97///     |node| selection.contains(&node.id),
98///     |node| &mut node.selected,
99/// );
100/// ```
101pub fn project_selection<T: Clone + 'static>(
102    model: &impl Model<Data = T>,
103    wanted: impl Fn(&T) -> bool,
104    flag: impl Fn(&mut T) -> &mut bool,
105) {
106    for i in 0..model.row_count() {
107        let Some(mut row) = model.row_data(i) else {
108            continue;
109        };
110        let want = wanted(&row);
111        let current = flag(&mut row);
112        if *current != want {
113            *current = want;
114            model.set_row_data(i, row);
115        }
116    }
117}
118
119/// Apply a click to a model whose rows carry the selection.
120///
121/// Reads the current selection out of the rows, resolves the click against it,
122/// and projects the answer back — the whole gesture, with no state in between.
123/// `flag` is the row's own selected field, used for both halves.
124pub fn apply_click<T: Clone + 'static, K: Clone + PartialEq>(
125    model: &impl Model<Data = T>,
126    key: impl Fn(&T) -> K,
127    flag: impl Fn(&mut T) -> &mut bool,
128    item: K,
129    shift: bool,
130) {
131    let current = collect_selected(model, &key, &flag);
132    let next = resolve_click(&current, item, shift);
133    project_selection(model, |row| next.contains(&key(row)), &flag);
134}
135
136/// Apply a released marquee to a model whose rows carry the selection.
137///
138/// The mirror of [`apply_click`] for [`resolve_box`].
139pub fn apply_box<T: Clone + 'static, K: Clone + PartialEq>(
140    model: &impl Model<Data = T>,
141    key: impl Fn(&T) -> K,
142    flag: impl Fn(&mut T) -> &mut bool,
143    hits: Vec<K>,
144    shift: bool,
145) {
146    let current = collect_selected(model, &key, &flag);
147    let next = resolve_box(&current, hits, shift);
148    project_selection(model, |row| next.contains(&key(row)), &flag);
149}
150
151/// Deselect every row of a model.
152pub fn clear_selection<T: Clone + 'static>(
153    model: &impl Model<Data = T>,
154    flag: impl Fn(&mut T) -> &mut bool,
155) {
156    project_selection(model, |_| false, flag);
157}
158
159/// Read the selection through the same mutable accessor the writers use, so a
160/// gesture never needs a second accessor that could disagree with it.
161fn collect_selected<T: Clone + 'static, K>(
162    model: &impl Model<Data = T>,
163    key: &impl Fn(&T) -> K,
164    flag: &impl Fn(&mut T) -> &mut bool,
165) -> Vec<K> {
166    (0..model.row_count())
167        .filter_map(|i| model.row_data(i))
168        .filter_map(|mut row| {
169            if *flag(&mut row) {
170                Some(key(&row))
171            } else {
172                None
173            }
174        })
175        .collect()
176}
177
178/// Collect a key for every row the model currently shows as selected.
179///
180/// The rows are a complete record of the selection, so this is how a host
181/// with no separate selection store reads the current set before resolving a
182/// gesture against it. Results come back in row order — the rows do not
183/// remember the order the selection was built in.
184pub fn selected_rows<T: Clone + 'static, K>(
185    model: &impl Model<Data = T>,
186    key: impl Fn(&T) -> K,
187    flag: impl Fn(&T) -> bool,
188) -> Vec<K> {
189    (0..model.row_count())
190        .filter_map(|i| model.row_data(i))
191        .filter(|row| flag(row))
192        .map(|row| key(&row))
193        .collect()
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use slint::VecModel;
200    use std::rc::Rc;
201
202    // ========================================================================
203    // resolve_click() — click policy
204    // ========================================================================
205
206    #[test]
207    fn click_replaces_the_selection() {
208        assert_eq!(resolve_click(&[1, 2, 3], 9, false), vec![9]);
209    }
210
211    #[test]
212    fn click_on_the_only_selected_item_is_idempotent() {
213        assert_eq!(resolve_click(&[7], 7, false), vec![7]);
214    }
215
216    #[test]
217    fn shift_click_appends_an_unselected_item() {
218        assert_eq!(resolve_click(&[1, 2], 3, true), vec![1, 2, 3]);
219    }
220
221    #[test]
222    fn shift_click_removes_a_selected_item_and_keeps_order() {
223        assert_eq!(resolve_click(&[1, 2, 3], 2, true), vec![1, 3]);
224    }
225
226    #[test]
227    fn shift_click_on_an_empty_selection_selects() {
228        assert_eq!(resolve_click(&[], 4, true), vec![4]);
229    }
230
231    #[test]
232    fn click_policy_is_not_id_specific() {
233        // The resolvers are generic so hosts can key selection by whatever
234        // identity they already have — here a link's (output, input) pair.
235        let current = [(1, 2), (3, 4)];
236        assert_eq!(resolve_click(&current, (3, 4), true), vec![(1, 2)]);
237    }
238
239    // ========================================================================
240    // resolve_box() — marquee policy
241    // ========================================================================
242
243    #[test]
244    fn box_replaces_the_selection() {
245        assert_eq!(resolve_box(&[1, 2], vec![5, 6], false), vec![5, 6]);
246    }
247
248    #[test]
249    fn empty_box_clears_without_shift() {
250        assert_eq!(resolve_box(&[1, 2], Vec::new(), false), Vec::<i32>::new());
251    }
252
253    #[test]
254    fn shift_box_keeps_current_order_and_appends_new_hits() {
255        assert_eq!(resolve_box(&[3, 1], vec![4, 5], true), vec![3, 1, 4, 5]);
256    }
257
258    #[test]
259    fn shift_box_never_toggles_an_already_selected_hit() {
260        // Unlike shift-click, a hit that is already selected stays selected.
261        assert_eq!(resolve_box(&[1, 2], vec![2, 3], true), vec![1, 2, 3]);
262    }
263
264    #[test]
265    fn shift_box_with_no_hits_is_a_no_op() {
266        assert_eq!(resolve_box(&[1, 2], Vec::new(), true), vec![1, 2]);
267    }
268
269    // ========================================================================
270    // project_selection() — selection → per-row model data
271    // ========================================================================
272
273    #[derive(Clone, PartialEq, Debug)]
274    struct Row {
275        id: i32,
276        selected: bool,
277    }
278
279    fn rows(ids: &[i32]) -> Rc<VecModel<Row>> {
280        Rc::new(VecModel::from(
281            ids.iter()
282                .map(|&id| Row {
283                    id,
284                    selected: false,
285                })
286                .collect::<Vec<_>>(),
287        ))
288    }
289
290    fn project(model: &VecModel<Row>, selection: &[i32]) {
291        project_selection(model, |r| selection.contains(&r.id), |r| &mut r.selected);
292    }
293
294    fn flags(model: &VecModel<Row>) -> Vec<bool> {
295        (0..model.row_count())
296            .filter_map(|i| model.row_data(i))
297            .map(|r| r.selected)
298            .collect()
299    }
300
301    #[test]
302    fn project_marks_selected_rows() {
303        let model = rows(&[1, 2, 3]);
304        project(&model, &[2]);
305        assert_eq!(flags(&model), vec![false, true, false]);
306    }
307
308    #[test]
309    fn project_clears_stale_flags() {
310        let model = rows(&[1, 2]);
311        project(&model, &[1]);
312        project(&model, &[2]);
313        assert_eq!(flags(&model), vec![false, true]);
314    }
315
316    #[test]
317    fn project_only_writes_changed_rows() {
318        let model = rows(&[1, 2]);
319        project(&model, &[1]);
320
321        // A second projection of the same selection must write nothing. The
322        // model itself is the witness: a rewrite would have to change a flag,
323        // and none of them move.
324        let before = flags(&model);
325        project(&model, &[1]);
326        assert_eq!(flags(&model), before);
327        assert_eq!(before, vec![true, false]);
328    }
329
330    #[test]
331    fn project_into_an_empty_model_is_a_no_op() {
332        let model = rows(&[]);
333        project(&model, &[1, 2]);
334        assert_eq!(flags(&model), Vec::<bool>::new());
335    }
336
337    // ========================================================================
338    // selected_rows() — the rows are the selection
339    // ========================================================================
340
341    #[test]
342    fn selected_rows_reads_back_what_was_projected() {
343        let model = rows(&[1, 2, 3]);
344        project(&model, &[3, 1]);
345
346        // Row order, not selection order — the rows don't remember the latter.
347        assert_eq!(selected_rows(&model, |r| r.id, |r| r.selected), vec![1, 3]);
348    }
349
350    #[test]
351    fn selected_rows_is_empty_when_nothing_is_selected() {
352        let model = rows(&[1, 2]);
353        assert_eq!(
354            selected_rows(&model, |r| r.id, |r| r.selected),
355            Vec::<i32>::new()
356        );
357    }
358
359    // ========================================================================
360    // Round trip: the rows as the only selection store
361    // ========================================================================
362
363    #[test]
364    fn gesture_round_trip_through_the_rows() {
365        let model = rows(&[1, 2, 3]);
366
367        // Click 2, then shift-click 3, then shift-click 2 back off.
368        for (item, shift) in [(2, false), (3, true), (2, true)] {
369            let current = selected_rows(&model, |r| r.id, |r| r.selected);
370            let next = resolve_click(&current, item, shift);
371            project(&model, &next);
372        }
373
374        assert_eq!(flags(&model), vec![false, false, true]);
375    }
376
377    #[test]
378    fn negative_ids_work() {
379        assert_eq!(resolve_click(&[-1], -2, true), vec![-1, -2]);
380    }
381}