Skip to main content

egui_pop_views/
select.rs

1//! Selection by key, shared by the tree, the list and the table.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! A selection holds keys, never row numbers: rows come and go, are
7//! sorted or moved, and what was selected stays selected. The **cursor**
8//! is the row the keyboard is on; the **anchor** is where a range
9//! (Shift) starts.
10//!
11//! ```
12//! use egui_pop_views::select::{Mode, Selection};
13//!
14//! let rows = [10, 20, 30, 40];
15//! let mut s = Selection::<u32>::default();
16//! s.apply(s.click(Mode::Multiple, rows.len(), &|i| rows[i], 1, egui::Modifiers::NONE));
17//! s.apply(s.click(Mode::Multiple, rows.len(), &|i| rows[i], 3, egui::Modifiers::SHIFT));
18//! assert_eq!(s.keys(), &[20, 30, 40]);
19//! assert_eq!(s.cursor(), Some(&40));
20//! ```
21
22use std::collections::HashSet;
23use std::hash::Hash;
24
25use egui::Modifiers;
26use serde::Serialize;
27use serde::de::DeserializeOwned;
28use serde_json::{Value as Json, json};
29
30/// What a view's keys are: cloned, compared, hashed, and carried in
31/// step arguments as JSON.
32pub trait Key:
33    Clone + Eq + Hash + std::fmt::Debug + Serialize + DeserializeOwned + 'static
34{
35}
36
37impl<T: Clone + Eq + Hash + std::fmt::Debug + Serialize + DeserializeOwned + 'static> Key for T {}
38
39/// How many rows may be selected.
40#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
41pub enum Mode {
42    /// Rows are not selectable (the cursor still moves).
43    None,
44    /// One row at a time.
45    #[default]
46    Single,
47    /// Several rows: Ctrl toggles one, Shift extends a range, Ctrl+A
48    /// selects all.
49    Multiple,
50}
51
52/// The selected keys, the cursor and the anchor.
53#[derive(Clone, Debug)]
54pub struct Selection<K> {
55    keys: Vec<K>,
56    set: HashSet<K>,
57    cursor: Option<K>,
58    anchor: Option<K>,
59}
60
61impl<K: Key> PartialEq for Selection<K> {
62    fn eq(&self, other: &Self) -> bool {
63        self.keys == other.keys && self.cursor == other.cursor && self.anchor == other.anchor
64    }
65}
66
67impl<K> Default for Selection<K> {
68    fn default() -> Self {
69        Self {
70            keys: Vec::new(),
71            set: HashSet::new(),
72            cursor: None,
73            anchor: None,
74        }
75    }
76}
77
78/// A selection a gesture proposes, before its step runs.
79#[derive(Clone, Debug, PartialEq)]
80pub struct Proposal<K> {
81    pub keys: Vec<K>,
82    pub cursor: Option<K>,
83    pub anchor: Option<K>,
84}
85
86impl<K: Key> Proposal<K> {
87    /// The step's arguments: `keys` and `cursor`, under `field` naming
88    /// the view.
89    pub fn args(&self, field: &str, view: &str) -> Json {
90        json!({ field: view, "keys": self.keys, "cursor": self.cursor })
91    }
92
93    /// The proposal as a (possibly redirected) step's arguments give it.
94    pub fn from_args(&self, args: &Json) -> Result<Proposal<K>, String> {
95        let keys: Vec<K> =
96            serde_json::from_value(args["keys"].clone()).map_err(|e| format!("keys: {e}"))?;
97        let cursor: Option<K> =
98            serde_json::from_value(args["cursor"].clone()).map_err(|e| format!("cursor: {e}"))?;
99        let anchor = if keys == self.keys {
100            self.anchor.clone()
101        } else {
102            cursor.clone()
103        };
104        Ok(Proposal {
105            keys,
106            cursor,
107            anchor,
108        })
109    }
110}
111
112impl<K: Key> Selection<K> {
113    /// The selected keys, in the order they were selected.
114    pub fn keys(&self) -> &[K] {
115        &self.keys
116    }
117
118    pub fn contains(&self, key: &K) -> bool {
119        self.set.contains(key)
120    }
121
122    pub fn is_empty(&self) -> bool {
123        self.keys.is_empty()
124    }
125
126    pub fn len(&self) -> usize {
127        self.keys.len()
128    }
129
130    /// The row the keyboard is on.
131    pub fn cursor(&self) -> Option<&K> {
132        self.cursor.as_ref()
133    }
134
135    /// Where a Shift range starts.
136    pub fn anchor(&self) -> Option<&K> {
137        self.anchor.as_ref()
138    }
139
140    /// Selects these keys, the cursor on `cursor`.
141    pub fn set(&mut self, keys: impl IntoIterator<Item = K>, cursor: Option<K>) {
142        self.keys.clear();
143        self.set.clear();
144        for k in keys {
145            if self.set.insert(k.clone()) {
146                self.keys.push(k);
147            }
148        }
149        self.anchor = cursor.clone();
150        self.cursor = cursor;
151    }
152
153    /// Selects these keys, the cursor and the anchor kept (a selection
154    /// shared with other widgets, followed).
155    pub fn set_keys(&mut self, keys: impl IntoIterator<Item = K>) {
156        self.keys.clear();
157        self.set.clear();
158        for k in keys {
159            if self.set.insert(k.clone()) {
160                self.keys.push(k);
161            }
162        }
163    }
164
165    /// Moves the cursor without changing the selection.
166    pub fn set_cursor(&mut self, cursor: Option<K>) {
167        self.cursor = cursor;
168    }
169
170    pub fn clear(&mut self) {
171        self.set(Vec::new(), None);
172    }
173
174    /// Keeps the keys `keep` accepts (rows that are gone are dropped);
175    /// the cursor and anchor go too when refused. Returns whether
176    /// anything was dropped.
177    pub fn retain(&mut self, keep: impl Fn(&K) -> bool) -> bool {
178        let before = self.keys.len();
179        self.keys.retain(|k| keep(k));
180        self.set.retain(|k| keep(k));
181        if self.cursor.as_ref().is_some_and(|c| !keep(c)) {
182            self.cursor = None;
183        }
184        if self.anchor.as_ref().is_some_and(|a| !keep(a)) {
185            self.anchor = None;
186        }
187        before != self.keys.len()
188    }
189
190    /// Applies a proposal.
191    pub fn apply(&mut self, p: Proposal<K>) {
192        self.set(p.keys, p.cursor);
193        self.anchor = p.anchor;
194    }
195
196    /// The selection a click on row `index` proposes. `key_at` gives
197    /// the key of a row; `len` is how many rows there are.
198    pub fn click(
199        &self,
200        mode: Mode,
201        len: usize,
202        key_at: &dyn Fn(usize) -> K,
203        index: usize,
204        modifiers: Modifiers,
205    ) -> Proposal<K> {
206        let key = key_at(index);
207        match mode {
208            Mode::None => self.only_cursor(key),
209            Mode::Single => self.single(key),
210            Mode::Multiple if modifiers.command => {
211                let mut keys = self.keys.clone();
212                if self.contains(&key) {
213                    keys.retain(|k| *k != key);
214                } else {
215                    keys.push(key.clone());
216                }
217                Proposal {
218                    keys,
219                    cursor: Some(key.clone()),
220                    anchor: Some(key),
221                }
222            }
223            Mode::Multiple if modifiers.shift => self.range(len, key_at, index),
224            Mode::Multiple => self.single(key),
225        }
226    }
227
228    /// The selection moving the cursor to row `index` with the keyboard
229    /// proposes: Shift extends from the anchor, Ctrl moves the cursor
230    /// alone.
231    pub fn move_to(
232        &self,
233        mode: Mode,
234        len: usize,
235        key_at: &dyn Fn(usize) -> K,
236        index: usize,
237        modifiers: Modifiers,
238    ) -> Proposal<K> {
239        let key = key_at(index);
240        match mode {
241            Mode::None => self.only_cursor(key),
242            Mode::Multiple if modifiers.shift => self.range(len, key_at, index),
243            Mode::Multiple if modifiers.command => self.only_cursor(key),
244            _ => self.single(key),
245        }
246    }
247
248    /// Every row (Ctrl+A).
249    pub fn all(&self, len: usize, key_at: &dyn Fn(usize) -> K) -> Proposal<K> {
250        Proposal {
251            keys: (0..len).map(key_at).collect(),
252            cursor: self.cursor.clone(),
253            anchor: self.anchor.clone(),
254        }
255    }
256
257    /// Toggles the cursor's row (Ctrl+Space).
258    pub fn toggle_cursor(&self, mode: Mode) -> Option<Proposal<K>> {
259        let key = self.cursor.clone()?;
260        let mut keys = self.keys.clone();
261        match mode {
262            Mode::None => return None,
263            Mode::Single if self.contains(&key) => keys.clear(),
264            Mode::Single => keys = vec![key.clone()],
265            Mode::Multiple if self.contains(&key) => keys.retain(|k| *k != key),
266            Mode::Multiple => keys.push(key.clone()),
267        }
268        Some(Proposal {
269            keys,
270            cursor: Some(key.clone()),
271            anchor: Some(key),
272        })
273    }
274
275    fn only_cursor(&self, key: K) -> Proposal<K> {
276        Proposal {
277            keys: self.keys.clone(),
278            cursor: Some(key),
279            anchor: self.anchor.clone(),
280        }
281    }
282
283    fn single(&self, key: K) -> Proposal<K> {
284        Proposal {
285            keys: vec![key.clone()],
286            cursor: Some(key.clone()),
287            anchor: Some(key),
288        }
289    }
290
291    fn range(&self, len: usize, key_at: &dyn Fn(usize) -> K, index: usize) -> Proposal<K> {
292        let from = self
293            .anchor
294            .as_ref()
295            .and_then(|a| (0..len).find(|&i| key_at(i) == *a))
296            .unwrap_or(index);
297        let (lo, hi) = if from <= index {
298            (from, index)
299        } else {
300            (index, from)
301        };
302        Proposal {
303            keys: (lo..=hi).map(key_at).collect(),
304            cursor: Some(key_at(index)),
305            anchor: Some(key_at(from)),
306        }
307    }
308}
309
310/// Runs a selection step (`list.select`, `table.select`): the default
311/// applies the proposal, or what a before-hook redirected it to.
312/// Returns the selection made, or why there was none.
313pub(crate) fn run<K: Key>(
314    app: Option<&crate::app_link::AppHandle>,
315    step: &egui_pop_model::ids::StepId,
316    field: &str,
317    view: &str,
318    selection: &mut Selection<K>,
319    p: Proposal<K>,
320) -> Result<Proposal<K>, String> {
321    let mut done = p.clone();
322    let outcome = crate::steps::run(app, step, p.args(field, view), |args| {
323        done = p.from_args(args)?;
324        selection.apply(done.clone());
325        Ok(json!(done.keys.len()))
326    });
327    match outcome {
328        crate::app_link::Outcome::Done(Ok(_)) => Ok(done),
329        crate::app_link::Outcome::Done(Err(reason))
330        | crate::app_link::Outcome::Vetoed { reason, .. } => Err(reason),
331    }
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    fn rows(i: usize) -> u32 {
339        i as u32 * 10
340    }
341
342    #[test]
343    fn ctrl_toggles_and_shift_extends_from_the_anchor() {
344        let mut s = Selection::<u32>::default();
345        s.apply(s.click(Mode::Multiple, 10, &rows, 2, Modifiers::NONE));
346        s.apply(s.click(Mode::Multiple, 10, &rows, 5, Modifiers::COMMAND));
347        assert_eq!(s.keys(), &[20, 50]);
348        s.apply(s.click(Mode::Multiple, 10, &rows, 3, Modifiers::SHIFT));
349        assert_eq!(s.keys(), &[30, 40, 50]);
350        assert_eq!(s.anchor(), Some(&50));
351        s.apply(s.click(Mode::Multiple, 10, &rows, 5, Modifiers::COMMAND));
352        assert_eq!(s.keys(), &[30, 40]);
353    }
354
355    #[test]
356    fn single_mode_ignores_modifiers_and_retain_drops_gone_rows() {
357        let mut s = Selection::<u32>::default();
358        s.apply(s.click(Mode::Single, 10, &rows, 2, Modifiers::NONE));
359        s.apply(s.click(Mode::Single, 10, &rows, 4, Modifiers::SHIFT));
360        assert_eq!(s.keys(), &[40]);
361        assert!(s.retain(|k| *k != 40));
362        assert!(s.is_empty());
363        assert_eq!(s.cursor(), None);
364    }
365
366    #[test]
367    fn a_redirect_replaces_the_proposal() {
368        let s = Selection::<u32>::default();
369        let p = s.click(Mode::Multiple, 10, &rows, 2, Modifiers::NONE);
370        let args = p.args("list", "l");
371        assert_eq!(args, json!({ "list": "l", "keys": [20], "cursor": 20 }));
372        let q = p
373            .from_args(&json!({ "keys": [30, 40], "cursor": 40 }))
374            .unwrap();
375        assert_eq!(q.keys, vec![30, 40]);
376        assert_eq!(q.anchor, Some(40));
377    }
378}