egui-elegance 0.13.0

Elegant, opinionated widgets for egui: buttons, inputs, selects, cards, tabs and more. Paired dark/light themes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Top-of-window menu bar — a horizontal strip of click-to-open menus.
//!
//! [`MenuBar`] paints a desktop-style menu strip with an optional brand on
//! the left, a row of menu triggers (File, Edit, View, …), and an optional
//! status slot on the right. Clicking a trigger opens its dropdown; once
//! one menu is open, hovering a sibling trigger switches to it. That
//! "menu mode" hover-switching matches how native menubars feel.
//!
//! ```no_run
//! # use elegance::{MenuBar, MenuItem};
//! # egui::__run_test_ui(|ui| {
//! MenuBar::new("app_menubar")
//!     .brand("Elegance")
//!     .status("main \u{00b7} up to date")
//!     .show(ui, |bar| {
//!         bar.menu("File", |ui| {
//!             ui.add(MenuItem::new("New").shortcut("\u{2318}N"));
//!             ui.add(MenuItem::new("Open\u{2026}").shortcut("\u{2318}O"));
//!             ui.separator();
//!             ui.add(MenuItem::new("Save").shortcut("\u{2318}S"));
//!         });
//!         bar.menu("Edit", |ui| {
//!             ui.add(MenuItem::new("Undo").shortcut("\u{2318}Z"));
//!         });
//!     });
//! # });
//! ```
//!
//! By default the brand renders as a sky-blue square followed by the label.
//! Use [`MenuBar::brand_logo`] to swap the square for a different accent
//! colour, a unicode glyph, an image, or to omit the logo slot entirely:
//!
//! ```no_run
//! # use elegance::{Accent, BrandLogo, MenuBar};
//! # egui::__run_test_ui(|ui| {
//! MenuBar::new("app_menubar")
//!     .brand("Elegance")
//!     .brand_logo(BrandLogo::Glyph("\u{25C6}".into()))
//!     .show(ui, |_bar| {});
//! # });
//! ```
//!
//! Dropdowns close on outside-click, `Esc`, or clicking an item.
//!
//! For a single click-to-open menu attached to an arbitrary trigger button,
//! use [`Menu`](crate::Menu) directly.

use std::hash::Hash;

use egui::{
    Align, Color32, CornerRadius, Frame, Id, ImageSource, Layout, Margin, Popup,
    PopupCloseBehavior, Pos2, Rect, Sense, SetOpenCommand, Stroke, Ui, Vec2, WidgetInfo,
    WidgetText, WidgetType, emath::RectAlign,
};

use crate::theme::{Accent, Theme, mix, with_alpha};

const STRIP_PAD_Y: f32 = 4.0;
const STRIP_PAD_X: f32 = 6.0;
const TRIGGER_PAD_X: f32 = 10.0;
const TRIGGER_PAD_Y: f32 = 5.0;
const BRAND_LOGO_SIZE: f32 = 14.0;

#[derive(Debug, Clone)]
struct StatusContent {
    text: WidgetText,
    dot: Option<Color32>,
}

/// What to paint in the brand's logo slot, left of the brand label.
///
/// The default ([`BrandLogo::Square`] with [`Accent::Sky`]) is used when a
/// [`MenuBar`] sets brand text without an explicit logo. Use
/// [`MenuBar::brand_logo`] to override it.
///
/// The slot is opinionated: it is a fixed size and paints glyphs in the
/// theme's body text colour. Pick the variant that matches the kind of
/// logo you have, and use [`BrandLogo::Image`] when you need full control
/// over colour and detail.
#[derive(Debug, Clone)]
pub enum BrandLogo {
    /// Omit the logo slot entirely. Use this to suppress the default
    /// square next to a brand label, giving a text-only brand that sits
    /// flush against the strip's left padding.
    None,
    /// Filled square in the given accent colour. The library default
    /// (with [`Accent::Sky`]).
    Square(Accent),
    /// A unicode glyph, e.g. a character from an icon font like Material
    /// Icons or Phosphor. Painted in the theme's body text colour at the
    /// fixed logo size; styling beyond the glyph text itself is not
    /// honoured. For a coloured or detailed mark, use [`BrandLogo::Image`].
    Glyph(String),
    /// A bitmap or SVG image, scaled to the logo size.
    ///
    /// The host app must have registered egui image loaders (e.g. via
    /// `egui_extras::install_image_loaders`) for this to render; without
    /// loaders, egui paints its placeholder.
    ///
    /// The `'static` bound suits the two common cases: a compiled-in
    /// asset from [`egui::include_image!`], or an owned URI string via
    /// `ImageSource::Uri(Cow::Owned(...))`. Borrowed URIs need to be
    /// promoted to owned (or interned) by the caller.
    Image(ImageSource<'static>),
}

impl Default for BrandLogo {
    fn default() -> Self {
        Self::Square(Accent::Sky)
    }
}

#[derive(Debug, Clone)]
struct Brand {
    text: Option<WidgetText>,
    /// `None` means "use the default logo if `text` is set, otherwise omit".
    logo: Option<BrandLogo>,
}

/// A horizontal desktop-style menu bar with click-to-open dropdowns.
///
/// See the module-level docs for an example.
#[derive(Debug, Clone)]
#[must_use = "Call `.show(ui, |bar| ...)` to render the menu bar."]
pub struct MenuBar {
    id_salt: Id,
    brand: Option<Brand>,
    status: Option<StatusContent>,
}

impl MenuBar {
    /// Create a new menu bar keyed by `id_salt`. The salt scopes per-menu
    /// open state in egui memory and must be stable across frames.
    pub fn new(id_salt: impl Hash) -> Self {
        Self {
            id_salt: Id::new(("elegance::menu_bar", Id::new(id_salt))),
            brand: None,
            status: None,
        }
    }

    /// Show a brand label on the left. By default it is preceded by a small
    /// sky-blue accent square; call [`MenuBar::brand_logo`] to override that
    /// visual.
    ///
    /// Use this for the application name.
    #[inline]
    pub fn brand(mut self, text: impl Into<WidgetText>) -> Self {
        let logo = self.brand.and_then(|b| b.logo);
        self.brand = Some(Brand {
            text: Some(text.into()),
            logo,
        });
        self
    }

    /// Override the brand's logo slot. Pass [`BrandLogo::Square`] with a
    /// different [`Accent`] to recolour the default square,
    /// [`BrandLogo::Glyph`] for a unicode/icon-font glyph, [`BrandLogo::Image`]
    /// for a bitmap or SVG, or [`BrandLogo::None`] for a text-only brand.
    ///
    /// Calling this without [`MenuBar::brand`] renders the logo on its own
    /// (no brand label).
    #[inline]
    pub fn brand_logo(mut self, logo: BrandLogo) -> Self {
        let text = self.brand.and_then(|b| b.text);
        self.brand = Some(Brand {
            text,
            logo: Some(logo),
        });
        self
    }

    /// Show a muted status line on the right (e.g. `"main · up to date"`).
    #[inline]
    pub fn status(mut self, text: impl Into<WidgetText>) -> Self {
        self.status = Some(StatusContent {
            text: text.into(),
            dot: None,
        });
        self
    }

    /// Show a status line preceded by a coloured dot, useful for indicating
    /// connection or run state (green for healthy, amber for running, red
    /// for failing).
    #[inline]
    pub fn status_with_dot(mut self, text: impl Into<WidgetText>, dot: Color32) -> Self {
        self.status = Some(StatusContent {
            text: text.into(),
            dot: Some(dot),
        });
        self
    }

    /// Render the menu bar. The closure receives a [`MenuBarUi`] used to
    /// declare each menu's trigger label and dropdown body.
    pub fn show<R>(self, ui: &mut Ui, body: impl FnOnce(&mut MenuBarUi<'_>) -> R) -> R {
        let theme = Theme::current(ui.ctx());
        let p = &theme.palette;

        // The strip sits between the page background and the elevated card
        // tone — close to body bg on dark themes, close to card on light
        // themes. Mixing keeps the same visual relationship across all four
        // built-in palettes.
        let menubar_fill = mix(p.bg, p.card, 0.45);

        // Read the previous frame's snapshot: which menus existed, where
        // their triggers were, and whether any was open.
        let state_id = self.id_salt.with("__state");
        let prev_state: MenuBarFrameState = ui
            .ctx()
            .data(|d| d.get_temp::<MenuBarFrameState>(state_id))
            .unwrap_or_default();

        // Hover arbitrator. If a sibling trigger is being hovered while
        // another menu of ours is currently open, close that other menu
        // *before* any popup renders this frame. The new menu's normal
        // hover-switch logic then opens itself in its own paint, and only
        // one popup ends up visible. Without this step, the previously
        // open menu would render its area for one extra frame because its
        // `Popup::show` runs (and renders) before the new menu's call to
        // `open_id` overwrites the memory slot.
        if prev_state.any_open
            && let Some(pointer) = ui.ctx().pointer_hover_pos()
        {
            let open_idx = prev_state
                .triggers
                .iter()
                .position(|(id, _)| Popup::is_id_open(ui.ctx(), *id));
            if let Some(open_idx) = open_idx {
                let on_sibling = prev_state
                    .triggers
                    .iter()
                    .enumerate()
                    .any(|(i, (_, rect))| i != open_idx && rect.contains(pointer));
                if on_sibling {
                    Popup::close_id(ui.ctx(), prev_state.triggers[open_idx].0);
                }
            }
        }

        let frame = Frame::new()
            .fill(menubar_fill)
            .inner_margin(Margin::symmetric(STRIP_PAD_X as i8, STRIP_PAD_Y as i8));

        let outer = frame.show(ui, |ui| {
            ui.horizontal(|ui| {
                ui.spacing_mut().item_spacing.x = 0.0;
                ui.set_min_height(theme.typography.body + TRIGGER_PAD_Y * 2.0);

                if let Some(brand) = self.brand.as_ref() {
                    paint_brand(ui, &theme, brand);
                }

                let mut bar = MenuBarUi {
                    ui,
                    base_id: self.id_salt,
                    next_idx: 0,
                    any_open_prev: prev_state.any_open,
                    any_open_now: false,
                    triggers: Vec::with_capacity(prev_state.triggers.len()),
                };
                let r = body(&mut bar);
                let any_open_now = bar.any_open_now;
                let triggers = std::mem::take(&mut bar.triggers);

                if let Some(status) = self.status.as_ref() {
                    bar.ui
                        .with_layout(Layout::right_to_left(Align::Center), |ui| {
                            paint_status(ui, &theme, status);
                        });
                }

                bar.ui.ctx().data_mut(|d| {
                    d.insert_temp(
                        state_id,
                        MenuBarFrameState {
                            triggers,
                            any_open: any_open_now,
                        },
                    )
                });

                r
            })
            .inner
        });

        // Bottom border separates the strip from the body content below.
        let strip_rect = outer.response.rect;
        ui.painter().line_segment(
            [
                Pos2::new(strip_rect.min.x, strip_rect.max.y - 0.5),
                Pos2::new(strip_rect.max.x, strip_rect.max.y - 0.5),
            ],
            Stroke::new(1.0, p.border),
        );

        outer.inner
    }
}

/// Per-frame state stored in [`egui::Memory`] so the next frame can know
/// where each trigger sat and whether any of our menus was open.
#[derive(Clone, Default, Debug)]
struct MenuBarFrameState {
    triggers: Vec<(Id, Rect)>,
    any_open: bool,
}

/// The handle passed to a [`MenuBar::show`] closure for declaring menu
/// triggers. Each call to [`MenuBarUi::menu`] paints one trigger and its
/// dropdown.
pub struct MenuBarUi<'u> {
    ui: &'u mut Ui,
    base_id: Id,
    next_idx: usize,
    any_open_prev: bool,
    any_open_now: bool,
    triggers: Vec<(Id, Rect)>,
}

impl<'u> std::fmt::Debug for MenuBarUi<'u> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MenuBarUi")
            .field("base_id", &self.base_id)
            .field("next_idx", &self.next_idx)
            .field("any_open_prev", &self.any_open_prev)
            .field("any_open_now", &self.any_open_now)
            .finish()
    }
}

impl<'u> MenuBarUi<'u> {
    /// Paint a single menu trigger with `label` and attach a dropdown
    /// populated by `body`. Clicking an item inside the dropdown dismisses
    /// the menu — the standard pattern for action-style menus (File / Edit
    /// / etc.). For settings-style menus that should stay open while the
    /// user toggles items, use [`MenuBarUi::menu_keep_open`].
    ///
    /// Returns `Some` with the body closure's return value while the
    /// dropdown is open, `None` while it's closed.
    pub fn menu<R>(
        &mut self,
        label: impl Into<WidgetText>,
        body: impl FnOnce(&mut Ui) -> R,
    ) -> Option<R> {
        self.menu_inner(label, PopupCloseBehavior::CloseOnClick, body)
    }

    /// Like [`MenuBarUi::menu`], but the dropdown stays open while the
    /// user clicks items inside it. Useful for menus full of toggles
    /// (checkboxes, radio groups) where the user expects to see the state
    /// change without the menu vanishing. The menu still closes on click
    /// outside, on `Esc`, or when the user clicks the trigger again.
    pub fn menu_keep_open<R>(
        &mut self,
        label: impl Into<WidgetText>,
        body: impl FnOnce(&mut Ui) -> R,
    ) -> Option<R> {
        self.menu_inner(label, PopupCloseBehavior::CloseOnClickOutside, body)
    }

    fn menu_inner<R>(
        &mut self,
        label: impl Into<WidgetText>,
        close_behavior: PopupCloseBehavior,
        body: impl FnOnce(&mut Ui) -> R,
    ) -> Option<R> {
        let label: WidgetText = label.into();
        let theme = Theme::current(self.ui.ctx());
        let p = &theme.palette;
        let t = &theme.typography;

        let idx = self.next_idx;
        self.next_idx += 1;
        let popup_id = self.base_id.with("__menu").with(idx);

        let galley =
            crate::theme::placeholder_galley(self.ui, label.text(), t.body, false, f32::INFINITY);
        let trigger_size = Vec2::new(
            galley.size().x + TRIGGER_PAD_X * 2.0,
            galley.size().y + TRIGGER_PAD_Y * 2.0,
        );
        let (rect, response) = self.ui.allocate_exact_size(trigger_size, Sense::click());
        self.triggers.push((popup_id, rect));

        let was_open = Popup::is_id_open(self.ui.ctx(), popup_id);
        let hovered = response.hovered();
        let clicked = response.clicked();

        // Decide what to do this frame.
        //   1. Click: toggle this menu open/closed.
        //   2. Hover while another menu of ours is already open: switch
        //      to this one. `Bool(true)` opens this id and closes others
        //      (egui memory only tracks one open popup at a time).
        //   3. Otherwise: leave the state as-is.
        let intent: Option<SetOpenCommand> = if clicked {
            Some(SetOpenCommand::Bool(!was_open))
        } else if self.any_open_prev && hovered && !was_open {
            Some(SetOpenCommand::Bool(true))
        } else {
            None
        };

        let will_be_open = matches!(intent, Some(SetOpenCommand::Bool(true)))
            || (was_open && !matches!(intent, Some(SetOpenCommand::Bool(false))));
        self.any_open_now |= will_be_open;

        if self.ui.is_rect_visible(rect) {
            let bg = if will_be_open {
                p.card
            } else if hovered {
                with_alpha(p.text, 14)
            } else {
                Color32::TRANSPARENT
            };
            if bg.a() > 0 {
                self.ui.painter().rect_filled(rect, CornerRadius::ZERO, bg);
            }
            let text_color = if will_be_open || hovered {
                p.text
            } else {
                p.text_muted
            };
            let pos = Pos2::new(
                rect.min.x + TRIGGER_PAD_X,
                rect.center().y - galley.size().y * 0.5,
            );
            self.ui.painter().galley(pos, galley, text_color);
        }

        // Dropdown panel. Top-left corner is square so the panel reads
        // visually flush with the trigger above it.
        let r = theme.card_radius as u8;
        let frame = Frame::new()
            .fill(p.card)
            .stroke(Stroke::new(1.0, p.border))
            .corner_radius(CornerRadius {
                nw: 0,
                ne: r,
                sw: r,
                se: r,
            })
            .inner_margin(Margin::same(4));

        let label_text = label.text().to_string();
        response.widget_info(|| WidgetInfo::labeled(WidgetType::Button, true, &label_text));

        let result = Popup::menu(&response)
            .id(popup_id)
            .open_memory(intent)
            .align(RectAlign::BOTTOM_START)
            .gap(0.0)
            .frame(frame)
            .close_behavior(close_behavior)
            .show(|ui| {
                ui.spacing_mut().item_spacing.y = 2.0;
                body(ui)
            });

        result.map(|r| r.inner)
    }
}

fn paint_brand(ui: &mut Ui, theme: &Theme, brand: &Brand) {
    let p = &theme.palette;
    let t = &theme.typography;

    // Resolve the effective logo: an explicit override wins; otherwise the
    // library default applies when there is brand text to sit next to.
    // `Brand` is constructed only via `MenuBar::brand` or
    // `MenuBar::brand_logo`, each of which sets at least one of the two
    // fields — so the (None, None) state is unreachable.
    let effective_logo = match (&brand.logo, &brand.text) {
        (Some(logo), _) => logo.clone(),
        (None, Some(_)) => BrandLogo::default(),
        (None, None) => unreachable!("Brand requires at least one of text or logo"),
    };

    let logo_painted = paint_brand_logo(ui, theme, &effective_logo);

    if logo_painted && brand.text.is_some() {
        ui.add_space(8.0);
    }

    if let Some(text) = brand.text.as_ref() {
        let galley = crate::theme::placeholder_galley(ui, text.text(), t.body, true, f32::INFINITY);
        let label_size = Vec2::new(galley.size().x, galley.size().y + 4.0);
        let (rect, _) = ui.allocate_exact_size(label_size, Sense::hover());
        let pos = Pos2::new(rect.min.x, rect.center().y - galley.size().y * 0.5);
        ui.painter().galley(pos, galley, p.text);
    }

    if logo_painted || brand.text.is_some() {
        ui.add_space(14.0);
    }
}

/// Paint the logo slot. Returns `true` if anything occupied the slot, so
/// the caller knows whether to insert the gap before the brand label.
fn paint_brand_logo(ui: &mut Ui, theme: &Theme, logo: &BrandLogo) -> bool {
    let p = &theme.palette;
    let size = Vec2::splat(BRAND_LOGO_SIZE);

    match logo {
        BrandLogo::None => false,
        BrandLogo::Square(accent) => {
            let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
            ui.painter()
                .rect_filled(rect, CornerRadius::same(3), p.accent_fill(*accent));
            true
        }
        BrandLogo::Glyph(glyph) => {
            let galley =
                crate::theme::placeholder_galley(ui, glyph, BRAND_LOGO_SIZE, true, f32::INFINITY);
            // Allocate enough room for the actual glyph metrics — line
            // height at a 14pt body font typically exceeds BRAND_LOGO_SIZE,
            // so an undersized slot would lie to the surrounding layout.
            let slot = Vec2::new(
                galley.size().x.max(BRAND_LOGO_SIZE),
                galley.size().y.max(BRAND_LOGO_SIZE),
            );
            let (rect, _) = ui.allocate_exact_size(slot, Sense::hover());
            let pos = Pos2::new(
                rect.center().x - galley.size().x * 0.5,
                rect.center().y - galley.size().y * 0.5,
            );
            ui.painter().galley(pos, galley, p.text);
            true
        }
        BrandLogo::Image(src) => {
            let (rect, _) = ui.allocate_exact_size(size, Sense::hover());
            egui::Image::new(src.clone())
                .fit_to_exact_size(size)
                .paint_at(ui, rect);
            true
        }
    }
}

fn paint_status(ui: &mut Ui, theme: &Theme, status: &StatusContent) {
    let p = &theme.palette;
    let t = &theme.typography;

    // Layout is right-to-left here, so allocations come from the right edge
    // inward — paint text first, then the dot to the left of it.
    ui.add_space(4.0);
    let galley =
        crate::theme::placeholder_galley(ui, status.text.text(), t.small, false, f32::INFINITY);
    let label_size = Vec2::new(galley.size().x, galley.size().y + 4.0);
    let (rect, _) = ui.allocate_exact_size(label_size, Sense::hover());
    let pos = Pos2::new(rect.min.x, rect.center().y - galley.size().y * 0.5);
    ui.painter().galley(pos, galley, p.text_faint);

    if let Some(color) = status.dot {
        ui.add_space(6.0);
        let (dot_rect, _) = ui.allocate_exact_size(Vec2::splat(7.0), Sense::hover());
        ui.painter().circle_filled(dot_rect.center(), 3.5, color);
    }
}