zeus-widgets 0.4.3

A collection of widgets for egui
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
//! Modal dialog — a centered themed card over a dimmed backdrop.
//!
//! Painted in two layers: a full-viewport dimmed backdrop that swallows
//! clicks (and closes the modal when clicked), and a centered [`Card`]-
//! like window with an optional heading row and a close "×" button.
//! Press `Esc` to dismiss.
//!
//! Forked from https://github.com/stephenberry/egui-elegance

use egui::{
   Align, Align2, Area, Color32, Context, CornerRadius, FontId, Frame, Id, Key, Layout, Margin,
   Order, Pos2, Rect, Response, RichText, Sense, Shape, Stroke, Ui, Vec2, WidgetInfo, WidgetText,
   WidgetType, accesskit, vec2,
};

use crate::Button;
use zeus_theme::Theme;

/// Boxed `FnOnce(&mut Ui)` callback used by the footer slots.
type UiFn<'a> = Box<dyn FnOnce(&mut Ui) + 'a>;

/// A centered modal dialog.
///
/// The `open` flag drives visibility: when it's `false` on entry to
/// [`Modal::show`], nothing is rendered; when the user clicks the backdrop,
/// presses `Esc`, or clicks the "×" button, it's flipped to `false`.
///
/// ```no_run
/// # use elegance::Modal;
/// # let ctx = egui::Context::default();
/// # let mut open = true;
/// Modal::new("stats", &mut open)
///     .heading("Run Summary")
///     .show(&ctx, |ui| {
///         ui.label("…");
///     });
/// ```
#[must_use = "Call `.show(ctx, |ui| { ... })` to render the modal."]
pub struct Modal<'a> {
   id_salt: Id,
   heading: Option<WidgetText>,
   subtitle: Option<WidgetText>,
   header_icon: Option<WidgetText>,
   backdrop_order: Order,
   content_order: Order,
   open: &'a mut bool,
   max_width: f32,
   closable: bool,
   close_on_backdrop: bool,
   close_on_escape: bool,
   alert: bool,
   footer: Option<UiFn<'a>>,
   footer_left: Option<UiFn<'a>>,
}

impl<'a> std::fmt::Debug for Modal<'a> {
   fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      f.debug_struct("Modal")
         .field("id_salt", &self.id_salt)
         .field(
            "heading",
            &self.heading.as_ref().map(|h| h.text()),
         )
         .field(
            "subtitle",
            &self.subtitle.as_ref().map(|h| h.text()),
         )
         .field(
            "header_icon",
            &self.header_icon.as_ref().map(|h| h.text()),
         )
         .field("backdrop_order", &self.backdrop_order)
         .field("content_order", &self.content_order)
         .field("open", &*self.open)
         .field("max_width", &self.max_width)
         .field("closable", &self.closable)
         .field("close_on_backdrop", &self.close_on_backdrop)
         .field("close_on_escape", &self.close_on_escape)
         .field("alert", &self.alert)
         .field(
            "footer",
            &self.footer.as_ref().map(|_| "<closure>"),
         )
         .field(
            "footer_left",
            &self.footer_left.as_ref().map(|_| "<closure>"),
         )
         .finish()
   }
}

impl<'a> Modal<'a> {
   /// Create a modal keyed by `id_salt` whose visibility is bound to `open`.
   pub fn new(id: impl Into<Id>, open: &'a mut bool) -> Self {
      Self {
         id_salt: Id::new(id.into()),
         heading: None,
         subtitle: None,
         header_icon: None,
         backdrop_order: Order::Middle,
         content_order: Order::Foreground,
         open,
         max_width: 440.0,
         closable: true,
         close_on_backdrop: true,
         close_on_escape: true,
         alert: false,
         footer: None,
         footer_left: None,
      }
   }

   /// Show a strong heading at the top of the modal, alongside the close button.
   pub fn heading(mut self, heading: impl Into<WidgetText>) -> Self {
      self.heading = Some(heading.into());
      self
   }

   /// Show a muted subtitle line under the heading.
   pub fn subtitle(mut self, subtitle: impl Into<WidgetText>) -> Self {
      self.subtitle = Some(subtitle.into());
      self
   }

   /// Paint a glyph in a tinted circular halo to the left of the heading.
   /// Use any short text — `"⚠"`, `"✓"`, `"!"`, an emoji, or a symbol from
   /// the bundled `Elegance Symbols` font. The halo's tint comes from
   /// [`Modal::header_accent`] and defaults to [`Accent::Sky`].
   pub fn header_icon(mut self, icon: impl Into<WidgetText>) -> Self {
      self.header_icon = Some(icon.into());
      self
   }

   /// Override the [Order] used for the backdrop of the modal
   pub fn backdrop_order(mut self, order: Order) -> Self {
      self.backdrop_order = order;
      self
   }

   /// Override the [Order] used for the content of the modal
   pub fn content_order(mut self, order: Order) -> Self {
      self.content_order = order;
      self
   }

   /// Override the maximum width of the modal card in points. Default: 440.
   pub fn max_width(mut self, max_width: f32) -> Self {
      self.max_width = max_width;
      self
   }

   /// Whether the user may dismiss the modal at all. When `false`, the
   /// close "×" button is hidden and `Esc` / backdrop clicks are ignored —
   /// regardless of [`Modal::close_on_backdrop`] / [`Modal::close_on_escape`].
   ///
   /// Use this to force the user to see an in-progress action through (or
   /// cancel it via an explicit footer button) — for example, blocking
   /// dismissal while a long-running task runs, instead of juggling the
   /// `open` flag with an external "is it running?" guard.
   ///
   /// This only removes the *user-driven* dismissal affordances; the caller
   /// is still free to set the bound `open` flag to `false` programmatically
   /// to close the modal from code. Default: `true`.
   pub fn closable(mut self, closable: bool) -> Self {
      self.closable = closable;
      self
   }

   /// Whether clicking the dimmed backdrop dismisses the modal. Default: `true`.
   pub fn close_on_backdrop(mut self, close: bool) -> Self {
      self.close_on_backdrop = close;
      self
   }

   /// Whether pressing `Esc` dismisses the modal. Default: `true`.
   pub fn close_on_escape(mut self, close: bool) -> Self {
      self.close_on_escape = close;
      self
   }

   /// Mark this modal as an *alert dialog* — a dialog that demands the
   /// user's attention to proceed, such as a destructive confirmation or
   /// an unsaved-changes prompt. Screen readers announce alert dialogs
   /// more assertively than ordinary dialogs. Default: `false`.
   ///
   /// Under the hood this exposes `accesskit::Role::AlertDialog` on the
   /// modal's root node instead of the default `Role::Dialog`.
   pub fn alert(mut self, alert: bool) -> Self {
      self.alert = alert;
      self
   }

   /// Add a footer row at the bottom of the modal. The closure runs in a
   /// right-to-left layout, so widgets added in source order land
   /// rightmost-first — matching the typical "Cancel | Confirm" reading.
   /// The footer renders below a horizontal divider and over a slightly
   /// recessed fill, separating it visually from the body.
   pub fn footer<F: FnOnce(&mut Ui) + 'a>(mut self, add_footer: F) -> Self {
      self.footer = Some(Box::new(add_footer));
      self
   }

   /// Add a left-aligned slot to the footer (only rendered when
   /// [`Modal::footer`] is also set). Useful for an "export before delete"
   /// checkbox or a keyboard-shortcut hint that should sit opposite the
   /// action buttons.
   pub fn footer_left<F: FnOnce(&mut Ui) + 'a>(mut self, add_left: F) -> Self {
      self.footer_left = Some(Box::new(add_left));
      self
   }

   /// Render the modal. Returns `None` if the modal was suppressed because
   /// the bound `open` flag was `false`; otherwise returns `Some(R)` with
   /// the content closure's return value.
   pub fn show<R>(self, ctx: &Context, add_contents: impl FnOnce(&mut Ui) -> R) -> Option<R> {
      // --- Focus lifecycle ------------------------------------------------
      // Track the open/closed transition so we can (a) record which widget
      // had keyboard focus before the modal opened and (b) restore that
      // focus when the modal closes. Without this the user's focus is
      // visually eclipsed by the modal but structurally remains behind it —
      // Tab would navigate widgets on the underlying page.
      let focus_storage = Id::new(("elegance_modal_focus", self.id_salt));
      let mut focus_state: ModalFocusState =
         ctx.data(|d| d.get_temp(focus_storage).unwrap_or_default());
      let is_open = *self.open;

      if focus_state.was_open && !is_open {
         // Just closed this frame — return focus to whatever had it before.
         if let Some(prev) = focus_state.prev_focus {
            ctx.memory_mut(|m| m.request_focus(prev));
         }
         ctx.data_mut(|d| d.insert_temp(focus_storage, ModalFocusState::default()));
         return None;
      }

      if !is_open {
         return None;
      }

      let just_opened = !focus_state.was_open;
      if just_opened {
         focus_state.prev_focus = ctx.memory(|m| m.focused());
         focus_state.was_open = true;
         ctx.data_mut(|d| d.insert_temp(focus_storage, focus_state));
      }

      let theme = Theme::current(ctx);
      let mut should_close = false;
      let mut close_btn_id: Option<Id> = None;
      let closable = self.closable;

      // --- Backdrop ----------------------------------------------------
      let screen = ctx.content_rect();
      let backdrop_id = Id::new("elegance_modal_backdrop").with(self.id_salt);
      let backdrop =
         Area::new(backdrop_id)
            .fixed_pos(screen.min)
            .order(self.backdrop_order)
            .show(ctx, |ui| {
               ui.painter().rect_filled(
                  screen,
                  CornerRadius::ZERO,
                  Color32::from_rgba_premultiplied(0, 0, 0, 150),
               );
               ui.allocate_rect(screen, Sense::click())
            });
      if closable && self.close_on_backdrop && backdrop.inner.clicked() {
         should_close = true;
      }

      // --- Content -----------------------------------------------------
      let window_id = Id::new("elegance_modal_window").with(self.id_salt);
      let alert = self.alert;
      let heading_text: Option<String> = self.heading.as_ref().map(|h| h.text().to_string());
      let result = Area::new(window_id)
         .order(self.content_order)
         .anchor(Align2::CENTER_CENTER, Vec2::ZERO)
         .show(ctx, |ui| {
            // Upgrade this Ui's accesskit role from `GenericContainer`
            // (set automatically by `Ui::new`) to a dialog role, so
            // screen readers announce the modal correctly and
            // platforms that support dialog focus tracking (AT-SPI)
            // treat it as a window-like surface.
            let role = if alert {
               accesskit::Role::AlertDialog
            } else {
               accesskit::Role::Dialog
            };
            let heading_for_label = heading_text.clone();
            ui.ctx().accesskit_node_builder(ui.unique_id(), |node| {
               node.set_role(role);
               if let Some(label) = heading_for_label {
                  node.set_label(label);
               }
            });

            ui.set_max_width(self.max_width);
            Frame::new()
               .fill(theme.colors.widget_bg)
               .stroke(Stroke::new(1.0, theme.colors.border))
               .corner_radius(theme.frame1.corner_radius)
               .show(ui, |ui| {
                  let pad = theme.frame1.inner_margin.left;
                  let has_heading = self.heading.is_some();
                  let has_icon = self.header_icon.is_some();
                  if has_heading || has_icon {
                     // Header band — same horizontal padding as body,
                     // tighter bottom so the optional separator + body
                     // continue to read as one block.
                     Frame::new()
                        .inner_margin(Margin {
                           left: pad as i8,
                           right: pad as i8,
                           top: pad as i8,
                           bottom: 0,
                        })
                        .show(ui, |ui| {
                           ui.horizontal_top(|ui| {
                              if let Some(icon) = &self.header_icon {
                                 paint_icon_halo(ui, icon.text(), &theme);
                                 ui.add_space(10.0);
                              }
                              ui.vertical(|ui| {
                                 if let Some(h) = &self.heading {
                                    ui.add(egui::Label::new(h.clone()));
                                 }
                                 if let Some(sub) = &self.subtitle {
                                    ui.add(egui::Label::new(sub.clone()));
                                 }
                              });
                              ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
                                 // A non-closable modal shows no "×":
                                 // there's no user-driven way out, so
                                 // an affordance would only mislead.
                                 if closable {
                                    let resp = close_button(ui, &theme);
                                    if resp.clicked() {
                                       should_close = true;
                                    }
                                    close_btn_id = Some(resp.id);
                                 }
                              });
                           });
                        });
                     ui.add_space(6.0);
                     ui.separator();
                     ui.add_space(10.0);
                  }
                  // --- Body ---
                  let body_result = Frame::new()
                     .inner_margin(Margin {
                        left: pad as i8,
                        right: pad as i8,
                        top: if has_heading || has_icon {
                           0
                        } else {
                           pad as i8
                        },
                        bottom: if self.footer.is_some() {
                           pad as i8 / 2
                        } else {
                           pad as i8
                        },
                     })
                     .show(ui, |ui| add_contents(ui))
                     .inner;

                  // --- Footer ---
                  if let Some(footer) = self.footer {
                     ui.separator();
                     // The recessed footer fill is painted by hand rather
                     // than via the frame's own `.fill`. A plain frame
                     // fill is a square-cornered rectangle flush with the
                     // card edges, so it paints over the card's rounded
                     // bottom corners and bottom border — the non-round
                     // corners reported in issue #7. Instead we lay the
                     // footer out with no fill, then drop a rounded fill
                     // into a slot reserved *behind* the content, tucked
                     // one pixel inside the 1px border so the border (and
                     // its rounded corners) stays unbroken all the way
                     // around.
                     let footer_fill = theme.colors.widget_bg;
                     let fill_idx = ui.painter().add(Shape::Noop);
                     let footer_rect = Frame::new()
                        .inner_margin(Margin::symmetric(pad as i8, pad as i8 * 3 / 4))
                        .show(ui, |ui| {
                           ui.horizontal(|ui| {
                              if let Some(left) = self.footer_left {
                                 left(ui);
                              }
                              ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                                 footer(ui);
                              });
                           });
                        })
                        .response
                        .rect;
                     // Round the bottom corners one pixel tighter than the
                     // card so the fill follows the inside of the border's
                     // curve; leave the top flush with the divider above.
                     let card_radius = theme.frame1.corner_radius.ne as f32;
                     let r = (card_radius - 1.0).max(0.0) as u8;
                     let fill_rect = Rect::from_min_max(
                        Pos2::new(footer_rect.left() + 1.0, footer_rect.top()),
                        Pos2::new(
                           footer_rect.right() - 1.0,
                           footer_rect.bottom() - 1.0,
                        ),
                     );
                     ui.painter().set(
                        fill_idx,
                        Shape::rect_filled(
                           fill_rect,
                           CornerRadius {
                              nw: 0,
                              ne: 0,
                              sw: r,
                              se: r,
                           },
                           footer_fill,
                        ),
                     );
                  }
                  body_result
               })
         });

      if closable && self.close_on_escape && ctx.input(|i| i.key_pressed(Key::Escape)) {
         should_close = true;
      }

      // On the first frame a modal is open, move keyboard focus into it so
      // Tab navigates within the dialog rather than the background. We
      // target the close button when a heading is present (it has a
      // stable id and is always interactive); without a heading there's
      // no intrinsic focus target, so focus is left to the caller.
      if just_opened && let Some(id) = close_btn_id {
         ctx.memory_mut(|m| m.request_focus(id));
      }

      if should_close {
         *self.open = false;
         // Restore focus and clear the lifecycle state right now — in the
         // same frame the close is triggered — rather than deferring to the
         // `was_open && !is_open` branch on a subsequent `show()`. Callers
         // routinely drop the modal the instant it closes (the natural
         // `if let Some(m) = &self.modal { … }` + `self.modal = None`
         // pattern), so `show()` is never called again. A deferred cleanup
         // would then silently leak: focus is never returned to the
         // pre-modal widget, and the stale `was_open = true` defeats the
         // just-opened focus grab the next time a modal with this salt opens.
         if let Some(prev) = focus_state.prev_focus {
            ctx.memory_mut(|m| m.request_focus(prev));
         }
         ctx.data_mut(|d| d.insert_temp(focus_storage, ModalFocusState::default()));
      }

      Some(result.inner.inner)
   }
}

/// Persistent focus-lifecycle state for a single `Modal`, keyed by the
/// modal's `id_salt`. Stored via `ctx.data_mut`.
#[derive(Clone, Copy, Default, Debug)]
struct ModalFocusState {
   /// Whether the modal was rendered open last frame. Used to detect
   /// open/close transitions.
   was_open: bool,
   /// Which widget (if any) had keyboard focus at the moment the modal
   /// opened. Restored on close.
   prev_focus: Option<Id>,
}

/// Render the modal's close button. Returns its `Response` so the caller
/// can route focus to it and check `clicked()`. The accesskit label is
/// set to `"Close"` explicitly — without this, screen readers announce
/// the "×" glyph literally as "multiplication sign."
///
/// The button is scoped under a stable id (`"elegance_modal_close"`) so
/// focus requests targeting it survive layout changes.
fn close_button(ui: &mut Ui, theme: &Theme) -> Response {
   let inner = ui
      .push_id("modal_close", |ui| {
         let text = RichText::new("X").size(theme.text_sizes.normal);
         ui.add(Button::new(text).min_size(vec2(20.0, 20.0)))
      })
      .inner;
   let enabled = inner.enabled();
   inner.widget_info(|| WidgetInfo::labeled(WidgetType::Button, enabled, "Close"));
   inner
}

/// Paint a circular tinted halo with a centered glyph. The fg uses the full
/// accent colour; the bg is the same colour at low alpha so the halo reads
/// as a coloured "wash" against the card surface.
fn paint_icon_halo(ui: &mut Ui, glyph: &str, theme: &Theme) {
   let size = 32.0;
   let (rect, _) = ui.allocate_exact_size(Vec2::splat(size), Sense::hover());
   let fg = theme.colors.accent;
   let bg = Color32::from_rgba_unmultiplied(fg.r(), fg.g(), fg.b(), 36);
   let painter = ui.painter();
   painter.circle_filled(rect.center(), size * 0.5, bg);
   painter.text(
      rect.center(),
      Align2::CENTER_CENTER,
      glyph,
      FontId::proportional(theme.text_sizes.heading + 2.0),
      fg,
   );
}