Skip to main content

makeover_immediate/
widget.rs

1//! The described things that are not fields, tables or frames.
2//!
3//! A meter, a token, a control, a figure. `makeover-tui` has had these since its
4//! own `widget` module and this crate has not, which is the gap that showed up
5//! the moment anything tried to draw a whole `quasi_router::Screen` in egui:
6//! the screen walk had a renderer for the containers and nothing for four of the
7//! nodes inside them, so the drawing would have landed in the consumer, one copy
8//! per app. That is the divergence this suite exists to end, so it lands here.
9//!
10//! # What "in egui" changes, and what it does not
11//!
12//! The semantics are `makeover-tui`'s, deliberately: a meter is a bar and a
13//! reading, a badge is round and a chip is square, a control names its key where
14//! the description gave one, and a figure puts the movement on the value rather
15//! than on the caption. Those are description-level readings and they do not get
16//! a second opinion per host.
17//!
18//! What differs is forced by the target rather than chosen. A terminal spends a
19//! whole cell on a character and returns a `Line` for the caller to place; egui
20//! paints an arbitrary rect and answers a [`Response`], so every function here
21//! draws into the `Ui` it is given and hands back what the user did to it. That
22//! is also why nothing here takes a `focused` flag the way `makeover-tui`'s
23//! `act` does: egui owns focus, which is the rule the crate header states.
24
25use egui::{Align, Layout, Response, RichText, Sense, Ui, Vec2};
26use makeover_layout::{Act, Figure, Meter, State, Token, Tone};
27
28use crate::Palette;
29
30/// The sizes a widget cannot derive from the description.
31///
32/// Every number a caller might reasonably want different, in one place, on the
33/// footing [`FrameStyle`](crate::FrameStyle) and [`FieldStyle`](crate::FieldStyle)
34/// already establish: this crate owns no sizes.
35#[derive(Debug, Clone, Copy, PartialEq)]
36pub struct WidgetStyle {
37    /// How tall a meter's bar is drawn.
38    pub meter_height: f32,
39    /// How wide a meter's bar runs, or `None` to take the width on offer.
40    ///
41    /// `None` is the honest default in immediate mode: a bar in a side panel and
42    /// a bar in a wide pane are the same description, and the available width is
43    /// the only thing either of them knows.
44    pub meter_width: Option<f32>,
45    /// The corner radius on a meter's trough and on a token.
46    pub radius: u8,
47    /// Inside a token, around its label.
48    pub token_padding: Vec2,
49    /// Between a figure's value and its caption.
50    pub figure_gap: f32,
51    /// How much larger a figure's value is drawn than the body text.
52    ///
53    /// A multiplier rather than a size, so a figure scales with whatever text
54    /// style the app has set rather than pinning a point size this crate has no
55    /// business choosing.
56    pub figure_scale: f32,
57}
58
59impl Default for WidgetStyle {
60    /// Bars at 6pt taking the width on offer, and a figure at double text size.
61    fn default() -> Self {
62        Self {
63            meter_height: 6.0,
64            meter_width: None,
65            radius: 3,
66            token_padding: Vec2::new(6.0, 2.0),
67            figure_gap: 2.0,
68            figure_scale: 2.0,
69        }
70    }
71}
72
73/// A proportion as a bar and a reading.
74///
75/// The reading is built here from the two numbers and the noun, for the reason
76/// `makeover-tui` states: [`Meter::label`] carries the noun alone, so each
77/// renderer picks its own sentence order rather than the description picking one
78/// for all of them.
79///
80/// **A bar that has run over is drawn full and reads over.** `done` may exceed
81/// `total` and that is the case worth drawing, per `Meter`'s own docs: the fill
82/// is clamped because a rect cannot be longer than itself, and the reading is
83/// not, because "9/6" is the fact the user needs. Clamping both would hide the
84/// overrun entirely, which is the bug goingson's `is_over_estimate` flag exists
85/// to recover from on the other side.
86///
87/// A zero `total` is no set rather than a complete one, so it draws empty.
88pub fn meter(ui: &mut Ui, meter: &Meter<'_>, palette: &Palette, style: &WidgetStyle) -> Response {
89    let width = style
90        .meter_width
91        .unwrap_or_else(|| ui.available_width().max(1.0));
92    ui.horizontal(|ui| {
93        let (rect, response) =
94            ui.allocate_exact_size(Vec2::new(width, style.meter_height), Sense::hover());
95        // The trough is the sunken surface rather than a tint of the tone: a
96        // bar is a thing set into the page with something in it, which is what
97        // `Fill::Sunken` means, and tinting the empty half would read as a
98        // second, paler proportion.
99        ui.painter().rect_filled(rect, style.radius, palette.sunken);
100        let share = if meter.total == 0 {
101            0.0
102        } else {
103            (f64::from(meter.done) / f64::from(meter.total)).min(1.0)
104        };
105        #[expect(
106            clippy::cast_possible_truncation,
107            reason = "a share is 0..=1 and the product is a width in points"
108        )]
109        let filled = (f64::from(rect.width()) * share) as f32;
110        if filled > 0.0 {
111            let mut fill = rect;
112            fill.set_width(filled);
113            ui.painter()
114                .rect_filled(fill, style.radius, palette.tone(meter.tone));
115        }
116        let reading = match meter.label {
117            Some(label) => format!("{}/{} {label}", meter.done, meter.total),
118            None => format!("{}/{}", meter.done, meter.total),
119        };
120        ui.label(RichText::new(reading).color(palette.content_muted));
121        response
122    })
123    .inner
124}
125
126/// A badge or a chip.
127///
128/// Round for a badge, square for a chip, which is `makeover-tui`'s reading and
129/// `makeover-webview`'s before it. The shape carries the difference because
130/// colour is already spent on the tone.
131///
132/// **A chip answers a click and a badge does not**, which is
133/// [`Token::interactive`] and is the whole difference between the members. The
134/// `Response` comes back either way, so a caller that presses a badge is
135/// pressing something this function said was not interactive; the sense is what
136/// makes egui agree.
137///
138/// `latched` is a chip that is switched on, and it fills rather than outlines. A
139/// terminal has to collide latched with focus because it has one spare axis for
140/// two facts; egui does not, so it does not.
141///
142/// A chip's removable half is not drawn, on `makeover-tui`'s reasoning: a second
143/// control inside a token is a question for whoever owns the interaction rather
144/// than for a drawing.
145pub fn token(
146    ui: &mut Ui,
147    label: &str,
148    kind: Token,
149    tone: Tone,
150    latched: bool,
151    palette: &Palette,
152    style: &WidgetStyle,
153) -> Response {
154    let painted = palette.tone(tone);
155    let radius = match kind {
156        // Round enough to read as a pill whatever the height turns out to be.
157        Token::Badge => u8::MAX,
158        Token::Chip { .. } => style.radius,
159    };
160    let sense = if kind.interactive() {
161        Sense::click()
162    } else {
163        Sense::hover()
164    };
165
166    // Laid out before the rect is allocated, because a token is exactly as wide
167    // as what it says plus its padding: there is no box to fit text into here,
168    // the way a table cell has one.
169    let ink = if latched { palette.page } else { painted };
170    let galley = ui.painter().layout_no_wrap(
171        label.to_owned(),
172        egui::TextStyle::Body.resolve(ui.style()),
173        ink,
174    );
175    let size = galley.size() + style.token_padding * 2.0;
176    let (rect, response) = ui.allocate_exact_size(size, sense);
177
178    if latched {
179        ui.painter().rect_filled(rect, radius, painted);
180    } else {
181        ui.painter().rect_stroke(
182            rect,
183            radius,
184            egui::Stroke::new(1.0, painted),
185            egui::StrokeKind::Inside,
186        );
187    }
188    ui.painter()
189        .galley(rect.center() - galley.size() / 2.0, galley, ink);
190    response
191}
192
193/// A control.
194///
195/// The key the description named is drawn beside the label where there is one,
196/// which is [`Act::key`] finally being read by a second renderer: it was written
197/// for a terminal, and a desktop app has keys too.
198///
199/// **A disabled control is drawn and does not answer**, through
200/// [`State::suppresses_interaction`] rather than a second reading of what
201/// disabled means, and it takes [`Palette::content_muted`] because that is the
202/// intent `State::Disabled` resolves to. egui is told through `add_enabled`, so
203/// its own focus walk skips it: a control that is drawn and not reachable is
204/// exactly what `disabled` means on every host, and here the host already has
205/// the machinery.
206pub fn act(ui: &mut Ui, act: &Act<'_>, palette: &Palette, _style: &WidgetStyle) -> Response {
207    let disabled = act.state.is_some_and(State::suppresses_interaction);
208    let label = match act.key {
209        Some(key) => format!("{}  ({key})", act.label),
210        None => act.label.to_owned(),
211    };
212    let colour = if disabled {
213        palette.content_muted
214    } else {
215        palette.tone(act.tone)
216    };
217    ui.add_enabled(
218        !disabled,
219        egui::Button::new(RichText::new(label).color(colour)),
220    )
221}
222
223/// A figure: the value, then what it counts under it.
224///
225/// The tone lands on the value and its change rather than on the caption, which
226/// is what [`Figure::tone`] means: the figure is an ordinary fact and it is the
227/// movement that reads as good or bad. `makeover-tui` says the same thing with a
228/// bold span; here it is a larger one, because egui can size text and a terminal
229/// cannot.
230pub fn figure(
231    ui: &mut Ui,
232    figure: &Figure<'_>,
233    palette: &Palette,
234    style: &WidgetStyle,
235) -> Response {
236    ui.with_layout(Layout::top_down(Align::Min), |ui| {
237        let value = match figure.change {
238            Some(change) => format!("{} {change}", figure.value),
239            None => figure.value.to_owned(),
240        };
241        let size = egui::TextStyle::Body.resolve(ui.style()).size * style.figure_scale;
242        let shown = ui.label(
243            RichText::new(value)
244                .color(palette.tone(figure.tone))
245                .size(size)
246                .strong(),
247        );
248        ui.add_space(style.figure_gap);
249        ui.label(RichText::new(figure.caption).color(palette.content_muted));
250        shown
251    })
252    .inner
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258
259    fn palette() -> Palette {
260        use egui::Color32;
261        Palette {
262            page: Color32::from_rgb(1, 1, 1),
263            raised: Color32::from_rgb(2, 2, 2),
264            overlay: Color32::from_rgb(3, 3, 3),
265            well: Color32::from_rgb(4, 4, 4),
266            sunken: Color32::from_rgb(5, 5, 5),
267            bevel_light: Color32::from_rgb(6, 6, 6),
268            bevel_dark: Color32::from_rgb(7, 7, 7),
269            elevation: Color32::from_black_alpha(40),
270            content: Color32::from_rgb(20, 20, 20),
271            content_secondary: Color32::from_rgb(120, 120, 120),
272            content_muted: Color32::from_rgb(21, 21, 21),
273            action: Color32::from_rgb(22, 22, 22),
274            danger: Color32::from_rgb(23, 23, 23),
275            success: Color32::from_rgb(24, 24, 24),
276            warning: Color32::from_rgb(25, 25, 25),
277            info: Color32::from_rgb(26, 26, 26),
278        }
279    }
280
281    #[test]
282    fn every_tone_resolves_and_no_two_share_a_colour() {
283        // The reason the three status intents arrived together: a resolver
284        // missing one has to invent a colour for it.
285        let p = palette();
286        let all = [
287            p.tone(Tone::Neutral),
288            p.tone(Tone::Info),
289            p.tone(Tone::Success),
290            p.tone(Tone::Warning),
291            p.tone(Tone::Danger),
292        ];
293        for (i, a) in all.iter().enumerate() {
294            for b in &all[i + 1..] {
295                assert_ne!(a, b, "two tones resolved to one colour");
296            }
297        }
298        assert_eq!(p.tone(Tone::Neutral), p.content, "neutral is ordinary text");
299    }
300
301    #[test]
302    fn a_meter_draws_and_an_overrun_does_not_panic() {
303        // `done` may exceed `total`, which is the case Meter's own docs call
304        // the one worth drawing. The fill clamps; the reading does not.
305        let p = palette();
306        let style = WidgetStyle::default();
307        egui::__run_test_ui(|ui| {
308            meter(ui, &Meter::new(3, 6), &p, &style);
309            meter(ui, &Meter::new(9, 6), &p, &style);
310            // No set, rather than a complete one.
311            meter(ui, &Meter::new(0, 0), &p, &style);
312            // The overflow `makeover-layout` pins on its own side.
313            meter(ui, &Meter::new(u32::MAX, u32::MAX), &p, &style);
314        });
315    }
316
317    #[test]
318    fn a_chip_answers_a_click_and_a_badge_does_not() {
319        // `Token::interactive` is the whole difference between the members, and
320        // the sense is what makes egui agree with it.
321        let p = palette();
322        let style = WidgetStyle::default();
323        egui::__run_test_ui(|ui| {
324            let badge = token(ui, "beta", Token::Badge, Tone::Info, false, &p, &style);
325            assert!(!badge.sense.senses_click(), "a badge answers no click");
326
327            let chip = token(
328                ui,
329                "drums",
330                Token::Chip { removable: false },
331                Tone::Neutral,
332                false,
333                &p,
334                &style,
335            );
336            assert!(chip.sense.senses_click(), "a chip answers a click");
337        });
338    }
339
340    #[test]
341    fn a_disabled_control_is_drawn_and_does_not_answer() {
342        // Present, visible, and not answering. Through
343        // `State::suppresses_interaction` rather than a second reading here.
344        let p = palette();
345        let style = WidgetStyle::default();
346        egui::__run_test_ui(|ui| {
347            let live = act(ui, &Act::new("Save"), &p, &style);
348            assert!(live.enabled());
349
350            let gone = act(ui, &Act::new("Save").state(State::Disabled), &p, &style);
351            assert!(!gone.enabled(), "a disabled control still answers");
352        });
353    }
354
355    #[test]
356    fn a_control_shows_the_key_the_description_named() {
357        // `Act::key` was written for a terminal before there was one. A desktop
358        // app has keys too, so this is its second reader.
359        let p = palette();
360        let style = WidgetStyle::default();
361        egui::__run_test_ui(|ui| {
362            act(ui, &Act::new("New").key("n"), &p, &style);
363            act(ui, &Act::new("New"), &p, &style);
364        });
365    }
366
367    #[test]
368    fn a_figure_draws_its_movement_beside_its_value() {
369        let p = palette();
370        let style = WidgetStyle::default();
371        egui::__run_test_ui(|ui| {
372            figure(ui, &Figure::new("17", "Current streak"), &p, &style);
373            figure(
374                ui,
375                &Figure::new("17", "Current streak")
376                    .change("+3")
377                    .tone(Tone::Success),
378                &p,
379                &style,
380            );
381        });
382    }
383}