BREP_app 0.36.1

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
//! Buttons: primary, secondary, ghost and danger, in two sizes, with an
//! optional leading icon, trailing shortcut text and a busy state.
use super::{paint, Interact, Show};
use crate::theme::{radius, space, Text, Theme, BORDER};
use eframe::egui::{self, Color32, Stroke, Vec2};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Variant {
    /// Filled accent, white text: OK, Apply, Create. At most one per dialog.
    Primary,
    /// `bg.raised` fill with a `border.strong` outline.
    #[default]
    Secondary,
    /// No fill until hover: toolbars and inline actions.
    Ghost,
    /// Red text on the secondary look.
    Danger,
    /// Red fill: the confirm step of a destructive action.
    DangerFilled,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Size {
    /// The density's control height (24 compact, 28 comfortable).
    #[default]
    Auto,
    /// 24 px.
    Sm,
    /// 28 px.
    Md,
}

/// A button. `ui.add(Button::new("Apply").variant(Variant::Primary))`.
#[must_use = "a button does nothing until it is added to a Ui"]
pub struct Button<'a> {
    text: &'a str,
    variant: Variant,
    size: Size,
    icon: Option<&'a str>,
    shortcut: Option<&'a str>,
    busy: bool,
    enabled: bool,
    min_width: f32,
    max_width: Option<f32>,
    min_height: f32,
    selected: bool,
    show: Show,
}

impl<'a> Button<'a> {
    pub fn new(text: &'a str) -> Self {
        Self { text, variant: Variant::default(), size: Size::default(), icon: None, shortcut: None, busy: false, enabled: true, min_width: 0.0, max_width: None, min_height: 0.0, selected: false, show: Show::Live }
    }
    pub fn primary(text: &'a str) -> Self {
        Self::new(text).variant(Variant::Primary)
    }
    pub fn ghost(text: &'a str) -> Self {
        Self::new(text).variant(Variant::Ghost)
    }
    pub fn danger(text: &'a str) -> Self {
        Self::new(text).variant(Variant::Danger)
    }
    pub fn variant(mut self, variant: Variant) -> Self {
        self.variant = variant;
        self
    }
    pub fn size(mut self, size: Size) -> Self {
        self.size = size;
        self
    }
    /// A leading icon: a glyph of the icon catalog.
    pub fn icon(mut self, glyph: &'a str) -> Self {
        self.icon = Some(glyph);
        self
    }
    /// Trailing shortcut text, in `text.secondary`.
    pub fn shortcut(mut self, shortcut: &'a str) -> Self {
        self.shortcut = Some(shortcut);
        self
    }
    /// Busy: a spinner replaces the icon, the button keeps its width and takes no click.
    pub fn busy(mut self, busy: bool) -> Self {
        self.busy = busy;
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    pub fn min_width(mut self, width: f32) -> Self {
        self.min_width = width;
        self
    }
    /// The button is never wider than this: a label that does not fit is cut
    /// with an ellipsis (a full-width button in a narrow panel).
    pub fn max_width(mut self, width: f32) -> Self {
        self.max_width = Some(width);
        self
    }
    /// The button is at least this tall (a touch-height button); never
    /// under the theme's own height for its size.
    pub fn height(mut self, height: f32) -> Self {
        self.min_height = height;
        self
    }
    /// A toggle or selectable button that is on: a secondary or ghost button
    /// drawn on `accent.muted` with `accent.text`.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }
    /// Draw a fixed state (the gallery).
    pub fn show(mut self, show: Show) -> Self {
        self.show = show;
        self
    }
}

/// Fill, border and text colour of a variant at rest.
pub(crate) fn rest_colors(theme: &Theme, variant: Variant) -> (Color32, Color32, Color32) {
    let c = &theme.colors;
    match variant {
        Variant::Primary => (c.accent_fill, c.accent_fill, c.on_accent),
        Variant::Secondary => (c.bg_raised, c.border_strong, c.text_primary),
        Variant::Ghost => (Color32::TRANSPARENT, Color32::TRANSPARENT, c.text_primary),
        Variant::Danger => (c.bg_raised, c.border_strong, c.danger),
        Variant::DangerFilled => (c.danger_fill, c.danger_fill, c.on_accent),
    }
}

const ICON: f32 = 16.0;

impl egui::Widget for Button<'_> {
    fn ui(mut self, ui: &mut egui::Ui) -> egui::Response {
        // A disabled parent Ui disables the button.
        self.enabled = self.enabled && ui.is_enabled();
        let theme = Theme::of(ui);
        let c = &theme.colors;
        let height = match self.size {
            Size::Auto => theme.control_height(),
            Size::Sm => theme.control_height_sm(),
            Size::Md => 28.0_f32.max(theme.min_target),
        }
        .max(self.min_height);
        let pad = theme.control_padding() + 2.0;
        let mut text = paint::galley(ui, self.text, theme.font(Text::Body));
        let shortcut = self.shortcut.map(|s| paint::galley(ui, s, theme.font(Text::Caption)));
        let lead = if self.icon.is_some() { ICON + space::SM } else { 0.0 };
        let trail = shortcut.as_ref().map_or(0.0, |g| g.size().x + space::LG);
        let mut width = (pad * 2.0 + lead + text.size().x + trail).max(self.min_width).max(height);
        if let Some(max) = self.max_width.filter(|max| width > *max) {
            // Cut the label to what the button may take; never under a square.
            width = max.max(height);
            let room = (width - pad * 2.0 - lead - trail).max(0.0);
            if text.size().x > room {
                let mut job = egui::text::LayoutJob::simple_singleline(self.text.to_owned(), theme.font(Text::Body), Color32::PLACEHOLDER);
                job.wrap = egui::text::TextWrapping::truncate_at_width(room);
                text = ui.painter().layout_job(job);
            }
        }
        let active = self.enabled && !self.busy;
        let sense = if active { egui::Sense::click() } else { egui::Sense::hover() };
        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
        response.widget_info(|| {
            if self.selected {
                egui::WidgetInfo::selected(egui::WidgetType::Button, self.enabled, true, self.text)
            } else {
                egui::WidgetInfo::labeled(egui::WidgetType::Button, self.enabled, self.text)
            }
        });
        if !ui.is_rect_visible(rect) {
            return response;
        }
        let state = Interact::of(&response, self.show, active);
        let hover = ui.ctx().animate_bool_with_time(response.id.with("hover"), state.hovered, theme.motion_fast());
        let press = ui.ctx().animate_bool_with_time(response.id.with("press"), state.pressed, theme.motion_fast());

        let (mut fill, mut border, mut ink) = rest_colors(&theme, self.variant);
        if self.selected && matches!(self.variant, Variant::Secondary | Variant::Ghost) {
            fill = crate::theme::over(c.bg_panel, c.accent_muted);
            border = c.accent_ring;
            ink = c.accent_text;
        }
        if !self.enabled {
            ink = c.text_disabled;
            match self.variant {
                Variant::Ghost => {}
                _ => {
                    fill = crate::theme::over(c.bg_panel, c.hover);
                    border = c.border_subtle;
                }
            }
        } else {
            let overlay = paint::lerp_color(paint::lerp_color(Color32::TRANSPARENT, c.hover, hover), c.pressed, press);
            fill = match self.variant {
                // A ghost has no fill: the overlay sits on the panel.
                Variant::Ghost if !self.selected => overlay,
                // A filled button darkens, so its white text keeps its contrast.
                Variant::Primary | Variant::DangerFilled => {
                    let hovered = paint::lerp_color(fill, crate::theme::Palette::fill_hover(fill), hover);
                    paint::lerp_color(hovered, crate::theme::Palette::fill_pressed(fill), press)
                }
                _ => crate::theme::over(fill, overlay),
            };
            if matches!(self.variant, Variant::Primary | Variant::DangerFilled) {
                border = fill;
            }
        }
        let radius = if height <= 24.0 { radius::INPUT } else { radius::BUTTON };
        ui.painter().rect(rect, radius, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
        if state.focused {
            paint::focus_ring(ui, rect, radius, &theme);
        }

        // Pressed: the content sits 1 px lower.
        let nudge = Vec2::new(0.0, press.round());
        let content = lead + text.size().x + trail;
        let mut x = if shortcut.is_some() { rect.left() + pad } else { rect.center().x - content / 2.0 };
        let cy = rect.center().y;
        let slot = egui::Rect::from_center_size(egui::pos2(x + ICON / 2.0, cy), Vec2::splat(ICON)).translate(nudge);
        if self.busy {
            if self.icon.is_some() {
                paint::spinner(ui, slot.center(), 6.0, ink, &theme);
            } else {
                // No icon slot: the spinner takes the text's place, same width.
                paint::spinner(ui, rect.center() + nudge, 6.0, ink, &theme);
            }
        } else if let Some(glyph) = self.icon {
            paint::icon(ui, glyph, slot, ink);
        }
        x += lead;
        if !(self.busy && self.icon.is_none()) {
            ui.painter().galley(egui::pos2(x, cy - text.size().y / 2.0) + nudge, text, ink);
        }
        if let Some(g) = shortcut {
            let ink = if self.enabled && !matches!(self.variant, Variant::Primary | Variant::DangerFilled) { c.text_secondary } else { ink };
            ui.painter().galley(egui::pos2(rect.right() - pad - g.size().x, cy - g.size().y / 2.0) + nudge, g, ink);
        }
        if active {
            response.on_hover_cursor(egui::CursorIcon::PointingHand)
        } else {
            response
        }
    }
}

/// `ui.add_enabled(enabled, button)` for a [`Button`]: the button draws its
/// disabled look AND egui sees a disabled widget, so `on_disabled_hover_text`
/// still shows and `on_hover_text` stays hidden while it is off, exactly as
/// for the `egui::Button` it replaces.
pub fn add_enabled(ui: &mut egui::Ui, enabled: bool, button: Button<'_>) -> egui::Response {
    ui.add_enabled(enabled, button.enabled(enabled))
}