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    max_width: Option<f32>,
45    min_height: f32,
46    selected: bool,
47    show: Show,
48}
49
50impl<'a> Button<'a> {
51    pub fn new(text: &'a str) -> Self {
52        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 }
53    }
54    pub fn primary(text: &'a str) -> Self {
55        Self::new(text).variant(Variant::Primary)
56    }
57    pub fn ghost(text: &'a str) -> Self {
58        Self::new(text).variant(Variant::Ghost)
59    }
60    pub fn danger(text: &'a str) -> Self {
61        Self::new(text).variant(Variant::Danger)
62    }
63    pub fn variant(mut self, variant: Variant) -> Self {
64        self.variant = variant;
65        self
66    }
67    pub fn size(mut self, size: Size) -> Self {
68        self.size = size;
69        self
70    }
71    /// A leading icon: a glyph of the icon catalog.
72    pub fn icon(mut self, glyph: &'a str) -> Self {
73        self.icon = Some(glyph);
74        self
75    }
76    /// Trailing shortcut text, in `text.secondary`.
77    pub fn shortcut(mut self, shortcut: &'a str) -> Self {
78        self.shortcut = Some(shortcut);
79        self
80    }
81    /// Busy: a spinner replaces the icon, the button keeps its width and takes no click.
82    pub fn busy(mut self, busy: bool) -> Self {
83        self.busy = busy;
84        self
85    }
86    pub fn enabled(mut self, enabled: bool) -> Self {
87        self.enabled = enabled;
88        self
89    }
90    pub fn min_width(mut self, width: f32) -> Self {
91        self.min_width = width;
92        self
93    }
94    /// The button is never wider than this: a label that does not fit is cut
95    /// with an ellipsis (a full-width button in a narrow panel).
96    pub fn max_width(mut self, width: f32) -> Self {
97        self.max_width = Some(width);
98        self
99    }
100    /// The button is at least this tall (a touch-height button); never
101    /// under the theme's own height for its size.
102    pub fn height(mut self, height: f32) -> Self {
103        self.min_height = height;
104        self
105    }
106    /// A toggle or selectable button that is on: a secondary or ghost button
107    /// drawn on `accent.muted` with `accent.text`.
108    pub fn selected(mut self, selected: bool) -> Self {
109        self.selected = selected;
110        self
111    }
112    /// Draw a fixed state (the gallery).
113    pub fn show(mut self, show: Show) -> Self {
114        self.show = show;
115        self
116    }
117}
118
119/// Fill, border and text colour of a variant at rest.
120pub(crate) fn rest_colors(theme: &Theme, variant: Variant) -> (Color32, Color32, Color32) {
121    let c = &theme.colors;
122    match variant {
123        Variant::Primary => (c.accent_fill, c.accent_fill, c.on_accent),
124        Variant::Secondary => (c.bg_raised, c.border_strong, c.text_primary),
125        Variant::Ghost => (Color32::TRANSPARENT, Color32::TRANSPARENT, c.text_primary),
126        Variant::Danger => (c.bg_raised, c.border_strong, c.danger),
127        Variant::DangerFilled => (c.danger_fill, c.danger_fill, c.on_accent),
128    }
129}
130
131const ICON: f32 = 16.0;
132
133impl egui::Widget for Button<'_> {
134    fn ui(mut self, ui: &mut egui::Ui) -> egui::Response {
135        // A disabled parent Ui disables the button.
136        self.enabled = self.enabled && ui.is_enabled();
137        let theme = Theme::of(ui);
138        let c = &theme.colors;
139        let height = match self.size {
140            Size::Auto => theme.control_height(),
141            Size::Sm => theme.control_height_sm(),
142            Size::Md => 28.0_f32.max(theme.min_target),
143        }
144        .max(self.min_height);
145        let pad = theme.control_padding() + 2.0;
146        let mut text = paint::galley(ui, self.text, theme.font(Text::Body));
147        let shortcut = self.shortcut.map(|s| paint::galley(ui, s, theme.font(Text::Caption)));
148        let lead = if self.icon.is_some() { ICON + space::SM } else { 0.0 };
149        let trail = shortcut.as_ref().map_or(0.0, |g| g.size().x + space::LG);
150        let mut width = (pad * 2.0 + lead + text.size().x + trail).max(self.min_width).max(height);
151        if let Some(max) = self.max_width.filter(|max| width > *max) {
152            // Cut the label to what the button may take; never under a square.
153            width = max.max(height);
154            let room = (width - pad * 2.0 - lead - trail).max(0.0);
155            if text.size().x > room {
156                let mut job = egui::text::LayoutJob::simple_singleline(self.text.to_owned(), theme.font(Text::Body), Color32::PLACEHOLDER);
157                job.wrap = egui::text::TextWrapping::truncate_at_width(room);
158                text = ui.painter().layout_job(job);
159            }
160        }
161        let active = self.enabled && !self.busy;
162        let sense = if active { egui::Sense::click() } else { egui::Sense::hover() };
163        let (rect, response) = ui.allocate_exact_size(Vec2::new(width, height), sense);
164        response.widget_info(|| {
165            if self.selected {
166                egui::WidgetInfo::selected(egui::WidgetType::Button, self.enabled, true, self.text)
167            } else {
168                egui::WidgetInfo::labeled(egui::WidgetType::Button, self.enabled, self.text)
169            }
170        });
171        if !ui.is_rect_visible(rect) {
172            return response;
173        }
174        let state = Interact::of(&response, self.show, active);
175        let hover = ui.ctx().animate_bool_with_time(response.id.with("hover"), state.hovered, theme.motion_fast());
176        let press = ui.ctx().animate_bool_with_time(response.id.with("press"), state.pressed, theme.motion_fast());
177
178        let (mut fill, mut border, mut ink) = rest_colors(&theme, self.variant);
179        if self.selected && matches!(self.variant, Variant::Secondary | Variant::Ghost) {
180            fill = crate::theme::over(c.bg_panel, c.accent_muted);
181            border = c.accent_ring;
182            ink = c.accent_text;
183        }
184        if !self.enabled {
185            ink = c.text_disabled;
186            match self.variant {
187                Variant::Ghost => {}
188                _ => {
189                    fill = crate::theme::over(c.bg_panel, c.hover);
190                    border = c.border_subtle;
191                }
192            }
193        } else {
194            let overlay = paint::lerp_color(paint::lerp_color(Color32::TRANSPARENT, c.hover, hover), c.pressed, press);
195            fill = match self.variant {
196                // A ghost has no fill: the overlay sits on the panel.
197                Variant::Ghost if !self.selected => overlay,
198                // A filled button darkens, so its white text keeps its contrast.
199                Variant::Primary | Variant::DangerFilled => {
200                    let hovered = paint::lerp_color(fill, crate::theme::Palette::fill_hover(fill), hover);
201                    paint::lerp_color(hovered, crate::theme::Palette::fill_pressed(fill), press)
202                }
203                _ => crate::theme::over(fill, overlay),
204            };
205            if matches!(self.variant, Variant::Primary | Variant::DangerFilled) {
206                border = fill;
207            }
208        }
209        let radius = if height <= 24.0 { radius::INPUT } else { radius::BUTTON };
210        ui.painter().rect(rect, radius, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
211        if state.focused {
212            paint::focus_ring(ui, rect, radius, &theme);
213        }
214
215        // Pressed: the content sits 1 px lower.
216        let nudge = Vec2::new(0.0, press.round());
217        let content = lead + text.size().x + trail;
218        let mut x = if shortcut.is_some() { rect.left() + pad } else { rect.center().x - content / 2.0 };
219        let cy = rect.center().y;
220        let slot = egui::Rect::from_center_size(egui::pos2(x + ICON / 2.0, cy), Vec2::splat(ICON)).translate(nudge);
221        if self.busy {
222            if self.icon.is_some() {
223                paint::spinner(ui, slot.center(), 6.0, ink, &theme);
224            } else {
225                // No icon slot: the spinner takes the text's place, same width.
226                paint::spinner(ui, rect.center() + nudge, 6.0, ink, &theme);
227            }
228        } else if let Some(glyph) = self.icon {
229            paint::icon(ui, glyph, slot, ink);
230        }
231        x += lead;
232        if !(self.busy && self.icon.is_none()) {
233            ui.painter().galley(egui::pos2(x, cy - text.size().y / 2.0) + nudge, text, ink);
234        }
235        if let Some(g) = shortcut {
236            let ink = if self.enabled && !matches!(self.variant, Variant::Primary | Variant::DangerFilled) { c.text_secondary } else { ink };
237            ui.painter().galley(egui::pos2(rect.right() - pad - g.size().x, cy - g.size().y / 2.0) + nudge, g, ink);
238        }
239        if active {
240            response.on_hover_cursor(egui::CursorIcon::PointingHand)
241        } else {
242            response
243        }
244    }
245}
246
247/// `ui.add_enabled(enabled, button)` for a [`Button`]: the button draws its
248/// disabled look AND egui sees a disabled widget, so `on_disabled_hover_text`
249/// still shows and `on_hover_text` stays hidden while it is off, exactly as
250/// for the `egui::Button` it replaces.
251pub fn add_enabled(ui: &mut egui::Ui, enabled: bool, button: Button<'_>) -> egui::Response {
252    ui.add_enabled(enabled, button.enabled(enabled))
253}