Skip to main content

egui_pop_model/
tab.rs

1//! The Tab order of a focus scope: reading order by default, explicit
2//! indices and groups when the layout's order is wrong.
3//!
4//! - **Reading order**: rows from top to bottom, and in a row from left
5//!   to right (in a right-to-left language, from right to left). Two
6//!   stops share a row when the second's vertical centre lies within the
7//!   first's height.
8//! - **Groups**: the stops of a group follow each other, in reading
9//!   order (or by their indices), at the place of the group's first
10//!   stop.
11//! - **Indices**: stops with an explicit `index` come first, by index
12//!   (as HTML's positive `tabindex`); the others follow in reading
13//!   order. A group with indices takes its smallest.
14//! - **Skipped**: a stop that cannot take the focus (a disabled field)
15//!   has no place in the order; a read-only one does.
16//!
17//! ```
18//! use egui_pop_model::tab::{order, TabEntry};
19//!
20//! // Two columns drawn column by column: reading order goes row by row.
21//! let stops = [
22//!     TabEntry::at([0.0, 0.0, 100.0, 20.0]),   // left, first row
23//!     TabEntry::at([0.0, 30.0, 100.0, 20.0]),  // left, second row
24//!     TabEntry::at([120.0, 0.0, 100.0, 20.0]), // right, first row
25//! ];
26//! assert_eq!(order(&stops, false), vec![0, 2, 1]);
27//! ```
28
29use serde::Serialize;
30
31/// One Tab stop as drawn.
32#[derive(Clone, Debug, PartialEq, Serialize)]
33pub struct TabEntry {
34    /// `[left, top, width, height]` in points.
35    pub rect: [f32; 4],
36    /// An explicit place in the order.
37    pub index: Option<i32>,
38    /// A group whose stops follow each other.
39    pub group: Option<String>,
40    /// Out of the order (disabled).
41    pub skip: bool,
42}
43
44impl TabEntry {
45    /// A stop at `[left, top, width, height]`.
46    pub fn at(rect: [f32; 4]) -> Self {
47        Self {
48            rect,
49            index: None,
50            group: None,
51            skip: false,
52        }
53    }
54
55    pub fn index(mut self, index: i32) -> Self {
56        self.index = Some(index);
57        self
58    }
59
60    pub fn group(mut self, group: &str) -> Self {
61        self.group = Some(group.into());
62        self
63    }
64
65    pub fn skip(mut self, skip: bool) -> Self {
66        self.skip = skip;
67        self
68    }
69
70    fn top(&self) -> f32 {
71        self.rect[1]
72    }
73
74    fn bottom(&self) -> f32 {
75        self.rect[1] + self.rect[3]
76    }
77
78    fn centre_y(&self) -> f32 {
79        self.rect[1] + self.rect[3] / 2.0
80    }
81
82    fn left(&self) -> f32 {
83        self.rect[0]
84    }
85
86    fn right(&self) -> f32 {
87        self.rect[0] + self.rect[2]
88    }
89}
90
91/// The stops in reading order (indices into `entries`, skipped ones
92/// left out). `rtl` reads each row from right to left.
93pub fn reading_order(entries: &[TabEntry], rtl: bool) -> Vec<usize> {
94    let mut by_top: Vec<usize> = (0..entries.len()).filter(|&i| !entries[i].skip).collect();
95    by_top.sort_by(|&a, &b| {
96        let (a, b) = (&entries[a], &entries[b]);
97        a.top()
98            .total_cmp(&b.top())
99            .then(a.left().total_cmp(&b.left()))
100    });
101    let mut rows: Vec<Vec<usize>> = Vec::new();
102    let mut band = (f32::NEG_INFINITY, f32::NEG_INFINITY);
103    for i in by_top {
104        let e = &entries[i];
105        let c = e.centre_y();
106        let same_row = !rows.is_empty() && (band.0..=band.1).contains(&c);
107        if same_row {
108            if let Some(row) = rows.last_mut() {
109                row.push(i);
110            }
111        } else {
112            rows.push(vec![i]);
113            band = (e.top(), e.bottom());
114        }
115    }
116    let mut out = Vec::new();
117    for mut row in rows {
118        row.sort_by(|&a, &b| {
119            let (a, b) = (&entries[a], &entries[b]);
120            if rtl {
121                b.right().total_cmp(&a.right())
122            } else {
123                a.left().total_cmp(&b.left())
124            }
125        });
126        out.extend(row);
127    }
128    out
129}
130
131/// The Tab order of a scope's stops (indices into `entries`, skipped
132/// ones left out); see [the rules](self).
133pub fn order(entries: &[TabEntry], rtl: bool) -> Vec<usize> {
134    let reading = reading_order(entries, rtl);
135    let rank = |i: usize| reading.iter().position(|&r| r == i).unwrap_or(usize::MAX);
136    // Units: a group (its stops together) or a single stop, at the place
137    // of its first stop in reading order.
138    let mut units: Vec<Vec<usize>> = Vec::new();
139    for &i in &reading {
140        match &entries[i].group {
141            Some(g) => {
142                if let Some(u) = units
143                    .iter_mut()
144                    .find(|u| entries[u[0]].group.as_deref() == Some(g.as_str()))
145                {
146                    u.push(i);
147                } else {
148                    units.push(vec![i]);
149                }
150            }
151            None => units.push(vec![i]),
152        }
153    }
154    for u in &mut units {
155        u.sort_by_key(|&i| (entries[i].index.unwrap_or(i32::MAX), rank(i)));
156    }
157    let unit_index = |u: &Vec<usize>| u.iter().filter_map(|&i| entries[i].index).min();
158    // Stable: units without an index keep their reading place.
159    units.sort_by_key(|u| match unit_index(u) {
160        Some(n) => (0, n),
161        None => (1, 0),
162    });
163    units.into_iter().flatten().collect()
164}
165
166/// The stop after `current` in `order` (before it when `back`): `None`
167/// at either end unless `cycle`, when it wraps round. A `current` not in
168/// the order goes to the first stop (the last when `back`).
169pub fn next(order: &[usize], current: Option<usize>, back: bool, cycle: bool) -> Option<usize> {
170    if order.is_empty() {
171        return None;
172    }
173    let Some(at) = current.and_then(|c| order.iter().position(|&o| o == c)) else {
174        return Some(if back {
175            order[order.len() - 1]
176        } else {
177            order[0]
178        });
179    };
180    let n = order.len();
181    if back {
182        if at == 0 {
183            cycle.then(|| order[n - 1])
184        } else {
185            Some(order[at - 1])
186        }
187    } else if at + 1 == n {
188        cycle.then(|| order[0])
189    } else {
190        Some(order[at + 1])
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    fn row(y: f32, xs: &[f32]) -> Vec<TabEntry> {
199        xs.iter()
200            .map(|&x| TabEntry::at([x, y, 50.0, 20.0]))
201            .collect()
202    }
203
204    #[test]
205    fn reading_order_goes_by_rows_then_left_to_right() {
206        let mut e = row(40.0, &[100.0, 0.0]);
207        e.extend(row(0.0, &[60.0, 0.0]));
208        // A taller stop slightly lower still shares the first row.
209        e.push(TabEntry::at([200.0, 4.0, 50.0, 30.0]));
210        assert_eq!(order(&e, false), vec![3, 2, 4, 1, 0]);
211        assert_eq!(order(&e, true), vec![4, 2, 3, 0, 1]);
212    }
213
214    #[test]
215    fn indices_come_first_then_reading_order() {
216        let mut e = row(0.0, &[0.0, 60.0, 120.0]);
217        e[2] = e[2].clone().index(1);
218        assert_eq!(order(&e, false), vec![2, 0, 1]);
219    }
220
221    #[test]
222    fn a_group_stays_together_at_its_first_stop() {
223        // Two columns, the right one a group: its stops follow each
224        // other instead of interleaving by rows.
225        let mut e = Vec::new();
226        for y in [0.0, 30.0] {
227            e.push(TabEntry::at([0.0, y, 50.0, 20.0]));
228            e.push(TabEntry::at([100.0, y, 50.0, 20.0]).group("right"));
229        }
230        assert_eq!(order(&e, false), vec![0, 1, 3, 2]);
231    }
232
233    #[test]
234    fn skipped_stops_have_no_place() {
235        let mut e = row(0.0, &[0.0, 60.0, 120.0]);
236        e[1].skip = true;
237        assert_eq!(order(&e, false), vec![0, 2]);
238    }
239
240    #[test]
241    fn next_stops_at_the_ends_unless_it_cycles() {
242        let o = [3, 1, 2];
243        assert_eq!(next(&o, Some(3), false, false), Some(1));
244        assert_eq!(next(&o, Some(2), false, false), None);
245        assert_eq!(next(&o, Some(2), false, true), Some(3));
246        assert_eq!(next(&o, Some(3), true, true), Some(2));
247        assert_eq!(next(&o, Some(3), true, false), None);
248        assert_eq!(next(&o, None, false, false), Some(3));
249        assert_eq!(next(&o, None, true, false), Some(2));
250        assert_eq!(next(&[], None, false, true), None);
251    }
252}