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, and a wait. `makeover-tui` has had
4//! most of these since its
5//! own `widget` module and this crate has not, which is the gap that showed up
6//! the moment anything tried to draw a whole `quasi_router::Screen` in egui:
7//! the screen walk had a renderer for the containers and nothing for four of the
8//! nodes inside them, so the drawing would have landed in the consumer, one copy
9//! per app. That is the divergence this suite exists to end, so it lands here.
10//!
11//! # What "in egui" changes, and what it does not
12//!
13//! The semantics are `makeover-tui`'s, deliberately: a meter is a bar and a
14//! reading, a badge is round and a chip is square, a control names its key where
15//! the description gave one, and a figure puts the movement on the value rather
16//! than on the caption. Those are description-level readings and they do not get
17//! a second opinion per host.
18//!
19//! What differs is forced by the target rather than chosen. A terminal spends a
20//! whole cell on a character and returns a `Line` for the caller to place; egui
21//! paints an arbitrary rect and answers a [`Response`], so every function here
22//! draws into the `Ui` it is given and hands back what the user did to it. That
23//! is also why nothing here takes a `focused` flag the way `makeover-tui`'s
24//! `act` does: egui owns focus, which is the rule the crate header states.
25
26use egui::{Align, Layout, Response, RichText, Sense, Ui, Vec2};
27use makeover_layout::{Act, Awaiting, Bar, Chart, Fact, Figure, Meter, State, Token, Tone};
28use makeover_timing::activity_blink;
29use std::time::Duration;
30
31use crate::Palette;
32
33/// The sizes a widget cannot derive from the description.
34///
35/// Every number a caller might reasonably want different, in one place, on the
36/// footing [`FrameStyle`](crate::FrameStyle) and [`FieldStyle`](crate::FieldStyle)
37/// already establish: this crate owns no sizes.
38#[derive(Debug, Clone, Copy, PartialEq)]
39pub struct WidgetStyle {
40    /// How tall a meter's bar is drawn.
41    pub meter_height: f32,
42    /// How wide a meter's bar runs, or `None` to take the width on offer.
43    ///
44    /// `None` is the honest default in immediate mode: a bar in a side panel and
45    /// a bar in a wide pane are the same description, and the available width is
46    /// the only thing either of them knows.
47    pub meter_width: Option<f32>,
48    /// How tall a chart stands, in points.
49    ///
50    /// A chart's own, not [`meter_height`](Self::meter_height): a meter is a
51    /// rule set into a line of text and a chart is a figure with room of its
52    /// own. `makeover-webview` defers the same number to `--chart-height` for
53    /// the same reason, and 200 is the same default.
54    pub chart_height: f32,
55    /// The corner radius on a meter's trough and on a token.
56    pub radius: u8,
57    /// Inside a token, around its label.
58    pub token_padding: Vec2,
59    /// Between a figure's value and its caption.
60    pub figure_gap: f32,
61    /// How much larger a figure's value is drawn than the body text.
62    ///
63    /// A multiplier rather than a size, so a figure scales with whatever text
64    /// style the app has set rather than pinning a point size this crate has no
65    /// business choosing.
66    pub figure_scale: f32,
67    /// The side of the activity mark, square.
68    ///
69    /// Small on purpose. The mark says one thing and a reader should have to
70    /// look at it to read it, which is the difference between an indicator and
71    /// an animation competing with the content it sits beside.
72    pub mark_size: f32,
73}
74
75impl Default for WidgetStyle {
76    /// Bars at 6pt taking the width on offer, a figure at double text size, and
77    /// the activity mark a square a little larger than a bar is tall.
78    fn default() -> Self {
79        Self {
80            meter_height: 6.0,
81            meter_width: None,
82            chart_height: 200.0,
83            radius: 3,
84            token_padding: Vec2::new(6.0, 2.0),
85            figure_gap: 2.0,
86            figure_scale: 2.0,
87            mark_size: 8.0,
88        }
89    }
90}
91
92/// A proportion as a bar and a reading.
93///
94/// The reading is built here from the two numbers and the noun, for the reason
95/// `makeover-tui` states: [`Meter::label`] carries the noun alone, so each
96/// renderer picks its own sentence order rather than the description picking one
97/// for all of them.
98///
99/// **A bar that has run over is drawn full and reads over.** `done` may exceed
100/// `total` and that is the case worth drawing, per `Meter`'s own docs: the fill
101/// is clamped because a rect cannot be longer than itself, and the reading is
102/// not, because "9/6" is the fact the user needs. Clamping both would hide the
103/// overrun entirely, which is the bug goingson's `is_over_estimate` flag exists
104/// to recover from on the other side.
105///
106/// A zero `total` is no set rather than a complete one, so it draws empty.
107pub fn meter(ui: &mut Ui, meter: &Meter<'_>, palette: &Palette, style: &WidgetStyle) -> Response {
108    let width = style
109        .meter_width
110        .unwrap_or_else(|| ui.available_width().max(1.0));
111    ui.horizontal(|ui| {
112        let (rect, response) =
113            ui.allocate_exact_size(Vec2::new(width, style.meter_height), Sense::hover());
114        // The trough is the sunken surface rather than a tint of the tone: a
115        // bar is a thing set into the page with something in it, which is what
116        // `Fill::Sunken` means, and tinting the empty half would read as a
117        // second, paler proportion.
118        ui.painter().rect_filled(rect, style.radius, palette.sunken);
119        let share = if meter.total == 0 {
120            0.0
121        } else {
122            (f64::from(meter.done) / f64::from(meter.total)).min(1.0)
123        };
124        #[expect(
125            clippy::cast_possible_truncation,
126            reason = "a share is 0..=1 and the product is a width in points"
127        )]
128        let filled = (f64::from(rect.width()) * share) as f32;
129        if filled > 0.0 {
130            let mut fill = rect;
131            fill.set_width(filled);
132            ui.painter()
133                .rect_filled(fill, style.radius, palette.tone(meter.tone));
134        }
135        let reading = match meter.label {
136            Some(label) => format!("{}/{} {label}", meter.done, meter.total),
137            None => format!("{}/{}", meter.done, meter.total),
138        };
139        ui.label(RichText::new(reading).color(palette.content_muted));
140        response
141    })
142    .inner
143}
144
145/// A badge or a chip.
146///
147/// A badge is the table model's (wiki `table-model`), as `makeover-webview`
148/// draws it: a fill of its tone surface inside a one-point edge in its tone,
149/// the label in content ink. A neutral badge fills with the raised surface and
150/// takes the border for its edge. The tone is never the ink, which measured
151/// 1.34:1 as text on goingson's warning.
152///
153/// A chip is outlined in its tone, and filled while latched.
154///
155/// **A chip answers a click and a badge does not**, which is
156/// [`Token::interactive`] and is the whole difference between the members. The
157/// `Response` comes back either way, so a caller that presses a badge is
158/// pressing something this function said was not interactive; the sense is what
159/// makes egui agree.
160///
161/// `latched` is a chip that is switched on, and it fills rather than outlines. A
162/// terminal has to collide latched with focus because it has one spare axis for
163/// two facts; egui does not, so it does not.
164///
165/// A chip's removable half is not drawn, on `makeover-tui`'s reasoning: a second
166/// control inside a token is a question for whoever owns the interaction rather
167/// than for a drawing.
168pub fn token(
169    ui: &mut Ui,
170    label: &str,
171    kind: Token,
172    tone: Tone,
173    latched: bool,
174    palette: &Palette,
175    style: &WidgetStyle,
176) -> Response {
177    let painted = palette.tone(tone);
178    let radius = style.radius;
179    let sense = if kind.interactive() {
180        Sense::click()
181    } else {
182        Sense::hover()
183    };
184
185    // Laid out before the rect is allocated, because a token is exactly as wide
186    // as what it says plus its padding: there is no box to fit text into here,
187    // the way a table cell has one.
188    let ink = match kind {
189        Token::Badge => palette.content,
190        Token::Chip { .. } if latched => palette.page,
191        Token::Chip { .. } => painted,
192    };
193    let galley = ui.painter().layout_no_wrap(
194        label.to_owned(),
195        egui::TextStyle::Body.resolve(ui.style()),
196        ink,
197    );
198    let size = galley.size() + style.token_padding * 2.0;
199    let (rect, response) = ui.allocate_exact_size(size, sense);
200
201    if kind == Token::Badge {
202        ui.painter().rect(
203            rect,
204            radius,
205            palette.tone_surface(tone),
206            egui::Stroke::new(1.0, palette.tone_edge(tone)),
207            egui::StrokeKind::Inside,
208        );
209    } else if latched {
210        ui.painter().rect_filled(rect, radius, painted);
211    } else {
212        ui.painter().rect_stroke(
213            rect,
214            radius,
215            egui::Stroke::new(1.0, painted),
216            egui::StrokeKind::Inside,
217        );
218    }
219    ui.painter()
220        .galley(rect.center() - galley.size() / 2.0, galley, ink);
221
222    // Say what was drawn, because painting it says nothing.
223    //
224    // A token allocates its rect and paints the text straight onto it, so
225    // nothing reached the accessibility tree at all until 2026-08-22: an
226    // interactive chip was a control a mouse could press and a screen reader
227    // could not find, and a badge was text nobody could read out. The filter
228    // panel's twenty-four key pills were the site -- a whole way of filtering,
229    // absent.
230    //
231    // A chip that latches says so through `selected`, which is what a screen
232    // reader announces as pressed. That is `latched`'s whole meaning: the key
233    // is held down.
234    let role = if kind.interactive() {
235        egui::WidgetType::Button
236    } else {
237        egui::WidgetType::Label
238    };
239    response.widget_info(|| {
240        let mut info = egui::WidgetInfo::labeled(role, ui.is_enabled(), label);
241        if kind.interactive() {
242            info.selected = Some(latched);
243        }
244        info
245    });
246    response
247}
248
249/// A control.
250///
251/// The key the description named is drawn beside the label where there is one,
252/// which is [`Act::key`] finally being read by a second renderer: it was written
253/// for a terminal, and a desktop app has keys too.
254///
255/// **A disabled control is drawn and does not answer**, through
256/// [`State::suppresses_interaction`] rather than a second reading of what
257/// disabled means, and it takes [`Palette::content_muted`] because that is the
258/// intent `State::Disabled` resolves to. egui is told through `add_enabled`, so
259/// its own focus walk skips it: a control that is drawn and not reachable is
260/// exactly what `disabled` means on every host, and here the host already has
261/// the machinery.
262pub fn act(ui: &mut Ui, act: &Act<'_>, palette: &Palette, _style: &WidgetStyle) -> Response {
263    let disabled = act.state.is_some_and(State::suppresses_interaction);
264    let label = match act.key {
265        Some(key) => format!("{}  ({key})", act.label),
266        None => act.label.to_owned(),
267    };
268    let colour = if disabled {
269        palette.content_muted
270    } else {
271        palette.tone(act.tone)
272    };
273    // The act the screen is for takes the accent as a ground, which is this
274    // host's spelling of the webview's filled leading button (`Act::leading`).
275    //
276    // **Leading fills and committing outlines**, so the two compose: a control
277    // that is both is filled *and* stroked, and a sub-form's submit keeps the
278    // stroke alone. Before the member existed the stroke was the only emphasis
279    // there was, so a sub-form's Add and the screen's own act were drawn the
280    // same.
281    //
282    // Disabled takes neither, for the frame's reason below: a filled control
283    // that cannot be pressed is the loudest thing on the screen and does
284    // nothing.
285    // Untoned only, which a render caught missing. A toned control already
286    // says what pressing it means and that outranks how badly the screen wants
287    // it pressed, which is the rule `makeover-tui` states; without it the fill
288    // and the tone fight and the label loses.
289    let leading = act.leading && !disabled && act.tone == Tone::Neutral;
290    let colour = if leading {
291        palette.content_on_action
292    } else {
293        colour
294    };
295    let mut button = egui::Button::new(RichText::new(label).color(colour));
296    if leading {
297        button = button.fill(palette.action);
298    }
299    // The control that commits wears a frame, which is this host's spelling of
300    // the webview's default-button ring (`Act::commits`). Muted when disabled,
301    // as the label is, so it keeps its shape without asking for a press.
302    if act.commits {
303        let frame = if disabled {
304            palette.content_muted
305        } else {
306            palette.content
307        };
308        button = button.stroke(egui::Stroke::new(2.0, frame));
309    }
310    let drawn = ui.add_enabled(!disabled, button);
311    // Standing help, as a hover, which is honest on this host in a way it is
312    // not on a terminal: egui has a pointer. `makeover_tui` says the same
313    // sentence as a muted row under the control.
314    //
315    // Drawn here rather than by the caller as of `Act::hint` (0.40.0). quasi's
316    // egui renderer was doing exactly this outside the widget because
317    // `layout::Act` carried no hint, so a host that was not quasi got nothing.
318    match act.hint {
319        Some(hint) => drawn.on_hover_text(hint),
320        None => drawn,
321    }
322}
323
324/// A figure: the value, then what it counts under it.
325///
326/// The tone lands on the value and its change rather than on the caption, which
327/// is what [`Figure::tone`] means: the figure is an ordinary fact and it is the
328/// movement that reads as good or bad. `makeover-tui` says the same thing with a
329/// bold span; here it is a larger one, because egui can size text and a terminal
330/// cannot.
331/// Labelled facts, with their values in one column.
332///
333/// **The alignment is the member**, and `egui::Grid` is how this renderer gets
334/// it: a grid measures its widest cell per column and lays every row to that,
335/// which is the same answer `max-content` gives a webview and padding gives a
336/// terminal. Five goingson panes were drawing a row per fact, and every value
337/// started after its own label.
338///
339/// The grid is not striped. `Grid::striped` is the obvious reach and it is
340/// wrong here: a stripe says "these rows are a series you scan down", which is
341/// a table's claim. A pane of facts is one object read as a whole.
342///
343/// The label reads back and the value takes content, which is `figure`'s rule
344/// for a value against its caption. A fact with nothing to say never arrives:
345/// `Node::facts` drops it as it builds.
346pub fn facts(ui: &mut Ui, facts: &[Fact<'_>], palette: &Palette, id: impl Into<egui::Id>) {
347    egui::Grid::new(id.into())
348        .num_columns(2)
349        .striped(false)
350        .show(ui, |ui| {
351            for fact in facts {
352                ui.label(RichText::new(fact.label).color(palette.content_muted));
353                ui.label(RichText::new(fact.value).color(palette.content));
354                ui.end_row();
355            }
356        });
357}
358
359pub fn figure(
360    ui: &mut Ui,
361    figure: &Figure<'_>,
362    palette: &Palette,
363    style: &WidgetStyle,
364) -> Response {
365    ui.with_layout(Layout::top_down(Align::Min), |ui| {
366        let value = match figure.change {
367            Some(change) => format!("{} {change}", figure.value),
368            None => figure.value.to_owned(),
369        };
370        let size = egui::TextStyle::Body.resolve(ui.style()).size * style.figure_scale;
371        let shown = ui.label(
372            RichText::new(value)
373                .color(palette.tone(figure.tone))
374                .size(size)
375                .strong(),
376        );
377        ui.add_space(style.figure_gap);
378        ui.label(RichText::new(figure.caption).color(palette.content_muted));
379        shown
380    })
381    .inner
382}
383
384/// What a host can see about a wait that is running.
385///
386/// Both halves are optional because both are the host's to observe and neither
387/// is derivable from the description. `makeover_layout::Awaiting` says how big
388/// the payload is; nothing in a description can say how much of it has landed,
389/// because that is a fact about a transfer in flight.
390#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
391pub struct Progress {
392    /// How much has arrived, in whatever unit the description counted.
393    ///
394    /// `None` means nothing is watching the transfer, which is the common case
395    /// and is what keeps the bar from being drawn out of a total alone.
396    pub delivered: Option<u64>,
397    /// How long the wait has lasted so far.
398    ///
399    /// The one time value a wait is allowed to show. Never a remaining time and
400    /// never a rate: see [`awaiting`].
401    pub elapsed: Option<Duration>,
402}
403
404/// The activity mark: one small square, blinking.
405///
406/// Rule 2 of wiki `loading-and-progress-standard`, and the thing that replaced
407/// `Ui::spinner` here. A spinner turns at a rate it invented and reads as
408/// progress; this claims nothing beyond "something is happening", which is the
409/// whole of what an unmeasured wait knows.
410///
411/// **`reduced` stills the mark rather than removing it.** egui has no
412/// `prefers-reduced-motion`, so the preference arrives as a bool from whatever
413/// the host asked its own platform, exactly as `makeover_timing::activity_blink`
414/// is shaped for. A still mark still says something is happening; hiding it
415/// would answer a request nobody made.
416///
417/// The cadence is `makeover_timing::Cadence::Activity` and is not a number this
418/// crate chooses, so a browser, a terminal and an egui window blink together.
419///
420/// Repaint is asked for at the next flip rather than every frame: a blinking
421/// mark should not turn a window that is otherwise idle into one that renders
422/// continuously.
423pub fn activity(ui: &mut Ui, reduced: bool, palette: &Palette, style: &WidgetStyle) -> Response {
424    let (rect, response) = ui.allocate_exact_size(Vec2::splat(style.mark_size), Sense::hover());
425    let lit = match activity_blink(reduced) {
426        // Still, and lit. The state the mark holds when nothing may move.
427        None => true,
428        Some(half) => {
429            let half = half.as_secs_f64();
430            // A cadence of zero would divide by nothing and blink infinitely
431            // fast, which is the one value the token cannot mean.
432            if half <= 0.0 {
433                true
434            } else {
435                let phase = ui.input(|input| input.time).rem_euclid(half * 2.0);
436                let lit = phase < half;
437                let next = if lit { half } else { half * 2.0 } - phase;
438                ui.ctx()
439                    .request_repaint_after(Duration::from_secs_f64(next.max(0.0)));
440                lit
441            }
442        }
443    };
444    // Lit is the accent, dark is the trough it sits in. Not "drawn and not
445    // drawn": a mark that vanishes half the time is a hole in the layout, and
446    // the reader loses where to look between blinks.
447    let colour = if lit { palette.action } else { palette.sunken };
448    ui.painter().rect_filled(rect, style.radius, colour);
449    response
450}
451
452/// A wait, drawn from what is actually known about it.
453///
454/// The branch is `Awaiting::is_determinate` and one more question the
455/// description cannot answer: whether anything is watching the transfer. A bar
456/// needs both a total and a numerator, so a described amount with no
457/// [`Progress::delivered`] beside it draws the mark, not an empty trough that
458/// implies someone is counting.
459///
460/// **What the bar may not do**, from rule 1 of wiki
461/// `loading-and-progress-standard` and from `Awaiting`'s own docs: what is done
462/// over what there is, plus the time it has taken. Never a remaining time, an
463/// arrival time, or a rate extrapolated forward. A prediction is wrong the
464/// moment the transfer stalls, and being confidently wrong is worse than being
465/// honestly indeterminate.
466///
467/// The reading is the two raw numbers, as [`meter`] does it. The unit is the
468/// app's — bytes for an upload, rows for an import — and a renderer that
469/// guessed at one would be formatting a quantity it was deliberately not told
470/// about.
471pub fn awaiting(
472    ui: &mut Ui,
473    awaiting: Awaiting,
474    progress: Progress,
475    reduced: bool,
476    palette: &Palette,
477    style: &WidgetStyle,
478) -> Response {
479    let (Some(total), Some(done)) = (awaiting.amount, progress.delivered) else {
480        return activity(ui, reduced, palette, style);
481    };
482    let width = style
483        .meter_width
484        .unwrap_or_else(|| ui.available_width().max(1.0));
485    ui.horizontal(|ui| {
486        let (rect, response) =
487            ui.allocate_exact_size(Vec2::new(width, style.meter_height), Sense::hover());
488        ui.painter().rect_filled(rect, style.radius, palette.sunken);
489        // A total of zero is no payload rather than a finished one, which is
490        // `meter`'s reading of the same case. Over-delivery clamps for the same
491        // reason it does there: a rect cannot be longer than itself.
492        let share = if total == 0 {
493            0.0
494        } else {
495            #[expect(
496                clippy::cast_precision_loss,
497                reason = "a byte count past 2^53 is not a wait anyone is watching a bar for"
498            )]
499            let share = (done as f64 / total as f64).min(1.0);
500            share
501        };
502        #[expect(
503            clippy::cast_possible_truncation,
504            reason = "a share is 0..=1 and the product is a width in points"
505        )]
506        let filled = (f64::from(rect.width()) * share) as f32;
507        if filled > 0.0 {
508            let mut fill = rect;
509            fill.set_width(filled);
510            ui.painter().rect_filled(fill, style.radius, palette.action);
511        }
512        let reading = match progress.elapsed {
513            Some(elapsed) => format!("{done}/{total}  {}s", elapsed.as_secs()),
514            None => format!("{done}/{total}"),
515        };
516        ui.label(RichText::new(reading).color(palette.content_muted));
517        response
518    })
519    .inner
520}
521
522/// A chart, as bars standing on a shared axis.
523///
524/// The webview's drawing rather than the terminal's: this renderer paints into
525/// a rectangle it asks for, so columns cost it nothing and are what a reader
526/// expects of a chart. `makeover-tui` lays its bars down instead, because a
527/// terminal has rows to spend and cells to draw with; both are honest answers
528/// to the same description and neither is the other's fallback.
529///
530/// # The axis is the caller's height and the description's maximum
531///
532/// [`WidgetStyle::chart_height`] says how tall the figure stands and
533/// [`Chart::most`] says what a full bar means, which is the same split
534/// `--chart-height` and `--most` make in the stylesheet. An axis of zero draws
535/// its bars at nothing rather than dividing by it.
536///
537/// [`Bar::note`] is not painted. There is nowhere to put it without a hover
538/// surface this crate does not own, and the reading is the fact worth the room.
539pub fn chart(
540    ui: &mut Ui,
541    chart: &Chart<'_>,
542    bars: &[Bar<'_>],
543    palette: &Palette,
544    style: &WidgetStyle,
545) -> Response {
546    let width = ui.available_width().max(1.0);
547    let (rect, response) =
548        ui.allocate_exact_size(Vec2::new(width, style.chart_height), Sense::hover());
549
550    // The places on the axis take a band at the bottom, and the bars stand on
551    // top of it. Reserved out of the figure's own height rather than added to
552    // it, so `chart_height` is what a caller laying out a screen can measure
553    // against -- the same promise `--chart-height` makes in the stylesheet.
554    let font = egui::TextStyle::Small.resolve(ui.style());
555    let band = ui.text_style_height(&egui::TextStyle::Small);
556    let floor = (rect.bottom() - band).max(rect.top());
557    let standing = floor - rect.top();
558
559    if bars.is_empty() {
560        return response;
561    }
562
563    #[expect(
564        clippy::cast_precision_loss,
565        reason = "a bar count is small and this is a width in points"
566    )]
567    let each = rect.width() / bars.len() as f32;
568    for (index, bar) in bars.iter().enumerate() {
569        #[expect(
570            clippy::cast_precision_loss,
571            reason = "an index into the bars, which are few"
572        )]
573        let left = rect.left() + each * index as f32;
574        let reached = standing * bar.fraction(chart);
575        let mut column = egui::Rect::from_min_size(
576            egui::Pos2::new(left, floor - reached),
577            Vec2::new(each, reached),
578        );
579        // A bar of nothing still says it is there, which is what the
580        // stylesheet's `min-height` does in the other renderer.
581        if column.height() < 1.0 {
582            column.set_top(floor - 1.0);
583        }
584        ui.painter()
585            .rect_filled(column, style.radius, palette.tone(chart.tone));
586
587        // Centred under the column it belongs to. Drawn by the painter rather
588        // than laid out as a row of labels, because a row lays itself out and
589        // the labels would then sit where the text put them instead of under
590        // their own bars, which is the one thing a place on an axis has to do.
591        ui.painter().text(
592            egui::Pos2::new(left + each / 2.0, floor),
593            egui::Align2::CENTER_TOP,
594            bar.at,
595            font.clone(),
596            palette.content_muted,
597        );
598    }
599
600    response
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606
607    /// What the accessibility tree says a widget drew.
608    fn announced(
609        draw: impl FnMut(&mut Ui),
610    ) -> Vec<(
611        egui::accesskit::Role,
612        String,
613        Option<egui::accesskit::Toggled>,
614    )> {
615        let ctx = egui::Context::default();
616        ctx.enable_accesskit();
617        let mut draw = draw;
618        let input = || egui::RawInput {
619            screen_rect: Some(egui::Rect::from_min_size(
620                egui::Pos2::ZERO,
621                egui::vec2(600.0, 400.0),
622            )),
623            ..Default::default()
624        };
625        let _ = ctx.run_ui(input(), &mut draw);
626        let out = ctx.run_ui(input(), &mut draw);
627        out.platform_output
628            .accesskit_update
629            .expect("accesskit is on")
630            .nodes
631            .iter()
632            .map(|(_, node)| {
633                (
634                    node.role(),
635                    node.label()
636                        .or_else(|| node.value())
637                        .unwrap_or_default()
638                        .to_owned(),
639                    node.toggled(),
640                )
641            })
642            .collect()
643    }
644
645    #[test]
646    fn a_chip_is_announced_as_a_control_and_says_whether_it_is_held() {
647        // A token paints its own text onto its own rect, so before 2026-08-22
648        // it reached the tree as nothing: pressable by a mouse and invisible to
649        // everything else.
650        let p = palette();
651        let style = WidgetStyle::default();
652        let drawn = announced(|ui| {
653            token(
654                ui,
655                "C#",
656                Token::Chip { removable: false },
657                Tone::Neutral,
658                true,
659                &p,
660                &style,
661            );
662        });
663
664        let chip = drawn
665            .iter()
666            .find(|(role, name, _)| *role == egui::accesskit::Role::Button && name == "C#")
667            .unwrap_or_else(|| panic!("the chip is not in the tree: {drawn:?}"));
668        assert_eq!(
669            chip.2,
670            Some(egui::accesskit::Toggled::True),
671            "a latched chip is held down and says so: {drawn:?}"
672        );
673    }
674
675    #[test]
676    fn a_badge_is_announced_as_the_text_it_is() {
677        // Not a control, and not nothing either: a badge is a word on the
678        // screen and painting it is not the same as saying it.
679        let p = palette();
680        let style = WidgetStyle::default();
681        let drawn = announced(|ui| {
682            token(ui, "wav", Token::Badge, Tone::Neutral, false, &p, &style);
683        });
684
685        assert!(
686            drawn
687                .iter()
688                .any(|(role, name, _)| *role == egui::accesskit::Role::Label && name == "wav"),
689            "{drawn:?}"
690        );
691        assert!(
692            !drawn
693                .iter()
694                .any(|(role, _, _)| *role == egui::accesskit::Role::Button),
695            "a badge answers nothing and must not claim to: {drawn:?}"
696        );
697    }
698
699    fn palette() -> Palette {
700        use egui::Color32;
701        Palette {
702            page: Color32::from_rgb(1, 1, 1),
703            raised: Color32::from_rgb(2, 2, 2),
704            overlay: Color32::from_rgb(3, 3, 3),
705            well: Color32::from_rgb(4, 4, 4),
706            sunken: Color32::from_rgb(5, 5, 5),
707            bevel_light: Color32::from_rgb(6, 6, 6),
708            bevel_dark: Color32::from_rgb(7, 7, 7),
709            elevation: Color32::from_black_alpha(40),
710            content: Color32::from_rgb(20, 20, 20),
711            content_secondary: Color32::from_rgb(120, 120, 120),
712            content_muted: Color32::from_rgb(21, 21, 21),
713            action: Color32::from_rgb(22, 22, 22),
714            content_on_action: Color32::from_rgb(250, 250, 250),
715            danger: Color32::from_rgb(23, 23, 23),
716            success: Color32::from_rgb(24, 24, 24),
717            warning: Color32::from_rgb(25, 25, 25),
718            info: Color32::from_rgb(26, 26, 26),
719            border: Color32::from_rgb(200, 200, 200),
720            info_surface: Color32::from_rgb(201, 201, 201),
721            success_surface: Color32::from_rgb(202, 202, 202),
722            warning_surface: Color32::from_rgb(203, 203, 203),
723            danger_surface: Color32::from_rgb(204, 204, 204),
724            row_stripe: Color32::from_rgb(205, 205, 205),
725            row_hover: Color32::from_rgb(206, 206, 206),
726            row_rule: Color32::from_rgb(207, 207, 207),
727            row_selected: Color32::from_rgb(208, 208, 208),
728        }
729    }
730
731    #[test]
732    fn every_tone_resolves_and_no_two_share_a_colour() {
733        // The reason the three status intents arrived together: a resolver
734        // missing one has to invent a colour for it.
735        let p = palette();
736        let all = [
737            p.tone(Tone::Neutral),
738            p.tone(Tone::Info),
739            p.tone(Tone::Success),
740            p.tone(Tone::Warning),
741            p.tone(Tone::Danger),
742        ];
743        for (i, a) in all.iter().enumerate() {
744            for b in &all[i + 1..] {
745                assert_ne!(a, b, "two tones resolved to one colour");
746            }
747        }
748        assert_eq!(p.tone(Tone::Neutral), p.content, "neutral is ordinary text");
749    }
750
751    #[test]
752    fn a_meter_draws_and_an_overrun_does_not_panic() {
753        // `done` may exceed `total`, which is the case Meter's own docs call
754        // the one worth drawing. The fill clamps; the reading does not.
755        let p = palette();
756        let style = WidgetStyle::default();
757        egui::__run_test_ui(|ui| {
758            meter(ui, &Meter::new(3, 6), &p, &style);
759            meter(ui, &Meter::new(9, 6), &p, &style);
760            // No set, rather than a complete one.
761            meter(ui, &Meter::new(0, 0), &p, &style);
762            // The overflow `makeover-layout` pins on its own side.
763            meter(ui, &Meter::new(u32::MAX, u32::MAX), &p, &style);
764        });
765    }
766
767    #[test]
768    fn a_wait_draws_a_bar_only_when_something_is_counting_it() {
769        // The described total is half of what a bar needs. Without a numerator
770        // the honest drawing is the mark, not an empty trough implying that
771        // someone is watching bytes land.
772        let p = palette();
773        let style = WidgetStyle::default();
774        egui::__run_test_ui(|ui| {
775            awaiting(
776                ui,
777                Awaiting::unmeasured(),
778                Progress::default(),
779                false,
780                &p,
781                &style,
782            );
783            awaiting(
784                ui,
785                Awaiting::of(41_943_040),
786                Progress::default(),
787                false,
788                &p,
789                &style,
790            );
791            awaiting(
792                ui,
793                Awaiting::of(41_943_040),
794                Progress {
795                    delivered: Some(10_485_760),
796                    elapsed: Some(Duration::from_secs(3)),
797                },
798                false,
799                &p,
800                &style,
801            );
802            // A zero payload is no payload, and over-delivery clamps.
803            awaiting(
804                ui,
805                Awaiting::of(0),
806                Progress {
807                    delivered: Some(9),
808                    elapsed: None,
809                },
810                false,
811                &p,
812                &style,
813            );
814            awaiting(
815                ui,
816                Awaiting::of(4),
817                Progress {
818                    delivered: Some(9),
819                    elapsed: None,
820                },
821                false,
822                &p,
823                &style,
824            );
825        });
826    }
827
828    #[test]
829    fn reduced_motion_stills_the_mark_and_does_not_remove_it() {
830        // `activity_blink(true)` is None, which means lit and still. A renderer
831        // that drew nothing would have answered a request nobody made.
832        let p = palette();
833        let style = WidgetStyle::default();
834        egui::__run_test_ui(|ui| {
835            let still = activity(ui, true, &p, &style);
836            let blinking = activity(ui, false, &p, &style);
837            assert_eq!(
838                still.rect.size(),
839                blinking.rect.size(),
840                "the mark occupies the same space either way"
841            );
842        });
843    }
844
845    #[test]
846    fn a_chip_answers_a_click_and_a_badge_does_not() {
847        // `Token::interactive` is the whole difference between the members, and
848        // the sense is what makes egui agree with it.
849        let p = palette();
850        let style = WidgetStyle::default();
851        egui::__run_test_ui(|ui| {
852            let badge = token(ui, "beta", Token::Badge, Tone::Info, false, &p, &style);
853            assert!(!badge.sense.senses_click(), "a badge answers no click");
854
855            let chip = token(
856                ui,
857                "drums",
858                Token::Chip { removable: false },
859                Tone::Neutral,
860                false,
861                &p,
862                &style,
863            );
864            assert!(chip.sense.senses_click(), "a chip answers a click");
865        });
866    }
867
868    #[test]
869    fn a_disabled_control_is_drawn_and_does_not_answer() {
870        // Present, visible, and not answering. Through
871        // `State::suppresses_interaction` rather than a second reading here.
872        let p = palette();
873        let style = WidgetStyle::default();
874        egui::__run_test_ui(|ui| {
875            let live = act(ui, &Act::new("Save"), &p, &style);
876            assert!(live.enabled());
877
878            let gone = act(ui, &Act::new("Save").state(State::Disabled), &p, &style);
879            assert!(!gone.enabled(), "a disabled control still answers");
880        });
881    }
882
883    #[test]
884    fn a_control_shows_the_key_the_description_named() {
885        // `Act::key` was written for a terminal before there was one. A desktop
886        // app has keys too, so this is its second reader.
887        let p = palette();
888        let style = WidgetStyle::default();
889        egui::__run_test_ui(|ui| {
890            act(ui, &Act::new("New").key("n"), &p, &style);
891            act(ui, &Act::new("New"), &p, &style);
892        });
893    }
894
895    #[test]
896    fn a_figure_draws_its_movement_beside_its_value() {
897        let p = palette();
898        let style = WidgetStyle::default();
899        egui::__run_test_ui(|ui| {
900            figure(ui, &Figure::new("17", "Current streak"), &p, &style);
901            figure(
902                ui,
903                &Figure::new("17", "Current streak")
904                    .change("+3")
905                    .tone(Tone::Success),
906                &p,
907                &style,
908            );
909        });
910    }
911}