Skip to main content

max / makeover-immediate

18.5 KB · 501 lines History Blame Raw
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
25 use egui::{Align, Layout, Response, RichText, Sense, Ui, Vec2};
26 use makeover_layout::{Act, Figure, Meter, State, Token, Tone};
27
28 use 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)]
36 pub 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
59 impl 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.
88 pub 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.
145 pub 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
191 // Say what was drawn, because painting it says nothing.
192 //
193 // A token allocates its rect and paints the text straight onto it, so
194 // nothing reached the accessibility tree at all until 2026-08-22: an
195 // interactive chip was a control a mouse could press and a screen reader
196 // could not find, and a badge was text nobody could read out. The filter
197 // panel's twenty-four key pills were the site -- a whole way of filtering,
198 // absent.
199 //
200 // A chip that latches says so through `selected`, which is what a screen
201 // reader announces as pressed. That is `latched`'s whole meaning: the key
202 // is held down.
203 let role = if kind.interactive() {
204 egui::WidgetType::Button
205 } else {
206 egui::WidgetType::Label
207 };
208 response.widget_info(|| {
209 let mut info = egui::WidgetInfo::labeled(role, ui.is_enabled(), label);
210 if kind.interactive() {
211 info.selected = Some(latched);
212 }
213 info
214 });
215 response
216 }
217
218 /// A control.
219 ///
220 /// The key the description named is drawn beside the label where there is one,
221 /// which is [`Act::key`] finally being read by a second renderer: it was written
222 /// for a terminal, and a desktop app has keys too.
223 ///
224 /// **A disabled control is drawn and does not answer**, through
225 /// [`State::suppresses_interaction`] rather than a second reading of what
226 /// disabled means, and it takes [`Palette::content_muted`] because that is the
227 /// intent `State::Disabled` resolves to. egui is told through `add_enabled`, so
228 /// its own focus walk skips it: a control that is drawn and not reachable is
229 /// exactly what `disabled` means on every host, and here the host already has
230 /// the machinery.
231 pub fn act(ui: &mut Ui, act: &Act<'_>, palette: &Palette, _style: &WidgetStyle) -> Response {
232 let disabled = act.state.is_some_and(State::suppresses_interaction);
233 let label = match act.key {
234 Some(key) => format!("{} ({key})", act.label),
235 None => act.label.to_owned(),
236 };
237 let colour = if disabled {
238 palette.content_muted
239 } else {
240 palette.tone(act.tone)
241 };
242 ui.add_enabled(
243 !disabled,
244 egui::Button::new(RichText::new(label).color(colour)),
245 )
246 }
247
248 /// A figure: the value, then what it counts under it.
249 ///
250 /// The tone lands on the value and its change rather than on the caption, which
251 /// is what [`Figure::tone`] means: the figure is an ordinary fact and it is the
252 /// movement that reads as good or bad. `makeover-tui` says the same thing with a
253 /// bold span; here it is a larger one, because egui can size text and a terminal
254 /// cannot.
255 pub fn figure(
256 ui: &mut Ui,
257 figure: &Figure<'_>,
258 palette: &Palette,
259 style: &WidgetStyle,
260 ) -> Response {
261 ui.with_layout(Layout::top_down(Align::Min), |ui| {
262 let value = match figure.change {
263 Some(change) => format!("{} {change}", figure.value),
264 None => figure.value.to_owned(),
265 };
266 let size = egui::TextStyle::Body.resolve(ui.style()).size * style.figure_scale;
267 let shown = ui.label(
268 RichText::new(value)
269 .color(palette.tone(figure.tone))
270 .size(size)
271 .strong(),
272 );
273 ui.add_space(style.figure_gap);
274 ui.label(RichText::new(figure.caption).color(palette.content_muted));
275 shown
276 })
277 .inner
278 }
279
280 #[cfg(test)]
281 mod tests {
282 use super::*;
283
284 /// What the accessibility tree says a widget drew.
285 fn announced(
286 draw: impl FnMut(&mut Ui),
287 ) -> Vec<(
288 egui::accesskit::Role,
289 String,
290 Option<egui::accesskit::Toggled>,
291 )> {
292 let ctx = egui::Context::default();
293 ctx.enable_accesskit();
294 let mut draw = draw;
295 let input = || egui::RawInput {
296 screen_rect: Some(egui::Rect::from_min_size(
297 egui::Pos2::ZERO,
298 egui::vec2(600.0, 400.0),
299 )),
300 ..Default::default()
301 };
302 let _ = ctx.run_ui(input(), &mut draw);
303 let out = ctx.run_ui(input(), &mut draw);
304 out.platform_output
305 .accesskit_update
306 .expect("accesskit is on")
307 .nodes
308 .iter()
309 .map(|(_, node)| {
310 (
311 node.role(),
312 node.label()
313 .or_else(|| node.value())
314 .unwrap_or_default()
315 .to_owned(),
316 node.toggled(),
317 )
318 })
319 .collect()
320 }
321
322 #[test]
323 fn a_chip_is_announced_as_a_control_and_says_whether_it_is_held() {
324 // A token paints its own text onto its own rect, so before 2026-08-22
325 // it reached the tree as nothing: pressable by a mouse and invisible to
326 // everything else.
327 let p = palette();
328 let style = WidgetStyle::default();
329 let drawn = announced(|ui| {
330 token(
331 ui,
332 "C#",
333 Token::Chip { removable: false },
334 Tone::Neutral,
335 true,
336 &p,
337 &style,
338 );
339 });
340
341 let chip = drawn
342 .iter()
343 .find(|(role, name, _)| *role == egui::accesskit::Role::Button && name == "C#")
344 .unwrap_or_else(|| panic!("the chip is not in the tree: {drawn:?}"));
345 assert_eq!(
346 chip.2,
347 Some(egui::accesskit::Toggled::True),
348 "a latched chip is held down and says so: {drawn:?}"
349 );
350 }
351
352 #[test]
353 fn a_badge_is_announced_as_the_text_it_is() {
354 // Not a control, and not nothing either: a badge is a word on the
355 // screen and painting it is not the same as saying it.
356 let p = palette();
357 let style = WidgetStyle::default();
358 let drawn = announced(|ui| {
359 token(ui, "wav", Token::Badge, Tone::Neutral, false, &p, &style);
360 });
361
362 assert!(
363 drawn
364 .iter()
365 .any(|(role, name, _)| *role == egui::accesskit::Role::Label && name == "wav"),
366 "{drawn:?}"
367 );
368 assert!(
369 !drawn
370 .iter()
371 .any(|(role, _, _)| *role == egui::accesskit::Role::Button),
372 "a badge answers nothing and must not claim to: {drawn:?}"
373 );
374 }
375
376 fn palette() -> Palette {
377 use egui::Color32;
378 Palette {
379 page: Color32::from_rgb(1, 1, 1),
380 raised: Color32::from_rgb(2, 2, 2),
381 overlay: Color32::from_rgb(3, 3, 3),
382 well: Color32::from_rgb(4, 4, 4),
383 sunken: Color32::from_rgb(5, 5, 5),
384 bevel_light: Color32::from_rgb(6, 6, 6),
385 bevel_dark: Color32::from_rgb(7, 7, 7),
386 elevation: Color32::from_black_alpha(40),
387 content: Color32::from_rgb(20, 20, 20),
388 content_secondary: Color32::from_rgb(120, 120, 120),
389 content_muted: Color32::from_rgb(21, 21, 21),
390 action: Color32::from_rgb(22, 22, 22),
391 danger: Color32::from_rgb(23, 23, 23),
392 success: Color32::from_rgb(24, 24, 24),
393 warning: Color32::from_rgb(25, 25, 25),
394 info: Color32::from_rgb(26, 26, 26),
395 }
396 }
397
398 #[test]
399 fn every_tone_resolves_and_no_two_share_a_colour() {
400 // The reason the three status intents arrived together: a resolver
401 // missing one has to invent a colour for it.
402 let p = palette();
403 let all = [
404 p.tone(Tone::Neutral),
405 p.tone(Tone::Info),
406 p.tone(Tone::Success),
407 p.tone(Tone::Warning),
408 p.tone(Tone::Danger),
409 ];
410 for (i, a) in all.iter().enumerate() {
411 for b in &all[i + 1..] {
412 assert_ne!(a, b, "two tones resolved to one colour");
413 }
414 }
415 assert_eq!(p.tone(Tone::Neutral), p.content, "neutral is ordinary text");
416 }
417
418 #[test]
419 fn a_meter_draws_and_an_overrun_does_not_panic() {
420 // `done` may exceed `total`, which is the case Meter's own docs call
421 // the one worth drawing. The fill clamps; the reading does not.
422 let p = palette();
423 let style = WidgetStyle::default();
424 egui::__run_test_ui(|ui| {
425 meter(ui, &Meter::new(3, 6), &p, &style);
426 meter(ui, &Meter::new(9, 6), &p, &style);
427 // No set, rather than a complete one.
428 meter(ui, &Meter::new(0, 0), &p, &style);
429 // The overflow `makeover-layout` pins on its own side.
430 meter(ui, &Meter::new(u32::MAX, u32::MAX), &p, &style);
431 });
432 }
433
434 #[test]
435 fn a_chip_answers_a_click_and_a_badge_does_not() {
436 // `Token::interactive` is the whole difference between the members, and
437 // the sense is what makes egui agree with it.
438 let p = palette();
439 let style = WidgetStyle::default();
440 egui::__run_test_ui(|ui| {
441 let badge = token(ui, "beta", Token::Badge, Tone::Info, false, &p, &style);
442 assert!(!badge.sense.senses_click(), "a badge answers no click");
443
444 let chip = token(
445 ui,
446 "drums",
447 Token::Chip { removable: false },
448 Tone::Neutral,
449 false,
450 &p,
451 &style,
452 );
453 assert!(chip.sense.senses_click(), "a chip answers a click");
454 });
455 }
456
457 #[test]
458 fn a_disabled_control_is_drawn_and_does_not_answer() {
459 // Present, visible, and not answering. Through
460 // `State::suppresses_interaction` rather than a second reading here.
461 let p = palette();
462 let style = WidgetStyle::default();
463 egui::__run_test_ui(|ui| {
464 let live = act(ui, &Act::new("Save"), &p, &style);
465 assert!(live.enabled());
466
467 let gone = act(ui, &Act::new("Save").state(State::Disabled), &p, &style);
468 assert!(!gone.enabled(), "a disabled control still answers");
469 });
470 }
471
472 #[test]
473 fn a_control_shows_the_key_the_description_named() {
474 // `Act::key` was written for a terminal before there was one. A desktop
475 // app has keys too, so this is its second reader.
476 let p = palette();
477 let style = WidgetStyle::default();
478 egui::__run_test_ui(|ui| {
479 act(ui, &Act::new("New").key("n"), &p, &style);
480 act(ui, &Act::new("New"), &p, &style);
481 });
482 }
483
484 #[test]
485 fn a_figure_draws_its_movement_beside_its_value() {
486 let p = palette();
487 let style = WidgetStyle::default();
488 egui::__run_test_ui(|ui| {
489 figure(ui, &Figure::new("17", "Current streak"), &p, &style);
490 figure(
491 ui,
492 &Figure::new("17", "Current streak")
493 .change("+3")
494 .tone(Tone::Success),
495 &p,
496 &style,
497 );
498 });
499 }
500 }
501