Skip to main content

brep_app/ui_kit/
dropdown.rs

1//! Dropdowns: the one control for an enumeration. The closed control looks
2//! like an input with a chevron that turns when open; the popup is a raised
3//! card of 28 px rows with an accent check on the current value, caption
4//! headers for groups, and a search field once the list passes twelve items.
5use super::{paint, surface, Show};
6use crate::theme::{radius, space, Text, Theme, BORDER};
7use eframe::egui::{self, Rect, Stroke, Vec2};
8
9/// Lists longer than this get a search field at the top.
10pub const SEARCH_ABOVE: usize = 12;
11
12#[must_use = "a dropdown does nothing until `show` is called"]
13pub struct Dropdown<'a> {
14    id_salt: egui::Id,
15    items: &'a [&'a str],
16    /// `(index of the first item of the group, header)`, ascending.
17    groups: &'a [(usize, &'a str)],
18    width: Option<f32>,
19    enabled: bool,
20    show: Show,
21}
22
23pub struct DropdownOutput {
24    /// The closed control.
25    pub response: egui::Response,
26    pub changed: bool,
27    pub open: bool,
28    /// The rows drawn while open: `(item index, rect)`, for hit keys.
29    pub rows: Vec<(usize, Rect)>,
30}
31
32/// `dropdown("density", &["Compact", "Comfortable"]).show(ui, &mut index)`.
33pub fn dropdown<'a>(id_salt: impl std::hash::Hash + std::fmt::Debug, items: &'a [&'a str]) -> Dropdown<'a> {
34    Dropdown { id_salt: egui::Id::new(id_salt), items, groups: &[], width: None, enabled: true, show: Show::Live }
35}
36
37/// The index of the first item starting with `typed` (case-insensitive):
38/// type-to-jump.
39pub(crate) fn jump_to(items: &[&str], typed: &str) -> Option<usize> {
40    let typed = typed.to_lowercase();
41    (!typed.is_empty()).then(|| items.iter().position(|item| item.to_lowercase().starts_with(&typed))).flatten()
42}
43
44/// The items a search for `query` keeps (case-insensitive substring).
45pub(crate) fn filter(items: &[&str], query: &str) -> Vec<usize> {
46    let query = query.trim().to_lowercase();
47    (0..items.len()).filter(|i| query.is_empty() || items[*i].to_lowercase().contains(&query)).collect()
48}
49
50impl<'a> Dropdown<'a> {
51    pub fn groups(mut self, groups: &'a [(usize, &'a str)]) -> Self {
52        self.groups = groups;
53        self
54    }
55    pub fn width(mut self, width: f32) -> Self {
56        self.width = Some(width);
57        self
58    }
59    pub fn enabled(mut self, enabled: bool) -> Self {
60        self.enabled = enabled;
61        self
62    }
63    pub fn show_state(mut self, show: Show) -> Self {
64        self.show = show;
65        self
66    }
67
68    pub fn show(self, ui: &mut egui::Ui, selected: &mut usize) -> DropdownOutput {
69        let theme = Theme::of(ui);
70        let c = &theme.colors;
71        let id = ui.make_persistent_id(self.id_salt);
72        let height = theme.control_height();
73        let pad = space::MD;
74        let label = self.items.get(*selected).copied().unwrap_or("");
75        let widest = self.items.iter().map(|item| paint::galley(ui, item, theme.font(Text::Body)).size().x).fold(0.0, f32::max);
76        let width = self.width.unwrap_or(widest + pad * 2.0 + 20.0).max(60.0);
77        let sense = if self.enabled { egui::Sense::click() } else { egui::Sense::hover() };
78        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
79        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, self.enabled, label));
80        let popup_id = egui::Popup::default_response_id(&response);
81        let was_open = egui::Popup::is_id_open(ui.ctx(), popup_id);
82        let open_t = ui.ctx().animate_bool_with_time(id.with("open"), was_open, theme.motion_slow());
83        let hovered = self.enabled && (response.hovered() || self.show == Show::Hover);
84        let focused = self.enabled && (response.has_focus() || was_open || self.show == Show::Focus);
85
86        let fill = if !self.enabled {
87            crate::theme::over(c.bg_panel, c.hover)
88        } else if hovered {
89            crate::theme::over(c.bg_input, c.hover)
90        } else {
91            c.bg_input
92        };
93        let border = if !self.enabled {
94            c.border_subtle
95        } else if focused {
96            c.accent_ring
97        } else {
98            c.border_strong
99        };
100        ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
101        if focused {
102            paint::focus_ring(ui, rect, radius::INPUT, &theme);
103        }
104        let ink = if self.enabled { c.text_primary } else { c.text_disabled };
105        let g = paint::galley(ui, label, theme.font(Text::Body));
106        ui.painter().with_clip_rect(rect.shrink2(Vec2::new(pad, 0.0))).galley(egui::pos2(rect.left() + pad, rect.center().y - g.size().y / 2.0), g, ink);
107        paint::chevron(ui.painter(), egui::pos2(rect.right() - pad - 4.0, rect.center().y), 4.0, open_t, Stroke::new(1.5, if self.enabled { c.text_secondary } else { c.text_disabled }));
108
109        let mut out = DropdownOutput { response: response.clone(), changed: false, open: false, rows: Vec::new() };
110        if !self.enabled {
111            return out;
112        }
113        // Keyboard on the closed control: Enter and Space open it (egui turns
114        // them into a click on the focused control), and so does the down arrow.
115        if response.has_focus() && !was_open && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
116            egui::Popup::open_id(ui.ctx(), popup_id);
117        }
118        // While open, Enter picks the row under the cursor: it must not also
119        // count as the click that toggles the popup shut before the pick.
120        let enter_picks = was_open && ui.input(|i| i.key_pressed(egui::Key::Enter));
121        let toggle = (response.clicked() && !enter_picks).then_some(egui::SetOpenCommand::Toggle);
122        let cursor_id = id.with("cursor");
123        let query_id = id.with("query");
124        if !was_open {
125            ui.data_mut(|d| {
126                d.insert_temp(cursor_id, *selected);
127                d.remove::<String>(query_id);
128            });
129        }
130        let searchable = self.items.len() > SEARCH_ABOVE;
131        let items = self.items;
132        let groups = self.groups;
133        let mut pick = None;
134        let popup = egui::Popup::from_response(&response)
135            .open_memory(toggle)
136            .frame(surface::popup_frame(&theme))
137            .width(rect.width().max(widest + pad * 2.0 + 28.0))
138            .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
139            .gap(4.0)
140            .show(|ui| {
141                super::themed(ui, theme.clone(), |ui| {
142                    ui.spacing_mut().item_spacing.y = 0.0;
143                    let mut query = ui.data(|d| d.get_temp::<String>(query_id)).unwrap_or_default();
144                    if searchable {
145                        let search = super::search_input(&mut query).id(query_id.with("field")).width(ui.available_width()).show(ui);
146                        if !was_open {
147                            search.response.request_focus();
148                        }
149                        ui.add_space(space::XS);
150                    }
151                    let shown = filter(items, &query);
152                    let mut cursor = ui.data(|d| d.get_temp::<usize>(cursor_id)).unwrap_or(*selected);
153                    // Arrows move the cursor through the shown rows; typing jumps
154                    // (when there is no search field to take the text).
155                    let at = shown.iter().position(|i| *i == cursor);
156                    let (down, up, enter, typed) = ui.input(|i| {
157                        let typed: String = i.events.iter().filter_map(|e| if let egui::Event::Text(t) = e { Some(t.as_str()) } else { None }).collect();
158                        (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::Enter), typed)
159                    });
160                    let mut moved = false;
161                    if down && !shown.is_empty() {
162                        cursor = shown[at.map_or(0, |a| (a + 1).min(shown.len() - 1))];
163                        moved = true;
164                    }
165                    if up && !shown.is_empty() {
166                        cursor = shown[at.map_or(0, |a| a.saturating_sub(1))];
167                        moved = true;
168                    }
169                    if !searchable {
170                        if let Some(i) = jump_to(items, &typed) {
171                            cursor = i;
172                            moved = true;
173                        }
174                    } else if at.is_none() {
175                        if let Some(first) = shown.first() {
176                            cursor = *first;
177                        }
178                    }
179                    if enter && shown.contains(&cursor) {
180                        pick = Some(cursor);
181                    }
182                    egui::ScrollArea::vertical().max_height(theme.row_height().max(28.0) * 12.5).show(ui, |ui| {
183                        if shown.is_empty() {
184                            ui.label(egui::RichText::new("No matches").font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
185                        }
186                        for i in shown {
187                            if query.trim().is_empty() {
188                                if let Some((_, header)) = groups.iter().find(|(first, _)| *first == i) {
189                                    surface::menu_header(ui, header);
190                                }
191                            }
192                            let row = surface::menu_row_with(ui, items[i], None, i == *selected, i == cursor);
193                            if moved && i == cursor {
194                                row.scroll_to_me(None);
195                            }
196                            if row.clicked() {
197                                pick = Some(i);
198                            }
199                            out.rows.push((i, row.rect));
200                        }
201                    });
202                    ui.data_mut(|d| {
203                        d.insert_temp(cursor_id, cursor);
204                        d.insert_temp(query_id, query);
205                    });
206                });
207            });
208        out.open = popup.is_some();
209        if let Some(i) = pick {
210            if *selected != i {
211                *selected = i;
212                out.changed = true;
213            }
214            egui::Popup::close_id(ui.ctx(), popup_id);
215            response.request_focus();
216        }
217        out
218    }
219}