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(mut self, ui: &mut egui::Ui, selected: &mut usize) -> DropdownOutput {
69        self.enabled = self.enabled && ui.is_enabled();
70        let theme = Theme::of(ui);
71        let c = &theme.colors;
72        let id = ui.make_persistent_id(self.id_salt);
73        let height = theme.control_height();
74        let pad = space::MD;
75        let label = self.items.get(*selected).copied().unwrap_or("");
76        let widest = self.items.iter().map(|item| paint::galley(ui, item, theme.font(Text::Body)).size().x).fold(0.0, f32::max);
77        let width = self.width.unwrap_or(widest + pad * 2.0 + 20.0).max(60.0);
78        let sense = if self.enabled { egui::Sense::click() } else { egui::Sense::hover() };
79        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
80        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, self.enabled, label));
81        let popup_id = egui::Popup::default_response_id(&response);
82        let was_open = egui::Popup::is_id_open(ui.ctx(), popup_id);
83        let open_t = ui.ctx().animate_bool_with_time(id.with("open"), was_open, theme.motion_slow());
84        let hovered = self.enabled && (response.hovered() || self.show == Show::Hover);
85        let focused = self.enabled && (response.has_focus() || was_open || self.show == Show::Focus);
86
87        let fill = if !self.enabled {
88            crate::theme::over(c.bg_panel, c.hover)
89        } else if hovered {
90            crate::theme::over(c.bg_input, c.hover)
91        } else {
92            c.bg_input
93        };
94        let border = if !self.enabled {
95            c.border_subtle
96        } else if focused {
97            c.accent_ring
98        } else {
99            c.border_strong
100        };
101        ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
102        if focused {
103            paint::focus_ring(ui, rect, radius::INPUT, &theme);
104        }
105        let ink = if self.enabled { c.text_primary } else { c.text_disabled };
106        let g = paint::galley(ui, label, theme.font(Text::Body));
107        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);
108        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 }));
109
110        let mut out = DropdownOutput { response: response.clone(), changed: false, open: false, rows: Vec::new() };
111        if !self.enabled {
112            return out;
113        }
114        // Keyboard on the closed control: Enter and Space open it (egui turns
115        // them into a click on the focused control), and so does the down arrow.
116        if response.has_focus() && !was_open && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
117            egui::Popup::open_id(ui.ctx(), popup_id);
118        }
119        // While open, Enter picks the row under the cursor: it must not also
120        // count as the click that toggles the popup shut before the pick.
121        let enter_picks = was_open && ui.input(|i| i.key_pressed(egui::Key::Enter));
122        let toggle = (response.clicked() && !enter_picks).then_some(egui::SetOpenCommand::Toggle);
123        let cursor_id = id.with("cursor");
124        let query_id = id.with("query");
125        if !was_open {
126            ui.data_mut(|d| {
127                d.insert_temp(cursor_id, *selected);
128                d.remove::<String>(query_id);
129            });
130        }
131        let searchable = self.items.len() > SEARCH_ABOVE;
132        let items = self.items;
133        let groups = self.groups;
134        let mut pick = None;
135        let popup = egui::Popup::from_response(&response)
136            .open_memory(toggle)
137            .frame(surface::popup_frame(&theme))
138            .width(rect.width().max(widest + pad * 2.0 + 28.0))
139            .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
140            .gap(4.0)
141            .show(|ui| {
142                super::themed(ui, theme.clone(), |ui| {
143                    ui.spacing_mut().item_spacing.y = 0.0;
144                    let mut query = ui.data(|d| d.get_temp::<String>(query_id)).unwrap_or_default();
145                    if searchable {
146                        let search = super::search_input(&mut query).id(query_id.with("field")).width(ui.available_width()).show(ui);
147                        if !was_open {
148                            search.response.request_focus();
149                        }
150                        ui.add_space(space::XS);
151                    }
152                    let shown = filter(items, &query);
153                    let mut cursor = ui.data(|d| d.get_temp::<usize>(cursor_id)).unwrap_or(*selected);
154                    // Arrows move the cursor through the shown rows; typing jumps
155                    // (when there is no search field to take the text).
156                    let at = shown.iter().position(|i| *i == cursor);
157                    let (down, up, enter, typed) = ui.input(|i| {
158                        let typed: String = i.events.iter().filter_map(|e| if let egui::Event::Text(t) = e { Some(t.as_str()) } else { None }).collect();
159                        (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::Enter), typed)
160                    });
161                    let mut moved = false;
162                    if down && !shown.is_empty() {
163                        cursor = shown[at.map_or(0, |a| (a + 1).min(shown.len() - 1))];
164                        moved = true;
165                    }
166                    if up && !shown.is_empty() {
167                        cursor = shown[at.map_or(0, |a| a.saturating_sub(1))];
168                        moved = true;
169                    }
170                    if !searchable {
171                        if let Some(i) = jump_to(items, &typed) {
172                            cursor = i;
173                            moved = true;
174                        }
175                    } else if at.is_none() {
176                        if let Some(first) = shown.first() {
177                            cursor = *first;
178                        }
179                    }
180                    if enter && shown.contains(&cursor) {
181                        pick = Some(cursor);
182                    }
183                    egui::ScrollArea::vertical().max_height(theme.row_height().max(28.0) * 12.5).show(ui, |ui| {
184                        if shown.is_empty() {
185                            ui.label(egui::RichText::new("No matches").font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
186                        }
187                        for i in shown {
188                            if query.trim().is_empty() {
189                                if let Some((_, header)) = groups.iter().find(|(first, _)| *first == i) {
190                                    surface::menu_header(ui, header);
191                                }
192                            }
193                            let row = surface::menu_row_with(ui, items[i], None, i == *selected, i == cursor);
194                            if moved && i == cursor {
195                                row.scroll_to_me(None);
196                            }
197                            if row.clicked() {
198                                pick = Some(i);
199                            }
200                            out.rows.push((i, row.rect));
201                        }
202                    });
203                    ui.data_mut(|d| {
204                        d.insert_temp(cursor_id, cursor);
205                        d.insert_temp(query_id, query);
206                    });
207                });
208            });
209        out.open = popup.is_some();
210        if let Some(i) = pick {
211            if *selected != i {
212                *selected = i;
213                out.changed = true;
214            }
215            egui::Popup::close_id(ui.ctx(), popup_id);
216            response.request_focus();
217        }
218        out
219    }
220}