Skip to main content

egui_pop_views/
nav.rs

1//! Keyboard navigation shared by the views: the keys a focused view
2//! reads, where they move the cursor, and type-ahead.
3//!
4//! A view reads its keys only while it has the focus. It says which
5//! ([`READS`], through `focus::reads_keys`), so that they reach it before
6//! a global binding of theirs; a key bound in the view's surface, panel or
7//! window, or with Ctrl or Alt, runs its command and never reaches the
8//! view.
9
10use egui::{Event, Key, Modifiers, Ui};
11
12/// The keys a focused view reads itself: the arrows, Page Up and Page
13/// Down, Home and End, Space and Enter.
14pub(crate) const READS: [Key; 10] = [
15    Key::ArrowUp,
16    Key::ArrowDown,
17    Key::ArrowLeft,
18    Key::ArrowRight,
19    Key::PageUp,
20    Key::PageDown,
21    Key::Home,
22    Key::End,
23    Key::Space,
24    Key::Enter,
25];
26
27/// What a key asks a view to do.
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub(crate) enum Nav {
30    Up,
31    Down,
32    PageUp,
33    PageDown,
34    Home,
35    End,
36    Left,
37    Right,
38    Space,
39    Rename,
40    Activate,
41    All,
42    Text(String),
43}
44
45/// The navigation keys pressed this pass, with their modifiers.
46pub(crate) fn read(ui: &Ui) -> Vec<(Nav, Modifiers)> {
47    ui.input(|i| {
48        let mut out = Vec::new();
49        for e in &i.events {
50            match e {
51                Event::Key {
52                    key,
53                    pressed: true,
54                    modifiers,
55                    ..
56                } => {
57                    let nav = match key {
58                        Key::ArrowUp => Nav::Up,
59                        Key::ArrowDown => Nav::Down,
60                        Key::PageUp => Nav::PageUp,
61                        Key::PageDown => Nav::PageDown,
62                        Key::Home => Nav::Home,
63                        Key::End => Nav::End,
64                        Key::ArrowLeft => Nav::Left,
65                        Key::ArrowRight => Nav::Right,
66                        Key::Space => Nav::Space,
67                        Key::F2 => Nav::Rename,
68                        Key::Enter => Nav::Activate,
69                        Key::A if modifiers.command => Nav::All,
70                        _ => continue,
71                    };
72                    out.push((nav, *modifiers));
73                }
74                Event::Text(t) if !i.modifiers.command && !t.trim().is_empty() => {
75                    out.push((Nav::Text(t.clone()), i.modifiers));
76                }
77                _ => {}
78            }
79        }
80        out
81    })
82}
83
84/// Where a movement key puts the cursor, `page` rows to a page.
85pub(crate) fn target(nav: &Nav, cursor: Option<usize>, len: usize, page: usize) -> Option<usize> {
86    if len == 0 {
87        return None;
88    }
89    let last = len - 1;
90    let page = page.max(1);
91    Some(match (nav, cursor) {
92        (Nav::Home, _) => 0,
93        (Nav::End, _) => last,
94        (Nav::Up | Nav::PageUp, None) => last,
95        (Nav::Down | Nav::PageDown, None) => 0,
96        (Nav::Up, Some(c)) => c.saturating_sub(1),
97        (Nav::Down, Some(c)) => (c + 1).min(last),
98        (Nav::PageUp, Some(c)) => c.saturating_sub(page),
99        (Nav::PageDown, Some(c)) => (c + page).min(last),
100        _ => return None,
101    })
102}
103
104/// How long typed letters keep adding to the search, in seconds.
105pub const TYPE_AHEAD_DELAY: f64 = 1.0;
106
107/// Typed letters searched among the rows' labels.
108#[derive(Clone, Debug, Default)]
109pub(crate) struct TypeAhead {
110    text: String,
111    last: f64,
112}
113
114impl TypeAhead {
115    /// Adds typed text at time `now`; returns the search.
116    pub fn push(&mut self, text: &str, now: f64) -> &str {
117        if now - self.last > TYPE_AHEAD_DELAY {
118            self.text.clear();
119        }
120        self.last = now;
121        self.text.push_str(&text.to_lowercase());
122        &self.text
123    }
124}
125
126/// The first row from the cursor whose label starts with `search`
127/// (ignoring case), wrapping. One letter starts after the cursor, so
128/// pressing it again cycles through the rows starting with it.
129pub(crate) fn find(
130    search: &str,
131    cursor: Option<usize>,
132    len: usize,
133    label_at: &dyn Fn(usize) -> String,
134) -> Option<usize> {
135    if len == 0 || search.is_empty() {
136        return None;
137    }
138    let same = search.chars().all(|c| search.starts_with(c));
139    let start = match cursor {
140        Some(c) if same => c + 1,
141        Some(c) => c,
142        None => 0,
143    };
144    let needle = if same {
145        &search[..search.chars().next().map_or(0, char::len_utf8)]
146    } else {
147        search
148    };
149    (0..len)
150        .map(|i| (start + i) % len)
151        .find(|&i| label_at(i).to_lowercase().starts_with(needle))
152}
153
154/// The scroll offset that brings row `row` into a view `height` high,
155/// rows `row_h` high, now scrolled to `offset`.
156pub(crate) fn reveal(row: usize, row_h: f32, offset: f32, height: f32) -> f32 {
157    let top = row as f32 * row_h;
158    if top < offset {
159        top
160    } else if top + row_h > offset + height {
161        (top + row_h - height).max(0.0)
162    } else {
163        offset
164    }
165}
166
167/// The keys of a focused flat view (a list, a table): the selections
168/// they propose, the row to bring into view, and the cursor's key when
169/// Enter activates it.
170#[allow(
171    clippy::too_many_arguments,
172    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
173)]
174pub(crate) fn flat<K: crate::select::Key>(
175    ui: &Ui,
176    selection: &crate::select::Selection<K>,
177    mode: crate::select::Mode,
178    len: usize,
179    key_at: &dyn Fn(usize) -> K,
180    label_at: &dyn Fn(usize) -> String,
181    page: usize,
182    type_ahead: &mut TypeAhead,
183) -> (Vec<crate::select::Proposal<K>>, Option<usize>, Option<K>) {
184    let keys = read(ui);
185    let mut out = Vec::new();
186    let mut reveal = None;
187    let mut activate = None;
188    if keys.is_empty() || len == 0 {
189        return (out, reveal, activate);
190    }
191    let cursor = selection
192        .cursor()
193        .and_then(|c| (0..len).find(|&i| key_at(i) == *c));
194    let now = ui.input(|i| i.time);
195    for (k, mods) in keys {
196        let to = match &k {
197            Nav::Up | Nav::Down | Nav::PageUp | Nav::PageDown | Nav::Home | Nav::End => {
198                target(&k, cursor, len, page).map(|j| (j, mods))
199            }
200            Nav::Space if mods.command => {
201                out.extend(selection.toggle_cursor(mode));
202                None
203            }
204            Nav::Space => cursor.map(|c| (c, Modifiers::NONE)),
205            Nav::All if mode == crate::select::Mode::Multiple => {
206                out.push(selection.all(len, key_at));
207                None
208            }
209            Nav::Text(t) => {
210                let search = type_ahead.push(t, now).to_string();
211                find(&search, cursor, len, label_at).map(|j| (j, Modifiers::NONE))
212            }
213            Nav::Activate => {
214                if let Some(c) = cursor {
215                    activate = Some(key_at(c));
216                }
217                None
218            }
219            _ => None,
220        };
221        if let Some((j, mods)) = to {
222            out.push(selection.move_to(mode, len, key_at, j, mods));
223            reveal = Some(j);
224        }
225    }
226    (out, reveal, activate)
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    #[test]
234    fn movement_keys_stay_in_the_rows() {
235        assert_eq!(target(&Nav::Down, Some(9), 10, 5), Some(9));
236        assert_eq!(target(&Nav::PageDown, Some(2), 10, 5), Some(7));
237        assert_eq!(target(&Nav::PageUp, Some(2), 10, 5), Some(0));
238        assert_eq!(target(&Nav::End, None, 10, 5), Some(9));
239        assert_eq!(target(&Nav::Up, None, 0, 5), None);
240    }
241
242    #[test]
243    fn type_ahead_cycles_on_one_letter_and_narrows_on_more() {
244        let labels = ["Apple", "Banana", "Blueberry", "Cherry", "Bean"];
245        let at = |i: usize| labels[i].to_string();
246        assert_eq!(find("b", Some(0), 5, &at), Some(1));
247        assert_eq!(find("b", Some(1), 5, &at), Some(2));
248        assert_eq!(find("bb", Some(2), 5, &at), Some(4));
249        assert_eq!(find("bl", Some(1), 5, &at), Some(2));
250        assert_eq!(find("z", Some(1), 5, &at), None);
251        let mut t = TypeAhead::default();
252        assert_eq!(t.push("B", 0.0), "b");
253        assert_eq!(t.push("l", 0.5), "bl");
254        assert_eq!(t.push("c", 2.0), "c");
255    }
256
257    #[test]
258    fn reveal_scrolls_the_least() {
259        assert_eq!(reveal(0, 20.0, 100.0, 200.0), 0.0);
260        assert_eq!(reveal(10, 20.0, 0.0, 200.0), 20.0);
261        assert_eq!(reveal(6, 20.0, 0.0, 200.0), 0.0);
262    }
263}