BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
//! Dropdowns: the one control for an enumeration. The closed control looks
//! like an input with a chevron that turns when open; the popup is a raised
//! card of 28 px rows with an accent check on the current value, caption
//! headers for groups, and a search field once the list passes twelve items.
use super::{paint, surface, Show};
use crate::theme::{radius, space, Text, Theme, BORDER};
use eframe::egui::{self, Rect, Stroke, Vec2};

/// Lists longer than this get a search field at the top.
pub const SEARCH_ABOVE: usize = 12;

#[must_use = "a dropdown does nothing until `show` is called"]
pub struct Dropdown<'a> {
    id_salt: egui::Id,
    items: &'a [&'a str],
    /// `(index of the first item of the group, header)`, ascending.
    groups: &'a [(usize, &'a str)],
    width: Option<f32>,
    enabled: bool,
    show: Show,
}

pub struct DropdownOutput {
    /// The closed control.
    pub response: egui::Response,
    pub changed: bool,
    pub open: bool,
    /// The rows drawn while open: `(item index, rect)`, for hit keys.
    pub rows: Vec<(usize, Rect)>,
}

/// `dropdown("density", &["Compact", "Comfortable"]).show(ui, &mut index)`.
pub fn dropdown<'a>(id_salt: impl std::hash::Hash + std::fmt::Debug, items: &'a [&'a str]) -> Dropdown<'a> {
    Dropdown { id_salt: egui::Id::new(id_salt), items, groups: &[], width: None, enabled: true, show: Show::Live }
}

/// The index of the first item starting with `typed` (case-insensitive):
/// type-to-jump.
pub(crate) fn jump_to(items: &[&str], typed: &str) -> Option<usize> {
    let typed = typed.to_lowercase();
    (!typed.is_empty()).then(|| items.iter().position(|item| item.to_lowercase().starts_with(&typed))).flatten()
}

/// The items a search for `query` keeps (case-insensitive substring).
pub(crate) fn filter(items: &[&str], query: &str) -> Vec<usize> {
    let query = query.trim().to_lowercase();
    (0..items.len()).filter(|i| query.is_empty() || items[*i].to_lowercase().contains(&query)).collect()
}

impl<'a> Dropdown<'a> {
    pub fn groups(mut self, groups: &'a [(usize, &'a str)]) -> Self {
        self.groups = groups;
        self
    }
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    pub fn show_state(mut self, show: Show) -> Self {
        self.show = show;
        self
    }

    pub fn show(self, ui: &mut egui::Ui, selected: &mut usize) -> DropdownOutput {
        let theme = Theme::of(ui);
        let c = &theme.colors;
        let id = ui.make_persistent_id(self.id_salt);
        let height = theme.control_height();
        let pad = space::MD;
        let label = self.items.get(*selected).copied().unwrap_or("");
        let widest = self.items.iter().map(|item| paint::galley(ui, item, theme.font(Text::Body)).size().x).fold(0.0, f32::max);
        let width = self.width.unwrap_or(widest + pad * 2.0 + 20.0).max(60.0);
        let sense = if self.enabled { egui::Sense::click() } else { egui::Sense::hover() };
        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, self.enabled, label));
        let popup_id = egui::Popup::default_response_id(&response);
        let was_open = egui::Popup::is_id_open(ui.ctx(), popup_id);
        let open_t = ui.ctx().animate_bool_with_time(id.with("open"), was_open, theme.motion_slow());
        let hovered = self.enabled && (response.hovered() || self.show == Show::Hover);
        let focused = self.enabled && (response.has_focus() || was_open || self.show == Show::Focus);

        let fill = if !self.enabled {
            crate::theme::over(c.bg_panel, c.hover)
        } else if hovered {
            crate::theme::over(c.bg_input, c.hover)
        } else {
            c.bg_input
        };
        let border = if !self.enabled {
            c.border_subtle
        } else if focused {
            c.accent_ring
        } else {
            c.border_strong
        };
        ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
        if focused {
            paint::focus_ring(ui, rect, radius::INPUT, &theme);
        }
        let ink = if self.enabled { c.text_primary } else { c.text_disabled };
        let g = paint::galley(ui, label, theme.font(Text::Body));
        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);
        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 }));

        let mut out = DropdownOutput { response: response.clone(), changed: false, open: false, rows: Vec::new() };
        if !self.enabled {
            return out;
        }
        // Keyboard on the closed control: Enter and Space open it (egui turns
        // them into a click on the focused control), and so does the down arrow.
        if response.has_focus() && !was_open && ui.input(|i| i.key_pressed(egui::Key::ArrowDown)) {
            egui::Popup::open_id(ui.ctx(), popup_id);
        }
        // While open, Enter picks the row under the cursor: it must not also
        // count as the click that toggles the popup shut before the pick.
        let enter_picks = was_open && ui.input(|i| i.key_pressed(egui::Key::Enter));
        let toggle = (response.clicked() && !enter_picks).then_some(egui::SetOpenCommand::Toggle);
        let cursor_id = id.with("cursor");
        let query_id = id.with("query");
        if !was_open {
            ui.data_mut(|d| {
                d.insert_temp(cursor_id, *selected);
                d.remove::<String>(query_id);
            });
        }
        let searchable = self.items.len() > SEARCH_ABOVE;
        let items = self.items;
        let groups = self.groups;
        let mut pick = None;
        let popup = egui::Popup::from_response(&response)
            .open_memory(toggle)
            .frame(surface::popup_frame(&theme))
            .width(rect.width().max(widest + pad * 2.0 + 28.0))
            .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
            .gap(4.0)
            .show(|ui| {
                super::themed(ui, theme.clone(), |ui| {
                    ui.spacing_mut().item_spacing.y = 0.0;
                    let mut query = ui.data(|d| d.get_temp::<String>(query_id)).unwrap_or_default();
                    if searchable {
                        let search = super::search_input(&mut query).id(query_id.with("field")).width(ui.available_width()).show(ui);
                        if !was_open {
                            search.response.request_focus();
                        }
                        ui.add_space(space::XS);
                    }
                    let shown = filter(items, &query);
                    let mut cursor = ui.data(|d| d.get_temp::<usize>(cursor_id)).unwrap_or(*selected);
                    // Arrows move the cursor through the shown rows; typing jumps
                    // (when there is no search field to take the text).
                    let at = shown.iter().position(|i| *i == cursor);
                    let (down, up, enter, typed) = ui.input(|i| {
                        let typed: String = i.events.iter().filter_map(|e| if let egui::Event::Text(t) = e { Some(t.as_str()) } else { None }).collect();
                        (i.key_pressed(egui::Key::ArrowDown), i.key_pressed(egui::Key::ArrowUp), i.key_pressed(egui::Key::Enter), typed)
                    });
                    let mut moved = false;
                    if down && !shown.is_empty() {
                        cursor = shown[at.map_or(0, |a| (a + 1).min(shown.len() - 1))];
                        moved = true;
                    }
                    if up && !shown.is_empty() {
                        cursor = shown[at.map_or(0, |a| a.saturating_sub(1))];
                        moved = true;
                    }
                    if !searchable {
                        if let Some(i) = jump_to(items, &typed) {
                            cursor = i;
                            moved = true;
                        }
                    } else if at.is_none() {
                        if let Some(first) = shown.first() {
                            cursor = *first;
                        }
                    }
                    if enter && shown.contains(&cursor) {
                        pick = Some(cursor);
                    }
                    egui::ScrollArea::vertical().max_height(theme.row_height().max(28.0) * 12.5).show(ui, |ui| {
                        if shown.is_empty() {
                            ui.label(egui::RichText::new("No matches").font(theme.font(Text::Caption)).color(theme.colors.text_secondary));
                        }
                        for i in shown {
                            if query.trim().is_empty() {
                                if let Some((_, header)) = groups.iter().find(|(first, _)| *first == i) {
                                    surface::menu_header(ui, header);
                                }
                            }
                            let row = surface::menu_row_with(ui, items[i], None, i == *selected, i == cursor);
                            if moved && i == cursor {
                                row.scroll_to_me(None);
                            }
                            if row.clicked() {
                                pick = Some(i);
                            }
                            out.rows.push((i, row.rect));
                        }
                    });
                    ui.data_mut(|d| {
                        d.insert_temp(cursor_id, cursor);
                        d.insert_temp(query_id, query);
                    });
                });
            });
        out.open = popup.is_some();
        if let Some(i) = pick {
            if *selected != i {
                *selected = i;
                out.changed = true;
            }
            egui::Popup::close_id(ui.ctx(), popup_id);
            response.request_focus();
        }
        out
    }
}