Skip to main content

brep_app/ui_kit/
button.rs

1//! Buttons: primary, secondary, ghost and danger, in two sizes, with an
2//! optional leading icon, trailing shortcut text and a busy state.
3use super::{paint, Interact, Show};
4use crate::theme::{radius, space, Text, Theme, BORDER};
5use eframe::egui::{self, Color32, Stroke, Vec2};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
8pub enum Variant {
9    /// Filled accent, white text: OK, Apply, Create. At most one per dialog.
10    Primary,
11    /// `bg.raised` fill with a `border.strong` outline.
12    #[default]
13    Secondary,
14    /// No fill until hover: toolbars and inline actions.
15    Ghost,
16    /// Red text on the secondary look.
17    Danger,
18    /// Red fill: the confirm step of a destructive action.
19    DangerFilled,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum Size {
24    /// The density's control height (24 compact, 28 comfortable).
25    #[default]
26    Auto,
27    /// 24 px.
28    Sm,
29    /// 28 px.
30    Md,
31}
32
33/// A button. `ui.add(Button::new("Apply").variant(Variant::Primary))`.
34#[must_use = "a button does nothing until it is added to a Ui"]
35pub struct Button<'a> {
36    text: &'a str,
37    variant: Variant,
38    size: Size,
39    icon: Option<&'a str>,
40    shortcut: Option<&'a str>,
41    busy: bool,
42    enabled: bool,
43    min_width: f32,
44    show: Show,
45}
46
47impl<'a> Button<'a> {
48    pub fn new(text: &'a str) -> Self {
49        Self { text, variant: Variant::default(), size: Size::default(), icon: None, shortcut: None, busy: false, enabled: true, min_width: 0.0, show: Show::Live }
50    }
51    pub fn primary(text: &'a str) -> Self {
52        Self::new(text).variant(Variant::Primary)
53    }
54    pub fn ghost(text: &'a str) -> Self {
55        Self::new(text).variant(Variant::Ghost)
56    }
57    pub fn danger(text: &'a str) -> Self {
58        Self::new(text).variant(Variant::Danger)
59    }
60    pub fn variant(mut self, variant: Variant) -> Self {
61        self.variant = variant;
62        self
63    }
64    pub fn size(mut self, size: Size) -> Self {
65        self.size = size;
66        self
67    }
68    /// A leading icon: a glyph of the icon catalog.
69    pub fn icon(mut self, glyph: &'a str) -> Self {
70        self.icon = Some(glyph);
71        self
72    }
73    /// Trailing shortcut text, in `text.secondary`.
74    pub fn shortcut(mut self, shortcut: &'a str) -> Self {
75        self.shortcut = Some(shortcut);
76        self
77    }
78    /// Busy: a spinner replaces the icon, the button keeps its width and takes no click.
79    pub fn busy(mut self, busy: bool) -> Self {
80        self.busy = busy;
81        self
82    }
83    pub fn enabled(mut self, enabled: bool) -> Self {
84        self.enabled = enabled;
85        self
86    }
87    pub fn min_width(mut self, width: f32) -> Self {
88        self.min_width = width;
89        self
90    }
91    /// Draw a fixed state (the gallery).
92    pub fn show(mut self, show: Show) -> Self {
93        self.show = show;
94        self
95    }
96}
97
98/// Fill, border and text colour of a variant at rest.
99pub(crate) fn rest_colors(theme: &Theme, variant: Variant) -> (Color32, Color32, Color32) {
100    let c = &theme.colors;
101    match variant {
102        Variant::Primary => (c.accent_fill, c.accent_fill, c.on_accent),
103        Variant::Secondary => (c.bg_raised, c.border_strong, c.text_primary),
104        Variant::Ghost => (Color32::TRANSPARENT, Color32::TRANSPARENT, c.text_primary),
105        Variant::Danger => (c.bg_raised, c.border_strong, c.danger),
106        Variant::DangerFilled => (c.danger_fill, c.danger_fill, c.on_accent),
107    }
108}
109
110const ICON: f32 = 16.0;
111
112impl egui::Widget for Button<'_> {
113    fn ui(self, ui: &mut egui::Ui) -> egui::Response {
114        let theme = Theme::of(ui);
115        let c = &theme.colors;
116        let height = match self.size {
117            Size::Auto => theme.control_height(),
118            Size::Sm => theme.control_height_sm(),
119            Size::Md => 28.0,
120        };
121        let pad = theme.control_padding() + 2.0;
122        let text = paint::galley(ui, self.text, theme.font(Text::Body));
123        let shortcut = self.shortcut.map(|s| paint::galley(ui, s, theme.font(Text::Caption)));
124        let lead = if self.icon.is_some() { ICON + space::SM } else { 0.0 };
125        let trail = shortcut.as_ref().map_or(0.0, |g| g.size().x + space::LG);
126        let width = (pad * 2.0 + lead + text.size().x + trail).max(self.min_width).max(height);
127        let active = self.enabled && !self.busy;
128        let sense = if active { egui::Sense::click() } else { egui::Sense::hover() };
129        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
130        response.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, self.enabled, self.text));
131        if !ui.is_rect_visible(rect) {
132            return response;
133        }
134        let state = Interact::of(&response, self.show, active);
135        let hover = ui.ctx().animate_bool_with_time(response.id.with("hover"), state.hovered, theme.motion_fast());
136        let press = ui.ctx().animate_bool_with_time(response.id.with("press"), state.pressed, theme.motion_fast());
137
138        let (mut fill, mut border, mut ink) = rest_colors(&theme, self.variant);
139        if !self.enabled {
140            ink = c.text_disabled;
141            match self.variant {
142                Variant::Ghost => {}
143                _ => {
144                    fill = crate::theme::over(c.bg_panel, c.hover);
145                    border = c.border_subtle;
146                }
147            }
148        } else {
149            let overlay = paint::lerp_color(paint::lerp_color(Color32::TRANSPARENT, c.hover, hover), c.pressed, press);
150            fill = match self.variant {
151                // A ghost has no fill: the overlay sits on the panel.
152                Variant::Ghost => overlay,
153                // A filled button darkens, so its white text keeps its contrast.
154                Variant::Primary | Variant::DangerFilled => {
155                    let hovered = paint::lerp_color(fill, crate::theme::Palette::fill_hover(fill), hover);
156                    paint::lerp_color(hovered, crate::theme::Palette::fill_pressed(fill), press)
157                }
158                _ => crate::theme::over(fill, overlay),
159            };
160            if matches!(self.variant, Variant::Primary | Variant::DangerFilled) {
161                border = fill;
162            }
163        }
164        let radius = if height <= 24.0 { radius::INPUT } else { radius::BUTTON };
165        ui.painter().rect(rect, radius, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
166        if state.focused {
167            paint::focus_ring(ui, rect, radius, &theme);
168        }
169
170        // Pressed: the content sits 1 px lower.
171        let nudge = Vec2::new(0.0, press.round());
172        let content = lead + text.size().x + trail;
173        let mut x = if shortcut.is_some() { rect.left() + pad } else { rect.center().x - content / 2.0 };
174        let cy = rect.center().y;
175        let slot = egui::Rect::from_center_size(egui::pos2(x + ICON / 2.0, cy), Vec2::splat(ICON)).translate(nudge);
176        if self.busy {
177            if self.icon.is_some() {
178                paint::spinner(ui, slot.center(), 6.0, ink, &theme);
179            } else {
180                // No icon slot: the spinner takes the text's place, same width.
181                paint::spinner(ui, rect.center() + nudge, 6.0, ink, &theme);
182            }
183        } else if let Some(glyph) = self.icon {
184            paint::icon(ui, glyph, slot, ink);
185        }
186        x += lead;
187        if !(self.busy && self.icon.is_none()) {
188            ui.painter().galley(egui::pos2(x, cy - text.size().y / 2.0) + nudge, text, ink);
189        }
190        if let Some(g) = shortcut {
191            let ink = if self.enabled && !matches!(self.variant, Variant::Primary | Variant::DangerFilled) { c.text_secondary } else { ink };
192            ui.painter().galley(egui::pos2(rect.right() - pad - g.size().x, cy - g.size().y / 2.0) + nudge, g, ink);
193        }
194        if active {
195            response.on_hover_cursor(egui::CursorIcon::PointingHand)
196        } else {
197            response
198        }
199    }
200}