Skip to main content

makeover_immediate/
lib.rs

1//! The immediate-mode renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Named for the mode, not the library, the way `makeover-tui` is named for
6//! the target and not for ratatui. Immediate mode is the constraint that
7//! actually separates this renderer from the other two, and egui is the
8//! backend it is written against.
9//!
10//! It is the harshest renderer the description has to survive: no
11//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
12//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
13//! A two-tone lit edge is not something egui can be configured into producing,
14//! so it gets painted by hand here, once, instead of in every consuming app.
15//!
16//! # What this crate does and does not own
17//!
18//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
19//! for a filled region. It owns no colours and no sizes, and no longer owns a
20//! substitution: it briefly supplied the page for a well, which was a stand-in
21//! for `surface-well` before makeover derived it, and every consumer reads the
22//! real token now. [`Palette`] is supplied by the caller,
23//! already resolved, and every radius, margin and stroke width arrives in
24//! [`FrameStyle`].
25//!
26//! That split is why the crate has no dependency on `makeover` itself: the app
27//! already resolves a theme, and coupling a renderer to a colour crate's
28//! version would buy nothing.
29//!
30//! # The cascade is the real difference
31//!
32//! A stylesheet can say "a pressed button inverts its bevel" once and let the
33//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
34//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
35//! the decision from being re-derived per widget.
36//!
37//! # 0.11.0: the overlay becomes reachable
38//!
39//! 0.10.0 answered what overlaying means in immediate mode with
40//! [`Palette::cast`], and nothing could ask: the description had no
41//! `Depth::Overlay` until `makeover-layout` 0.14.0, so the answer sat beside a
42//! question that could not be posed. [`frame`] now hands the cast shadow to the
43//! `egui::Frame` for any depth whose fill is [`Fill::Overlay`], keyed off the
44//! fill rather than the variant.
45//!
46//! The same release brings `makeover_layout::CellPart`, which 0.11.0 carried
47//! and did not draw. [`table`] draws it, below.
48//!
49//! # 0.12.0: the table
50//!
51//! [`table`] is the vocabulary 0.11.0 took without using. The consumer is
52//! audiofiles, whose file list is the only table in the tree exercising all four
53//! of what the description says about one at once: sortable headings with
54//! carets, fixed and remainder tracks, and buttons inside cells.
55//!
56//! Two things it forces, both named where they land:
57//!
58//! - **`egui_extras`**, this crate's first dependency past egui. egui has no
59//!   table, and `Grid` gives no per-column sizing, no sticky header and no
60//!   scroll sync, which is why audiofiles reached for `egui_extras` rather than
61//!   building on `Grid`. A third answer here would reimplement that crate worse.
62//! - **[`Palette::action`]**, on the footing [`Palette::content`] arrived on: a
63//!   link in a cell is the first thing here needing the action intent.
64//!
65//! Narrowing works differently from the terminal's and the module header says
66//! why: a content column cannot be measured before the app's closure has drawn
67//! it, so `egui_extras` sizes it and the declared floor budgets it.
68//!
69//! # 0.13.0: what the adoption found missing
70//!
71//! 0.12.0 shipped [`table`] before audiofiles had taken it, and taking it found
72//! three things the file list already did that the function could not say. All
73//! three are host idiom rather than description, which is why they land here and
74//! not in `makeover-layout`, and all three are answered on a handle the app
75//! never sees: the `egui_extras` row and builder this crate owns. That is
76//! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer
77//! owes it.
78//!
79//! - **A selected row.** [`table::Body::selected`], a predicate asked per row,
80//!   because `set_selected` is a method on the row. Without it a file list has
81//!   no way to show what is selected, which is most of what a file list does.
82//! - **Scrolling a row into view.** [`table::Body::scroll_to`], because
83//!   `scroll_to_row` is a method on the builder. A keyboard cursor that moves
84//!   off-screen and stays there is the bug this prevents.
85//! - **Dragging a divider.** [`table::TableStyle::resizable`], which passes the
86//!   test `sticky_header` failed in 0.12.0: egui_extras offers two settings here
87//!   and a renderer can honestly make either choice.
88//!
89//! A fourth was found and is not a knob. Cells are centred on the row's centre
90//! line, always, because there is no second honest answer and egui's own default
91//! (top-aligned) is the one thing it cannot be.
92//!
93//! [`table::Body`] is also what splits a table's per-frame facts from its
94//! description and from its style. A row count, a selection and a scroll request
95//! are none of them style, and none of them survive the frame.
96//!
97//! # 0.18.0: the nodes that were not fields, tables or frames
98//!
99//! [`widget`] draws a meter, a token, a control and a figure. `makeover-tui` has
100//! had all four for releases and this crate had none of them, which stayed
101//! invisible while the only consumer was an app calling [`field`] and [`table`]
102//! directly. It stopped being invisible the moment anything tried to draw a
103//! whole `quasi_router::Screen` in egui: the four are ordinary nodes, so a
104//! screen walk would have had to draw them itself, one copy per consumer.
105//!
106//! [`Palette`] grows the three status intents with it. They arrive together
107//! rather than one per widget for the reason [`Palette::fill`] is an `Option`:
108//! `Tone` is five members wide, and a resolver missing one has to invent a
109//! colour, which is the substitution 0.2.0 spent a release removing.
110//!
111//! # Forms
112//!
113//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
114//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
115//! of them laid down a column in [`group`]. Before it, a description saying
116//! "text field, labelled, required, with this hint" had no way to become a
117//! widget here, and audiofiles' forms stayed hand-rolled.
118//!
119//! `makeover-webview` got there first and its form emitter is the precedent
120//! followed rather than re-derived, including the parts that are bug fixes: a
121//! select handed a value none of its options carries keeps that value visible
122//! instead of silently reading as the first option, which is a save-the-wrong-
123//! thing bug goingson hit for real.
124//!
125//! What differs is forced by the mode and not chosen:
126//!
127//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
128//!   and the widget writes through it. There is no DOM to read back out of,
129//!   which is also why the description deliberately does not carry the value.
130//! - **A text control is drawn as a well and a select is not.** The description
131//!   holds that a well is for anything the user looks *into*, and a text field
132//!   is its own example; a select and a checkbox are pressed rather than looked
133//!   into, so they keep egui's own control painting.
134//! - **Focus is not describable, and egui owns all of it here.** **Reach**,
135//!   **focus** and the **focus ring** are this renderer's three answers and
136//!   egui already has all three: its own id stack decides what is reachable,
137//!   its own state decides what holds the keyboard, and it paints exactly one
138//!   ring. A description states none of them — `makeover_layout` removed the
139//!   member that used to try in 0.19.0 — and drawing a second ring on top of
140//!   egui's would break the one-ring rule it would have come from. The terms
141//!   are defined once in `makeover_layout`'s crate header, "Reach, focus and
142//!   the focus ring". [`makeover_layout::State::Disabled`] *is* drawn, because
143//!   egui has no opinion about it until told.
144//! - **App-level chrome is not drawn here, and it is not this crate's to
145//!   draw.** `quasi-router` names the affordances that outlive one screen: a
146//!   `Chrome` of key bindings, and an `Outcome::Over` for a screen drawn over
147//!   another. Both are answered by `quasi-webview` and `quasi-tui`, and neither
148//!   is answerable here, because this crate depends on `makeover-layout` and
149//!   not on `quasi-router` — it is the peer of `makeover-webview` and
150//!   `makeover-tui`, one layer below the renderers that consume a `Screen`.
151//!   What is missing is the egui crate at *that* layer, which does not exist:
152//!   nothing renders a quasi `Screen` in egui at all, and chrome is one item on
153//!   the list such a crate would owe. Said here because this is where a reader
154//!   looks for it, and because the silent version reads as "egui does not need
155//!   a palette" rather than "nobody has built the renderer yet".
156
157//! # 0.33.0: an interval is a sixth control shape
158//!
159//! `makeover-layout` 0.34.0's [`FieldKind::Interval`], drawn as `Control::Spanned`:
160//! two drag boxes on one row with the word `to` between them.
161//!
162//! - **Dragged rather than typed**, because that is what these controls already
163//!   were. audiofiles' six filter axes are `DragValue` pairs sharing an extent,
164//!   a speed and a suffix, and describing them into two text boxes would be a
165//!   port that cost the app a control.
166//! - **One row, not two wells stacked.** Two wells are two questions on screen
167//!   whatever the description says, and the arrangement is the whole content of
168//!   the kind.
169//! - **An empty end reads as the bound it stands for.** An unset minimum sits
170//!   on the low edge and stores no filter, which is what the shipped control
171//!   did; egui's `DragValue` has no empty state, and a text box in its place
172//!   would be the regression above. With no extent to fall back on it reads
173//!   zero -- the one number this renderer invents, invented where the
174//!   description declined to say anything.
175//! - **The word rather than a dash**, which on a signed axis is a minus sign.
176//!   audiofiles filters loudness in dBFS.
177//!
178//! `Axis` holds the four facts both boxes share, because they are one axis:
179//! reading `min`, `max`, `step` and `unit` once is what stops the two ends
180//! drifting apart.
181//!
182//! # 0.32.0: a number draws its unit
183//!
184//! `makeover-layout` 0.33.0's [`Field::unit`], and this host is the one the
185//! member was argued from: egui's `Slider` already draws a suffix beside its
186//! readout, which is where these controls put the unit before they were
187//! described and is somewhere a label cannot reach.
188//!
189//! So a slider takes it as a suffix, inside the control. A typed number has no
190//! readout of its own and takes it as a muted label after the box. Every other
191//! kind ignores it, and the description says which those are --
192//! `FieldKind::measurable`, rather than a `matches!` kept here.
193//!
194//! # 0.31.0: the slider's track is a curve
195//!
196//! `makeover-layout` 0.32.0 says what a slider is: a fraction and a function
197//! taking numbers to numbers, with `min` and `max` being `f(0)` and `f(1)`
198//! rather than the control's extent. This host has the easiest job of the
199//! three, because egui already has the control -- `Slider::logarithmic` is a
200//! constant-ratio track, so the mapping is a builder call rather than an
201//! arithmetic of its own.
202//!
203//! Two things worth knowing. The granularity moved onto the curve, so a range
204//! reads `Field::curve.step()` and every other kind still reads `Field::step`;
205//! the step is in the value's own units under either curve, so the display
206//! precision is derived exactly as before. And the fallback for a ratio curve
207//! across zero is asked of `Curve::is_ratio` rather than matched on the
208//! variant, so this renderer and a terminal cannot disagree about when a
209//! logarithmic request is honoured.
210//!
211//! # 0.28.0: the slider, the unanswered chooser, and the option that is not
212//! offered yet
213//!
214//! Three things `makeover-layout` 0.28.0 lets a description say, all three
215//! found by audiofiles' forms port hitting a wall it could not describe its way
216//! past.
217//!
218//! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, and
219//!   the first one added since 0.5.0. egui has `Slider` and this crate had no
220//!   way to be asked for one, so four sliders in the only consuming app stayed
221//!   hand-rolled against a vocabulary that could not name them. A range missing
222//!   an end falls back to a well rather than to invented bounds, which is what
223//!   `makeover_layout::Field::bounded` is for.
224//! - **`Field::placeholder` finally reads on a chooser.** It was sayable and
225//!   this renderer ignored it, so a select with nothing chosen showed an empty
226//!   box. Nothing new is described; the renderer caught up.
227//! - **`Choice::unavailable` is drawn rather than dropped.** The option stays
228//!   in the list, inert, with its precondition beside it instead of behind a
229//!   hover — a greyed row with no reason reads as a dead end, which is the
230//!   whole finding.
231//!
232//! The value still arrives as a `&mut String` and a slider is a number, so the
233//! parse and the write-back are this renderer's, and the write happens only on
234//! a real drag: a value the app put there that this host cannot read survives
235//! being looked at.
236
237#![forbid(unsafe_code)]
238
239use egui::{
240    Color32, ComboBox, CornerRadius, DragValue, Margin, Painter, Rect, Response, RichText, Shape,
241    Slider, Stroke, TextEdit, Ui,
242};
243use makeover_layout::{
244    Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, ThemeVariant, Tone,
245};
246use std::ops::RangeInclusive;
247
248/// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
249pub mod table;
250pub mod widget;
251
252/// The resolved colours this renderer needs, as flat values.
253///
254/// Built by the app from whatever it already uses to resolve a theme, then
255/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
256/// painted per widget per frame, and a map lookup per edge is a cost with
257/// nothing to show for it.
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub struct Palette {
260    /// `surface-page`.
261    pub page: Color32,
262    /// `surface-raised`.
263    pub raised: Color32,
264    /// `surface-overlay`.
265    pub overlay: Color32,
266    /// `surface-well`.
267    ///
268    /// Required, not optional. makeover derives it for every theme from 2.3.0,
269    /// so a resolved palette without a well is not a thing that exists here.
270    /// It was an `Option` while that was untrue, and this renderer substituted
271    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
272    /// since a terminal can have the colour and still be unable to show it.
273    pub well: Color32,
274    /// `surface-sunken`.
275    ///
276    /// A surface set back from the one it sits on, by colour and nothing else.
277    /// Not a well: a well is a hole with an edge, and this has no edge. An
278    /// immediate-mode renderer paints an arbitrary rect, so unlike
279    /// `makeover-tui` it has no excuse for declining this one.
280    ///
281    /// Required rather than optional, on the same footing as `well`: all 31
282    /// themes makeover embeds author it.
283    pub sunken: Color32,
284    /// `bevel-light`.
285    pub bevel_light: Color32,
286    /// `bevel-dark`.
287    pub bevel_dark: Color32,
288    /// `elevation`.
289    ///
290    /// What a surface that floats OVER the page is cast onto it with. The one
291    /// intent here that is about a surface's relationship to the page rather
292    /// than about the surface, which is why it is a translucent near-black on
293    /// every theme rather than something read off the palette's own ramp.
294    ///
295    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
296    /// surface *in* the layout takes a bevel, and reaching for this on a panel
297    /// or a card is how a pre-Platinum look survives a conversion under a new
298    /// name.
299    ///
300    /// egui has a real answer for this where a terminal does not: see
301    /// [`Palette::cast`], which is the shadow to hand an
302    /// [`egui::Frame`](egui::Frame).
303    pub elevation: Color32,
304    /// `content`.
305    ///
306    /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
307    /// thing here that draws any: until then this crate painted surfaces and
308    /// edges and let the caller's own egui visuals answer for text.
309    pub content: Color32,
310    /// `content-secondary`.
311    ///
312    /// Inactive but usable: it still answers a press. The middle tone of the
313    /// three (wiki `three-tone-convention`), and the one an unchosen option in
314    /// a choice field takes. Added 0.26.0 for that widget, which drew every
315    /// option at full `content` and so said nothing about which one was
316    /// chosen beyond the dot egui paints.
317    ///
318    /// Not [`content_muted`](Self::content_muted), which carries a claim:
319    /// `State::Disabled` resolves to it, so a live control wearing it tells the
320    /// user it will not answer. `makeover-tui` draws the same widget the same
321    /// way from `makeover-tui@230bf63`.
322    ///
323    /// A step of `content` toward the page, derived at load by `makeover`
324    /// rather than authored, so it is read off the resolved theme here like
325    /// any other token and never re-derived.
326    pub content_secondary: Color32,
327    /// `content-muted`.
328    ///
329    /// A field's hint, and what
330    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
331    /// resolves to. Both readings come from the description rather than from
332    /// here: `State::Disabled` names this intent by token.
333    pub content_muted: Color32,
334    /// `action-primary`.
335    ///
336    /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
337    /// reason `content` was added 0.5.0 with the field renderer: a link in a
338    /// cell is the first thing here that needs the action intent, and a palette
339    /// should carry what is used.
340    ///
341    /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
342    /// separate. A cell holding a control took the cell's text colour until the
343    /// description could say otherwise, which is the drift `makeover-layout`
344    /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
345    pub action: Color32,
346    /// `danger`.
347    ///
348    /// A field's error message, a destructive control, a bar that has run over.
349    pub danger: Color32,
350    /// `success`.
351    ///
352    /// Added 0.18.0 with [`widget`], which is the first thing here that draws a
353    /// [`Tone`]. The three status intents arrive together and not one at a
354    /// time: [`Tone`] is five members wide and a resolver missing one has to
355    /// invent a colour for it, which is the substitution this crate spent
356    /// 0.2.0 removing from [`Palette::fill`].
357    pub success: Color32,
358    /// `warning`.
359    pub warning: Color32,
360    /// `info`.
361    pub info: Color32,
362}
363
364impl Palette {
365    /// Resolve a surface intent, or `None` for one this renderer does not know.
366    ///
367    /// A plain lookup. There is still no substitution: the old one existed only
368    /// while `surface-well` was underived, and every consumer reads the real
369    /// token now.
370    ///
371    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
372    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
373    /// stay total by inventing a colour for a member it has never heard of.
374    /// That is the substitution this crate spent 0.2.0 removing, so the return
375    /// type moved instead. Every member the description has today is answered
376    /// with `Some`.
377    #[must_use]
378    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
379        match fill {
380            Fill::Page => Some(self.page),
381            Fill::Raised => Some(self.raised),
382            Fill::Overlay => Some(self.overlay),
383            Fill::Well => Some(self.well),
384            Fill::Sunken => Some(self.sunken),
385            _ => None,
386        }
387    }
388
389    /// The colour a [`Tone`] reads as.
390    ///
391    /// Total, unlike [`fill`](Self::fill), and the difference is not an
392    /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
393    /// description layer settled tone at five members and grows surfaces, so a
394    /// total function here cannot be made to invent a colour by an upstream
395    /// release the way a total `fill` could.
396    ///
397    /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
398    /// its own, which is what "an ordinary fact" means: a neutral badge is text
399    /// in a box, not a fifth status.
400    #[must_use]
401    pub const fn tone(&self, tone: Tone) -> Color32 {
402        match tone {
403            Tone::Neutral => self.content,
404            Tone::Info => self.info,
405            Tone::Success => self.success,
406            Tone::Warning => self.warning,
407            Tone::Danger => self.danger,
408        }
409    }
410
411    /// The cast shadow for a surface that overlays the page.
412    ///
413    /// What "overlaying" means in immediate mode, answered rather than skipped.
414    /// egui already paints shadows for its menus and windows through
415    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
416    /// theme's tone instead of egui's own default, not to invent a painter here
417    /// the way [`paint_bevel`] had to.
418    ///
419    /// The geometry matches what `makeover-webview` composes, in points rather
420    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
421    /// menu sits just off the page rather than hovering above it.
422    ///
423    /// ```no_run
424    /// # let palette: makeover_immediate::Palette = unimplemented!();
425    /// # let ui: &mut egui::Ui = unimplemented!();
426    /// egui::Frame::popup(ui.style())
427    ///     .shadow(palette.cast())
428    ///     .show(ui, |ui| { ui.label("over the page"); });
429    /// ```
430    #[must_use]
431    pub const fn cast(&self) -> egui::Shadow {
432        egui::Shadow {
433            offset: [0, 2],
434            blur: 24,
435            spread: 0,
436            color: self.elevation,
437        }
438    }
439
440    /// Resolve a bevel edge intent.
441    #[must_use]
442    pub const fn edge(&self, edge: Edge) -> Color32 {
443        match edge {
444            Edge::Light => self.bevel_light,
445            Edge::Dark => self.bevel_dark,
446        }
447    }
448}
449
450/// The geometry a framed region is drawn with.
451///
452/// Every field is a value, which is why they all arrive from the caller:
453/// radius and border width belong to `makeover-geometry`, and margins come
454/// from its relational gaps.
455#[derive(Debug, Clone, Copy, PartialEq)]
456pub struct FrameStyle {
457    /// Corner radius. Square under the Platinum default.
458    pub radius: CornerRadius,
459    /// Inner margin between the frame and its contents.
460    pub margin: Margin,
461    /// Bevel stroke width, in points.
462    pub stroke: f32,
463}
464
465impl Default for FrameStyle {
466    /// A one-point square frame with no inner margin.
467    fn default() -> Self {
468        Self {
469            radius: CornerRadius::ZERO,
470            margin: Margin::ZERO,
471            stroke: 1.0,
472        }
473    }
474}
475
476/// Paint a two-tone edge just inside `rect`.
477///
478/// Fill first, bevel after: this adds two polylines and nothing else, so it
479/// composes over whatever is already there. That is what lets it go over an
480/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
481///
482/// Two three-point polylines meeting at opposite corners, rather than four
483/// segments, so egui mitres the corner joins instead of leaving a notch.
484///
485/// The dark polyline is drawn second, so the two corners where the runs meet
486/// take its tone. That is the right answer here rather than a concession.
487/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
488/// a renderer with room to divide one should; at the default one-point stroke
489/// the corner is a one-point square, so the division is sub-pixel and
490/// antialiasing resolves it to the same blend the mitre already gives. Splitting
491/// it would add a seam and no information. `makeover-tui` does split, because a
492/// terminal cell is large enough that not splitting costs a visible cell of edge
493/// weight — the same rule, at a resolution where it has something to say.
494pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
495    let (top_left, bottom_right) = bevel.edges();
496
497    // Inset by half a stroke so the line lands inside `rect` rather than
498    // straddling its edge, which on a fractional-scale display is the
499    // difference between one crisp pixel and two dim ones.
500    let r = rect.shrink(stroke / 2.0);
501
502    painter.add(Shape::line(
503        vec![r.left_bottom(), r.left_top(), r.right_top()],
504        Stroke::new(stroke, palette.edge(top_left)),
505    ));
506    painter.add(Shape::line(
507        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
508        Stroke::new(stroke, palette.edge(bottom_right)),
509    ));
510}
511
512/// Draw a region at a given [`Depth`]: its fill and its edge, together.
513///
514/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
515/// difference between level-with and painted-the-same-colour, and it is the
516/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
517/// page.
518pub fn frame<R>(
519    ui: &mut Ui,
520    depth: Depth,
521    palette: &Palette,
522    style: FrameStyle,
523    add_contents: impl FnOnce(&mut Ui) -> R,
524) -> R {
525    let mut f = egui::Frame::new()
526        .corner_radius(style.radius)
527        .inner_margin(style.margin);
528    // Two ways there is no fill to paint, and they collapse to the same
529    // outcome: the depth names none (Depth::Flat), or it names one this
530    // renderer cannot resolve. Either way the frame goes unfilled and the
531    // bevel below carries the depth on its own, which is the rule this
532    // module already documents for Flat.
533    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
534        f = f.fill(fill);
535    }
536    // A surface that overlays the page is cast onto it. [`Palette::cast`] has
537    // answered what that means here since 0.10.0 and nothing could reach it: a
538    // description had no way to say Overlay until makeover-layout 0.14.0, so
539    // the answer sat beside the question. Keyed off the fill rather than the
540    // variant, so it stays right for whatever else the description calls an
541    // overlay later.
542    if depth.fill() == Some(Fill::Overlay) {
543        f = f.shadow(palette.cast());
544    }
545    let framed = f.show(ui, add_contents);
546    if let Some(bevel) = depth.bevel() {
547        paint_bevel(
548            ui.painter(),
549            framed.response.rect,
550            bevel,
551            palette,
552            style.stroke,
553        );
554    }
555    framed.inner
556}
557
558/// The geometry a field group is drawn with.
559///
560/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
561/// `makeover-geometry` and arrives already resolved.
562#[derive(Debug, Clone, Copy, PartialEq)]
563pub struct FieldStyle {
564    /// The well a text control sits in.
565    pub frame: FrameStyle,
566    /// Between a field's own parts: its label, its control, its hint and its
567    /// error.
568    pub gap: f32,
569    /// Between one field and the next.
570    pub group_gap: f32,
571    /// What marks a required field, appended to its label.
572    ///
573    /// A knob rather than a constant, because it is the one piece of *copy* in
574    /// this crate and copy is not a renderer's call. A webview does not need it
575    /// at all — it emits the `required` attribute and the browser answers — so
576    /// this renderer is the first place where a compulsory field either shows
577    /// that it is or silently does not.
578    pub required_marker: &'static str,
579}
580
581impl Default for FieldStyle {
582    /// The default frame, no gaps, and an asterisk.
583    fn default() -> Self {
584        Self {
585            frame: FrameStyle::default(),
586            gap: 0.0,
587            group_gap: 0.0,
588            required_marker: "*",
589        }
590    }
591}
592
593/// What the field currently holds, borrowed from wherever the app keeps it.
594///
595/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
596/// place the two renderers are forced apart: there the value is read back out
597/// of the DOM after the fact, and here the widget writes through this borrow as
598/// it is edited. Same reason the description carries neither.
599///
600/// An enum rather than a bag of options, on the reasoning
601/// `makeover_webview::form::Value` records: a checkbox holding a string is
602/// unsayable here, where a struct would let it be said and then have to cope.
603#[derive(Debug, Default)]
604pub enum Filling<'a> {
605    /// Nothing to edit. The control is drawn and does not answer.
606    #[default]
607    Absent,
608    /// The buffer behind anything that takes typed text, a select included:
609    /// what a select holds is the `value` of one of its [`Choice`]s.
610    ///
611    /// [`Choice`]: makeover_layout::Choice
612    Text(&'a mut String),
613    /// A checkbox, on or off.
614    On(&'a mut bool),
615    /// The two buffers behind a [`FieldKind::Interval`], lower first.
616    ///
617    /// Two buffers rather than one string with a separator, which is
618    /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
619    /// interval is submitted under two names, so it is edited as two values,
620    /// and a delimiter this crate owned could appear inside either of them.
621    ///
622    /// Either end may be empty while the other stands. An open end is an
623    /// answer -- "over 120 BPM" -- rather than a half-filled box.
624    ///
625    /// Added 0.33.0 with makeover-layout 0.34.0.
626    Between {
627        /// The lower end's buffer.
628        lower: &'a mut String,
629        /// The upper end's buffer.
630        upper: &'a mut String,
631    },
632}
633
634/// The label, marked if the field is compulsory.
635fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
636    if field.required {
637        format!("{} {}", field.label, style.required_marker)
638    } else {
639        field.label.to_owned()
640    }
641}
642
643/// The four shapes a control comes in here, which is fewer than there are
644/// kinds.
645///
646/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
647/// ways egui has of asking for a value do not. Reducing the open set to this
648/// closed one in one total function is what keeps a new kind from needing a new
649/// arm at every match below.
650#[derive(Debug, Clone, Copy, PartialEq, Eq)]
651enum Control {
652    /// Typed into, so it is drawn as a well: the user looks into it.
653    Typed,
654    /// Picked from a control that shows one option at a time. Pressed rather
655    /// than looked into, so egui's own control painting stands.
656    Chosen,
657    /// Picked from options that are all on screen at once.
658    ///
659    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
660    /// apart, and holding them apart is the whole content of
661    /// [`FieldKind::Radio`]: same question, and an answer the user can read
662    /// without opening anything.
663    Listed,
664    /// Held on or off.
665    Toggled,
666    /// Dragged across an extent that is on screen the whole time.
667    ///
668    /// Apart from [`Typed`](Self::Typed) for the reason
669    /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
670    /// question means, so a well with a figure in it is not a quieter version
671    /// of this control, it is a different one.
672    Slid,
673    /// Picked from a list of themes that arrives grouped and marked.
674    ///
675    /// Apart from [`Chosen`](Self::Chosen) rather than folded into it, and the
676    /// distinction is the same one [`Listed`](Self::Listed) draws: it is not a
677    /// different question, it is a different amount of structure on screen. A
678    /// theme picker's rows carry a group heading and a contrast mark, and both
679    /// come from members [`Field::options`] does not have, so a shared arm
680    /// would be a `matches!` on the kind inside the loop rather than one arm
681    /// less.
682    ///
683    /// Added with makeover-layout 0.38.0's [`FieldKind::Theme`].
684    Themed,
685    /// Two values dragged across one axis, drawn as one question.
686    ///
687    /// Apart from [`Typed`](Self::Typed) for the reason
688    /// [`FieldKind::Interval`] is apart from `Number`: two wells one under the
689    /// other are two questions on screen, whatever the description says, and
690    /// the arrangement is the whole content of the kind.
691    Spanned,
692}
693
694/// Which shape a kind takes.
695///
696/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
697/// description since this renderer was built degrades to a text box, which
698/// accepts any value the others would, rather than to nothing drawn at all.
699///
700/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
701/// there rather than grown a shape of its own. egui's honest answer is a button
702/// that opens a native picker, which is a fifth control and a file-dialog
703/// dependency; no consumer of this crate asks for a file field yet. Same
704/// position this crate took on `Meter` at 0.10.0: the membership test is that
705/// every renderer *could* answer honestly, not that each one does on the day.
706/// A path in a text box is not nothing, and it is what an app that needs this
707/// tomorrow gets today.
708///
709/// makeover-layout 0.31.0 added `Field::accept` and `Field::multiple`, and this
710/// position is what they land on: both are the picker's arguments, and this
711/// renderer has no picker to give them to. They are not lost — the description
712/// still carries them, and the day the native dialog arrives here it is opened
713/// with them rather than with a filter written twice.
714///
715/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
716/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
717/// calendar is a sixth control and bare `egui` has none, so a typed value is
718/// the honest answer here; what the app gets is the format the description
719/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
720/// those are constants rather than a sentence. audiofiles is the only consumer
721/// of this crate and asks for neither today. A calendar popup is the upgrade
722/// whenever one does.
723///
724/// `Field::as_instant` (makeover-layout 0.37.0) is carried and not honoured, on
725/// the same footing. It asks for the typed wall-clock value to be submitted as
726/// the moment it names, and this renderer has no submission to convert on: it
727/// draws the control and the app reads the value back, so the conversion would
728/// belong wherever that read happens rather than here. What the app gets is the
729/// local value in `DATETIME_FORMAT`, which is what it got before the member
730/// existed. No described site on this host asks for it today.
731const fn control_shape(kind: FieldKind) -> Control {
732    match kind {
733        FieldKind::Select => Control::Chosen,
734        FieldKind::Radio => Control::Listed,
735        FieldKind::Checkbox => Control::Toggled,
736        FieldKind::Range => Control::Slid,
737        FieldKind::Interval => Control::Spanned,
738        FieldKind::Theme => Control::Themed,
739        _ => Control::Typed,
740    }
741}
742
743/// The shape the field actually gets, which is the kind's unless the field is
744/// missing what that shape needs.
745///
746/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
747/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
748/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
749/// inventing one would be this renderer picking bounds the app never stated and
750/// the user then dragging against them.
751///
752/// It falls back to [`Control::Typed`], which is where every kind this renderer
753/// cannot draw natively already lands: a number in a well is a true report of
754/// the value and takes any answer the slider would.
755fn shape_of(field: &Field<'_>) -> Control {
756    match control_shape(field.kind) {
757        Control::Slid if !field.bounded() => Control::Typed,
758        shape => shape,
759    }
760}
761
762/// The unit to draw beside this field's value, if there is one to draw.
763///
764/// Two conditions rather than one: the field has to carry a unit and its kind
765/// has to be one that means anything by it. `FieldKind::measurable` is the
766/// description answering the second, so this renderer does not keep its own
767/// list of which kinds are quantities -- which is the drift that predicate
768/// exists to stop.
769fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
770    field.unit.filter(|_| field.kind.measurable())
771}
772
773/// The two ends of a range, as egui wants them.
774///
775/// `None` when either end is missing or is not a number this host can read.
776/// The description carries the bounds as text on purpose — the bound of a date
777/// is a date — so parsing them is the renderer's job and failing to is a real
778/// outcome rather than an assertion.
779fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
780    let min = field.min?.parse::<f64>().ok()?;
781    let max = field.max?.parse::<f64>().ok()?;
782    Some(min..=max)
783}
784
785/// How many decimals to write a dragged value back with.
786///
787/// Read off [`Field::step`], which is the only thing that says what
788/// granularity the question has: a step of `0.01` is a two-decimal question and
789/// a step of `1` is a whole-number one. Without a step the host's own
790/// granularity stands, and egui's is continuous, so the value is written back
791/// at whatever precision it round-trips at.
792fn decimals(step: Option<&str>) -> Option<usize> {
793    let step = step?;
794    Some(match step.split_once('.') {
795        Some((_, fraction)) => fraction.trim_end_matches('0').len(),
796        None => 0,
797    })
798}
799
800/// What a select shows for the value it currently holds.
801///
802/// A value no option carries stays on screen as itself rather than reading as
803/// whichever option happens to be first. goingson saved a backup retention of
804/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
805/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
806/// stray `<option>` and this is the same fix in the shape egui allows.
807///
808/// The empty value is the one case that reads as unanswered rather than as an
809/// answer, and [`chosen_text`] is what puts the field's ghost text there.
810fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
811    options
812        .iter()
813        .find(|opt| opt.value == value)
814        .map_or(value, |opt| opt.label)
815}
816
817/// What a select's closed control reads, and in which tone.
818///
819/// A chooser with nothing chosen showed an empty box: `shown_label` falls back
820/// to the value, and the unanswered value is the empty string. So an app with
821/// an instruction to give — audiofiles' "Select device..." — had nowhere to put
822/// it but a disabled button elsewhere on the screen, which is the affordance
823/// this vocabulary keeps moving messages *off*.
824///
825/// [`Field::placeholder`] is already the description's word for "what the field
826/// reads while it is empty" and was honoured by the typed kinds alone, so
827/// nothing new is said here; the renderer is what had not caught up. Muted
828/// because it is not an answer, the same tone the typed kinds' ghost text takes
829/// three lines up.
830///
831/// A value no option carries but that is *not* empty stays as itself, in
832/// `content`: that is the goingson retention bug and it is a wrong answer
833/// rather than an absent one.
834///
835/// Returns the words and the tone rather than a built [`RichText`], because
836/// what it decides is both of them and only one of them is readable back off a
837/// `RichText`.
838///
839/// [`Field::placeholder`]: makeover_layout::Field::placeholder
840fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
841    match field.placeholder {
842        Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
843        _ => (shown_label(field.options, value), palette.content),
844    }
845}
846
847/// What one option in a choice field is drawn in.
848///
849/// The chosen one is the emphasised thing and takes `content`; the rest take
850/// [`content_secondary`](Palette::content_secondary), because an option that is
851/// not chosen is still an option and pressing it chooses it. Muted would be the
852/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
853/// live row and four dead ones. `makeover-tui` draws it the same way
854/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
855fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
856    if value == option {
857        palette.content
858    } else {
859        palette.content_secondary
860    }
861}
862
863/// Which end of an interval a box is.
864///
865/// Named rather than a bool, because what it selects is not a side but a
866/// fallback: an empty end reads as the bound it stands for, and which bound
867/// that is depends on the end.
868#[derive(Debug, Clone, Copy, PartialEq, Eq)]
869enum Bound {
870    /// The lower end, falling back to the start of the extent.
871    Low,
872    /// The upper end, falling back to its end.
873    High,
874}
875
876/// The facts an interval's two boxes share.
877///
878/// One struct because they are one axis: [`Field::min`], [`Field::max`],
879/// [`Field::step`] and [`Field::unit`] describe the question rather than either
880/// end of it, so reading them once is what stops the two boxes drifting apart.
881struct Axis<'a> {
882    /// The extent both ends are dragged inside, when it is one this host can
883    /// read.
884    extent: Option<RangeInclusive<f64>>,
885    /// The granularity, as the description writes it.
886    step: Option<&'a str>,
887    /// What the axis is measured in.
888    unit: Option<&'a str>,
889}
890
891impl Axis<'_> {
892    /// What an empty end reads as: the bound it stands for.
893    ///
894    /// Zero with no extent to fall back on. That is the one number this
895    /// renderer invents, and it invents it where the description declined to
896    /// say anything: an unbounded interval has no edge for the end to sit on,
897    /// and a drag box has to start somewhere.
898    fn edge(&self, which: Bound) -> f64 {
899        self.extent.as_ref().map_or(0.0, |extent| match which {
900            Bound::Low => *extent.start(),
901            Bound::High => *extent.end(),
902        })
903    }
904
905    /// One end of the interval, as a drag box.
906    ///
907    /// # An empty end reads as its bound
908    ///
909    /// Which is what the shipped control did before it was described: an unset
910    /// minimum sits on the low edge and stores no filter. egui's `DragValue`
911    /// holds a number and has no empty state to offer, so the alternative was a
912    /// text box, and that would cost the app a control on the way into being
913    /// described.
914    ///
915    /// With no extent to fall back on, an empty end reads zero. That is the one
916    /// number this renderer invents, and it invents it where the description
917    /// declined to say anything: an unbounded interval has no edge for the end
918    /// to sit on, and a drag box has to start somewhere.
919    ///
920    /// Nothing is written back until the user drags, so a value the app put
921    /// there survives being looked at -- the same guarantee the slider makes.
922    fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
923        let mut number = value.parse::<f64>().unwrap_or(self.edge(which));
924        let mut drag = DragValue::new(&mut number);
925        if let Some(extent) = self.extent.clone() {
926            drag = drag.range(extent);
927        }
928        if let Some(places) = decimals(self.step) {
929            drag = drag.max_decimals(places);
930        }
931        if let Some(step) = self.step.and_then(|s| s.parse::<f64>().ok()) {
932            drag = drag.speed(step);
933        }
934        // Inside the control, beside the readout, which is where `Field::unit`
935        // was decided to belong and where these boxes already put it.
936        if let Some(unit) = self.unit {
937            drag = drag.suffix(format!(" {unit}"));
938        }
939        let response = ui.add(drag);
940        if response.changed() {
941            *value = match decimals(self.step) {
942                Some(places) => format!("{number:.places$}"),
943                None => number.to_string(),
944            };
945        }
946        response
947    }
948}
949
950/// The control alone, without its label, hint or error.
951fn control(
952    ui: &mut Ui,
953    field: &Field<'_>,
954    filling: Filling<'_>,
955    palette: &Palette,
956    style: &FieldStyle,
957    named_by: Option<egui::Id>,
958) -> Response {
959    // The mismatch path: described as one thing and filled as another. Nothing
960    // here can fix it, so it is drawn as the empty, inert version of what was
961    // described — visible on screen, in the way an empty select is at the
962    // webview renderer, rather than reported in a log nobody reads.
963    let mut discard = String::new();
964    // The interval's second scratch buffer. Two ends means the mismatch path
965    // needs two places to write nothing to.
966    let mut spare = String::new();
967    let mut off = false;
968
969    match shape_of(field) {
970        Control::Slid => {
971            let value = match filling {
972                Filling::Text(text) => text,
973                _ => &mut discard,
974            };
975            // `shape_of` has already refused an unbounded range, so the extent
976            // is only missing here if a bound is not a number — a date range,
977            // say, which this control cannot draw either.
978            let Some(extent) = extent(field) else {
979                return ui.label(RichText::new(value.as_str()).color(palette.content));
980            };
981
982            // A value the host cannot read starts at the low end rather than at
983            // zero, which may be outside the extent entirely. Nothing is
984            // written back until the user drags, so an unreadable value the app
985            // put there survives being looked at.
986            let mut number = value.parse::<f64>().unwrap_or(*extent.start());
987            // The granularity is the curve's as of makeover-layout 0.32.0. It
988            // is still in the value's own units, so the display precision is
989            // read off it exactly as before.
990            let step = field.curve.step();
991            let mut slider = Slider::new(&mut number, extent.clone()).text("");
992            if let Some(places) = decimals(step) {
993                slider = slider.max_decimals(places);
994            }
995            if let Some(step) = step.and_then(|s| s.parse::<f64>().ok()) {
996                slider = slider.step_by(step);
997            }
998            // egui's own constant-ratio track, which is this host's answer to
999            // `Curve::Logarithmic`. `is_ratio` rather than a match on the
1000            // variant, because a ratio across zero is not one: makeover-layout
1001            // decides the fallback so that four renderers cannot disagree about
1002            // when it applies.
1003            if field.curve.is_ratio(*extent.start(), *extent.end()) {
1004                slider = slider.logarithmic(true);
1005            }
1006            // The unit goes inside the control, beside the readout egui already
1007            // draws. That placement is the argument `Field::unit` was decided
1008            // on: it is where these controls put it before they were described,
1009            // and it is the one a label could never reach.
1010            if let Some(unit) = unit_of(field) {
1011                slider = slider.suffix(format!(" {unit}"));
1012            }
1013            let response = ui.add(slider);
1014            if response.changed() {
1015                *value = match decimals(step) {
1016                    Some(places) => format!("{number:.places$}"),
1017                    None => number.to_string(),
1018                };
1019            }
1020            response
1021        }
1022        // One question, so one row. Two wells stacked would be two questions on
1023        // screen whatever the description said, which is the reading
1024        // `FieldKind::Interval` exists to prevent.
1025        //
1026        // Dragged rather than typed, because that is what these controls
1027        // already were: audiofiles' six filter axes are `DragValue` pairs with
1028        // a shared extent, a speed and a suffix, and a port that turned them
1029        // into text boxes would be a description costing the app a control.
1030        Control::Spanned => {
1031            let (lower, upper) = match filling {
1032                Filling::Between { lower, upper } => (lower, upper),
1033                _ => (&mut discard, &mut spare),
1034            };
1035            let axis = Axis {
1036                extent: extent(field),
1037                step: field.step,
1038                unit: unit_of(field),
1039            };
1040            ui.horizontal(|ui| {
1041                let low = axis.end(ui, lower, Bound::Low);
1042                // The word rather than a dash. A dash between two numbers is a
1043                // minus sign on a signed axis, and audiofiles filters loudness
1044                // in dBFS.
1045                ui.label(RichText::new("to").color(palette.content_secondary));
1046                let high = axis.end(ui, upper, Bound::High);
1047                // Both ends, by name. A union response carries the first id, so
1048                // labelling the union outside this arm names the lower box and
1049                // leaves the upper one announced as whatever number is in it --
1050                // which is how an interval half-kept the fix that gave every
1051                // other shape its question.
1052                if let Some(id) = named_by {
1053                    low.clone().labelled_by(id);
1054                    high.clone().labelled_by(id);
1055                }
1056                low | high
1057            })
1058            .inner
1059        }
1060        Control::Typed => {
1061            let text = match filling {
1062                Filling::Text(text) => text,
1063                _ => &mut discard,
1064            };
1065            // An empty frame and no margin: the well is this crate's, and egui's
1066            // own control background and padding would sit underneath it saying
1067            // something different about both.
1068            // Keyed on the description's own `multiline` and not on the
1069            // member: a markdown field is several lines by definition, and a
1070            // single-line edit would be a control the value cannot fit in. egui
1071            // does nothing else with the markdown, which is the honest answer
1072            // rather than a gap -- the source is text, and editing it as text
1073            // loses none of it.
1074            let mut edit = if field.kind.multiline() {
1075                TextEdit::multiline(text)
1076            } else {
1077                TextEdit::singleline(text)
1078            }
1079            .frame(egui::Frame::NONE)
1080            .margin(Margin::ZERO)
1081            .text_color(palette.content)
1082            .password(field.kind.confidential());
1083            if let Some(ghost) = field.placeholder {
1084                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
1085            }
1086            let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
1087            // A typed number has no readout of its own to sit beside, so the
1088            // unit follows the box. Muted, because it is a fact about the value
1089            // rather than a second thing to read.
1090            match unit_of(field) {
1091                Some(unit) => {
1092                    ui.label(RichText::new(unit).color(palette.content_muted));
1093                    response
1094                }
1095                None => response,
1096            }
1097        }
1098        Control::Toggled => {
1099            let on = match filling {
1100                Filling::On(on) => on,
1101                _ => &mut off,
1102            };
1103            ui.checkbox(on, RichText::new(field.label).color(palette.content))
1104        }
1105        Control::Listed => {
1106            let value = match filling {
1107                Filling::Text(text) => text,
1108                _ => &mut discard,
1109            };
1110            // No `shown_label` counterpart, and none is needed: a value no
1111            // option carries leaves every button unfilled, which is already
1112            // the honest report on screen. The select needs the fix because it
1113            // has one slot and must put *something* in it.
1114            let group = ui.vertical(|ui| {
1115                let mut answered: Option<Response> = None;
1116                for opt in field.options {
1117                    // An option that cannot be picked yet is drawn and does not
1118                    // answer, with the precondition beside it rather than
1119                    // behind a hover: a greyed row with no reason reads as a
1120                    // dead end, which is the state `Choice::unavailable` exists
1121                    // to stop being sayable.
1122                    let picked = if let Some(reason) = opt.unavailable {
1123                        ui.horizontal(|ui| {
1124                            let picked = ui
1125                                .add_enabled_ui(false, |ui| {
1126                                    ui.radio_value(
1127                                        value,
1128                                        opt.value.to_owned(),
1129                                        RichText::new(opt.label).color(palette.content_muted),
1130                                    )
1131                                })
1132                                .inner;
1133                            ui.label(RichText::new(reason).color(palette.content_muted));
1134                            picked
1135                        })
1136                        .inner
1137                    } else {
1138                        ui.radio_value(
1139                            value,
1140                            opt.value.to_owned(),
1141                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1142                        )
1143                    };
1144                    answered = Some(match answered {
1145                        Some(prev) => prev.union(picked),
1146                        None => picked,
1147                    });
1148                }
1149                answered
1150            });
1151            // A group described with no options answers as its own empty area
1152            // rather than as no response at all, which keeps the caller's
1153            // `.changed()` chain working on a field whose option list has not
1154            // loaded yet.
1155            group.inner.unwrap_or(group.response)
1156        }
1157        Control::Chosen => {
1158            let value = match filling {
1159                Filling::Text(text) => text,
1160                _ => &mut discard,
1161            };
1162            let (shown, tone) = chosen_text(field, value, palette);
1163            ComboBox::from_id_salt(field.name)
1164                .selected_text(RichText::new(shown).color(tone))
1165                .show_ui(ui, |ui| {
1166                    for opt in field.options {
1167                        // Same rule as the radio group: shown, inert, and
1168                        // saying why. A closed control hides its list, so the
1169                        // reason has to travel with the row it belongs to.
1170                        if let Some(reason) = opt.unavailable {
1171                            ui.add_enabled_ui(false, |ui| {
1172                                ui.selectable_value(
1173                                    value,
1174                                    opt.value.to_owned(),
1175                                    RichText::new(format!("{}  {reason}", opt.label))
1176                                        .color(palette.content_muted),
1177                                );
1178                            });
1179                            continue;
1180                        }
1181                        ui.selectable_value(
1182                            value,
1183                            opt.value.to_owned(),
1184                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1185                        );
1186                    }
1187                })
1188                .response
1189        }
1190        // The grouping comes out of the order rather than out of a group list:
1191        // `Field::themes` arrives sorted by variant, so the run of one variant
1192        // is the group and a heading opens whenever the variant changes. Same
1193        // walk as `makeover-webview`'s `<optgroup>` emission, which is what
1194        // keeps two renderers from disagreeing about where a group starts.
1195        Control::Themed => {
1196            let value = match filling {
1197                Filling::Text(text) => text,
1198                _ => &mut discard,
1199            };
1200            let shown = themed_text(field, value);
1201            ComboBox::from_id_salt(field.name)
1202                .selected_text(RichText::new(shown).color(palette.content))
1203                .show_ui(ui, |ui| {
1204                    if let Some(follow) = field.follows {
1205                        // First and outside every heading. It names no theme
1206                        // and sits in no variant, so a heading over it would be
1207                        // inventing a fourth variant for one row.
1208                        ui.selectable_value(
1209                            value,
1210                            follow.value.to_owned(),
1211                            RichText::new(follow.label).color(option_color(
1212                                value,
1213                                follow.value,
1214                                palette,
1215                            )),
1216                        );
1217                    }
1218                    let mut open: Option<ThemeVariant> = None;
1219                    for theme in field.themes {
1220                        if open != Some(theme.variant) {
1221                            // A heading rather than a `selectable_value`: it is
1222                            // not pickable, and egui has no inert row that
1223                            // still reads as a row. `content_muted` is the tone
1224                            // for something that is not an answer, which is the
1225                            // ghost text's tone eight lines up.
1226                            if open.is_some() {
1227                                ui.separator();
1228                            }
1229                            ui.label(
1230                                RichText::new(theme.variant.heading()).color(palette.content_muted),
1231                            );
1232                            open = Some(theme.variant);
1233                        }
1234                        ui.selectable_value(
1235                            value,
1236                            theme.id.to_owned(),
1237                            RichText::new(format!("{}  {}", theme.name, theme.contrast.badge()))
1238                                .color(option_color(value, theme.id, palette)),
1239                        );
1240                    }
1241                })
1242                .response
1243        }
1244    }
1245}
1246
1247/// What a theme picker's closed control reads.
1248///
1249/// [`chosen_text`]'s counterpart, and it is separate for the reason
1250/// [`Control::Themed`] is: the label lives on a [`makeover_layout::ThemeChoice`]
1251/// rather than on a [`Choice`], and the follow row is a third place to look.
1252///
1253/// No placeholder arm. A theme picker is never unanswered in the way a select
1254/// is — an app that resolved a theme to paint this control with has one — and
1255/// falling back to the raw value is the honest report on a stored id whose
1256/// theme has since been deleted.
1257fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str {
1258    if let Some(follow) = field.follows
1259        && follow.value == value
1260    {
1261        return follow.label;
1262    }
1263    field
1264        .themes
1265        .iter()
1266        .find(|theme| theme.id == value)
1267        .map_or(value, |theme| theme.name)
1268}
1269
1270/// One field, as the column the app drops into its form.
1271///
1272/// The anatomy is `makeover-webview`'s, so the two renderers put a form
1273/// together the same way: label, control, hint, error, top to bottom, with a
1274/// checkbox labelling itself instead of taking a label above.
1275///
1276/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
1277/// [`FieldKind::visible`] means and is the honest answer here: a webview still
1278/// emits an input for it because the form submits, and an immediate-mode
1279/// renderer has no form and no submission, so a hidden field is a value the app
1280/// already holds and there is nothing to draw or to respond to.
1281///
1282/// `state` is the description's interaction axis.
1283/// [`State::Disabled`] greys the field and stops it answering, through
1284/// [`State::suppresses_interaction`] rather than through a second reading of
1285/// what disabled means. Focus is not on that axis and never reaches here: egui
1286/// owns reach, focus and the ring for this renderer, and one ring means not a
1287/// second one per renderer that happens to have opinions.
1288pub fn field(
1289    ui: &mut Ui,
1290    field: &Field<'_>,
1291    filling: Filling<'_>,
1292    state: Option<State>,
1293    palette: &Palette,
1294    style: &FieldStyle,
1295) -> Option<Response> {
1296    if !field.kind.visible() {
1297        return None;
1298    }
1299    let enabled = !state.is_some_and(State::suppresses_interaction);
1300    let text = if enabled {
1301        palette.content
1302    } else {
1303        palette.content_muted
1304    };
1305
1306    let response = ui
1307        .vertical(|ui| {
1308            ui.spacing_mut().item_spacing.y = style.gap;
1309
1310            // A checkbox labels itself, on the right of the box.
1311            // `FieldKind::labels_itself` is the description saying so, and both
1312            // webview apps special-cased it inline before it did.
1313            let named_by = (!field.kind.labels_itself())
1314                .then(|| ui.label(RichText::new(label_text(field, style)).color(text)));
1315
1316            let response = ui
1317                .add_enabled_ui(enabled, |ui| {
1318                    control(
1319                        ui,
1320                        field,
1321                        filling,
1322                        palette,
1323                        style,
1324                        named_by.as_ref().map(|l| l.id),
1325                    )
1326                })
1327                .inner;
1328
1329            // The label, attached rather than merely adjacent.
1330            //
1331            // Drawing it above the control and stopping there is what this did
1332            // until 2026-08-22, and it put an unnamed box in the accessibility
1333            // tree with some text near it: a screen reader announced a text
1334            // field with no question, and a prefilled one announced its own
1335            // contents instead. audiofiles' four name modals were the site that
1336            // measured it, through a harness reading what the panel drew.
1337            //
1338            // Worth stating why it was worth fixing here rather than in each
1339            // app: `Field::label` is a member the description carries so a
1340            // renderer does not have to guess, `makeover-webview` has always
1341            // named it in `aria-describedby`, and the two renderers disagreeing
1342            // about a fact the description states is the one thing this layer
1343            // exists to prevent. A checkbox is unaffected -- egui names one from
1344            // its own text, which is what `labels_itself` already says.
1345            let response = match named_by {
1346                Some(label) => response.labelled_by(label.id),
1347                None => response,
1348            };
1349
1350            // Standing help, then what the answer costs, then what is wrong
1351            // now. All three, in that order, for the reason the webview
1352            // renderer names all three in `aria-describedby`: an error
1353            // appearing must not take the hint away with it. This host has the
1354            // room, so unlike makeover-tui it never has to choose -- the
1355            // precedence rule on `Field::note` is for the renderer that does.
1356            if let Some(hint) = field.hint {
1357                ui.label(RichText::new(hint).color(palette.content_muted));
1358            }
1359            // The note carries its own tone, and `Palette::tone` is what
1360            // resolves it, so a Neutral note is ordinary content rather than
1361            // a colour this renderer picked.
1362            if let Some((tone, note)) = field.note {
1363                ui.label(RichText::new(note).color(palette.tone(tone)));
1364            }
1365            if let Some(error) = field.error {
1366                ui.label(RichText::new(error).color(palette.danger));
1367            }
1368            response
1369        })
1370        .inner;
1371
1372    Some(response)
1373}
1374
1375/// A set of fields, laid down a column.
1376///
1377/// `show_extended` is the disclosure, and it is a parameter rather than state
1378/// held here because the disclosure belongs to the *form* and not to any field:
1379/// [`Field::extended`] marks which fields are behind one, and the app owns
1380/// whether it is open. That is the same division `makeover-webview` draws when
1381/// it marks the group `data-extended` and emits no control to toggle it.
1382///
1383/// `draw` is called once per field that should be visible, in order. Taking a
1384/// callback rather than a slice of [`Filling`]s is what keeps the app's own
1385/// values borrowed one at a time: a form's fields usually live in different
1386/// structs, and a parallel array would have to be built each frame and kept in
1387/// step with the description by hand.
1388pub fn group<'a>(
1389    ui: &mut Ui,
1390    fields: &'a [Field<'a>],
1391    show_extended: bool,
1392    style: &FieldStyle,
1393    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1394) {
1395    ui.vertical(|ui| {
1396        ui.spacing_mut().item_spacing.y = style.group_gap;
1397        for f in fields {
1398            if f.extended && !show_extended {
1399                continue;
1400            }
1401            draw(ui, f);
1402        }
1403    });
1404}
1405
1406#[cfg(test)]
1407mod tests {
1408    use super::*;
1409
1410    fn palette(well: Color32) -> Palette {
1411        Palette {
1412            page: Color32::from_rgb(1, 1, 1),
1413            raised: Color32::from_rgb(2, 2, 2),
1414            overlay: Color32::from_rgb(3, 3, 3),
1415            well,
1416            sunken: Color32::from_rgb(4, 4, 4),
1417            bevel_light: Color32::WHITE,
1418            bevel_dark: Color32::BLACK,
1419            elevation: Color32::from_black_alpha(46),
1420            content: Color32::from_rgb(5, 5, 5),
1421            content_secondary: Color32::from_rgb(55, 55, 55),
1422            content_muted: Color32::from_rgb(6, 6, 6),
1423            action: Color32::from_rgb(7, 7, 7),
1424            danger: Color32::from_rgb(8, 8, 8),
1425            success: Color32::from_rgb(9, 9, 9),
1426            warning: Color32::from_rgb(10, 10, 10),
1427            info: Color32::from_rgb(11, 11, 11),
1428        }
1429    }
1430
1431    /// The cast is egui's own shadow type carrying the theme's tone, which is
1432    /// the whole of what this crate had to decide for it: unlike a bevel, egui
1433    /// already knows how to paint one.
1434    #[test]
1435    fn a_unit_is_drawn_only_where_the_kind_is_a_quantity() {
1436        // egui-drawing has no harness here, so what is tested is the decision
1437        // that precedes it: which fields have a unit to draw at all. The kind
1438        // half comes from the description rather than from a `matches!` in this
1439        // crate, which is the drift `FieldKind::measurable` exists to stop.
1440        let ranged = makeover_layout::Field {
1441            unit: Some("s"),
1442            ..makeover_layout::Field::range("attack", "Attack", "0", "5")
1443        };
1444        assert_eq!(unit_of(&ranged), Some("s"));
1445
1446        let typed = makeover_layout::Field {
1447            unit: Some("ms"),
1448            ..makeover_layout::Field::new(makeover_layout::FieldKind::Number, "fade", "Fade")
1449        };
1450        assert_eq!(unit_of(&typed), Some("ms"));
1451
1452        let worded = makeover_layout::Field {
1453            unit: Some("s"),
1454            ..makeover_layout::Field::new(makeover_layout::FieldKind::Text, "name", "Name")
1455        };
1456        assert_eq!(unit_of(&worded), None);
1457
1458        let bare = makeover_layout::Field::range("attack", "Attack", "0", "5");
1459        assert_eq!(unit_of(&bare), None);
1460    }
1461
1462    #[test]
1463    fn the_cast_hands_egui_the_themes_tone() {
1464        let p = palette(Color32::from_rgb(9, 9, 9));
1465        let cast = p.cast();
1466        assert_eq!(cast.color, p.elevation);
1467        assert!(cast.blur > 0, "a cast shadow is soft");
1468        assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1469    }
1470
1471    #[test]
1472    fn a_well_resolves_to_its_own_token() {
1473        // No substitution left. The page-filled well was a stand-in for a
1474        // token that did not exist yet; it exists now.
1475        let w = Color32::from_rgb(9, 9, 9);
1476        let p = palette(w);
1477        assert_eq!(p.fill(Fill::Well), Some(w));
1478        assert_ne!(p.fill(Fill::Well), Some(p.page));
1479    }
1480
1481    #[test]
1482    fn every_intent_is_a_plain_lookup() {
1483        let p = palette(Color32::from_rgb(9, 9, 9));
1484        assert_eq!(p.fill(Fill::Page), Some(p.page));
1485        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1486        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1487    }
1488
1489    /// Sunken is its own colour, not the well's and not the page's. The two
1490    /// are authored in opposite directions and an earlier cut of the
1491    /// description conflated them.
1492    #[test]
1493    fn sunken_is_neither_the_well_nor_the_page() {
1494        let p = palette(Color32::from_rgb(9, 9, 9));
1495        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1496        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1497        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1498    }
1499
1500    #[test]
1501    fn a_raised_region_never_resolves_to_the_well_fill() {
1502        // The cross-app bug, asserted at the renderer boundary this time.
1503        let p = palette(Color32::from_rgb(9, 9, 9));
1504        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1505        let well = Depth::Well.fill().and_then(|f| p.fill(f));
1506        assert_eq!(raised, Some(p.raised));
1507        assert_ne!(raised, well);
1508    }
1509
1510    #[test]
1511    fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1512        // makeover-layout 0.14.0 is what made this reachable. The answer was
1513        // already here at 0.10.0 and the question could not be asked.
1514        let p = palette(Color32::from_rgb(9, 9, 9));
1515        assert_eq!(
1516            Depth::Overlay.fill().and_then(|f| p.fill(f)),
1517            Some(p.overlay)
1518        );
1519        assert_eq!(Depth::Overlay.bevel(), None);
1520        // The shadow `frame` reaches for is the theme's tone rather than
1521        // egui's default, which is the whole reason `cast` exists.
1522        assert_eq!(p.cast().color, p.elevation);
1523    }
1524
1525    #[test]
1526    fn the_lit_edge_swaps_when_a_card_is_pressed() {
1527        let p = palette(Color32::from_rgb(9, 9, 9));
1528        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1529        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1530        assert_eq!(p.edge(tl), p.bevel_light);
1531        assert_eq!(p.edge(ptl), p.bevel_dark);
1532    }
1533
1534    #[test]
1535    fn flat_asks_for_neither_fill_nor_edge() {
1536        assert!(Depth::Flat.fill().is_none());
1537        assert!(Depth::Flat.bevel().is_none());
1538    }
1539
1540    #[test]
1541    fn a_select_keeps_a_value_none_of_its_options_carries() {
1542        // The save-the-wrong-thing bug, asserted at the second renderer so it
1543        // is not re-found there. goingson's own numbers.
1544        let options = [
1545            Choice::plain("1"),
1546            Choice::plain("3"),
1547            Choice::plain("7"),
1548            Choice::plain("14"),
1549        ];
1550        assert_eq!(shown_label(&options, "10"), "10");
1551        // And a value that does match reads as its label, not as itself.
1552        let spelled = [Choice::new("7", "One week")];
1553        assert_eq!(shown_label(&spelled, "7"), "One week");
1554    }
1555
1556    #[test]
1557    fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1558        let p = palette(Color32::from_rgb(9, 9, 9));
1559        let options = [Choice::new("sp404", "SP-404")];
1560        let field = Field {
1561            placeholder: Some("Select device..."),
1562            ..Field::select("device", "Conform for device", &options)
1563        };
1564
1565        assert_eq!(
1566            chosen_text(&field, "", &p),
1567            ("Select device...", p.content_muted),
1568            "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1569        );
1570
1571        // Answered, and it is the label that reads rather than the value.
1572        assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1573    }
1574
1575    #[test]
1576    fn a_wrong_answer_is_not_an_absent_one() {
1577        // The retention-10 bug and the ghost text meet here: a value no option
1578        // carries still reads as itself, because the field IS answered and the
1579        // answer is wrong. Only the empty value is unanswered.
1580        let p = palette(Color32::from_rgb(9, 9, 9));
1581        let options = [Choice::plain("1"), Choice::plain("7")];
1582        let field = Field {
1583            placeholder: Some("Pick one"),
1584            ..Field::select("retention", "Keep backups for", &options)
1585        };
1586
1587        assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1588    }
1589
1590    #[test]
1591    fn a_chooser_with_no_ghost_text_is_unchanged() {
1592        // The whole change is opt-in from the description. A field that says
1593        // nothing about its empty state still shows an empty box.
1594        let p = palette(Color32::from_rgb(9, 9, 9));
1595        let options = [Choice::plain("1")];
1596        let field = Field::select("retention", "Keep backups for", &options);
1597        assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1598    }
1599
1600    #[test]
1601    fn a_range_is_slid_and_a_number_is_typed_into() {
1602        // The distinction the kind was added for, at the renderer that has to
1603        // act on it. A well with a figure in it is not a quiet slider.
1604        assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1605        assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1606    }
1607
1608    #[test]
1609    fn a_range_missing_an_end_falls_back_to_a_well() {
1610        // egui's `Slider` demands both ends, so inventing one would be this
1611        // renderer picking bounds the app never stated and the user then
1612        // dragging against them. A typed number takes every answer the slider
1613        // would.
1614        let whole = Field::range("review", "Review above", "0", "1");
1615        assert_eq!(shape_of(&whole), Control::Slid);
1616
1617        let half = Field {
1618            max: Some("1"),
1619            ..Field::new(FieldKind::Range, "review", "Review above")
1620        };
1621        assert_eq!(shape_of(&half), Control::Typed);
1622        assert_eq!(extent(&half), None);
1623
1624        // A bound this host cannot read is the same outcome by a different
1625        // route: the description carries bounds as text because the bound of a
1626        // date is a date.
1627        let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1628        assert_eq!(extent(&dated), None);
1629    }
1630
1631    #[test]
1632    fn an_interval_is_its_own_shape_and_not_two_numbers() {
1633        // The distinction the kind was added for, at the renderer that has to
1634        // arrange it: two wells stacked are two questions on screen, whatever
1635        // the description says.
1636        assert_eq!(control_shape(FieldKind::Interval), Control::Spanned);
1637        assert_eq!(shape_of(&Field::interval("a", "b", "A")), Control::Spanned);
1638
1639        // Unlike a range, it owes no extent: its bounds are a rule on each end
1640        // rather than the control, so a missing one is an open end.
1641        let axis = Field {
1642            min: Some("0"),
1643            max: Some("300"),
1644            ..Field::interval("bpm_min", "bpm_max", "BPM")
1645        };
1646        assert_eq!(shape_of(&axis), Control::Spanned);
1647    }
1648
1649    #[test]
1650    fn an_empty_end_reads_as_the_bound_it_stands_for() {
1651        // Which is what the shipped control did before it was described: an
1652        // unset minimum sits on the low edge and stores no filter. `DragValue`
1653        // has no empty state, and a text box instead would cost the app a
1654        // control on the way into being described.
1655        let axis = Axis {
1656            extent: Some(0.0..=300.0),
1657            step: Some("1"),
1658            unit: Some("BPM"),
1659        };
1660        assert!((axis.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1661        assert!((axis.edge(Bound::High) - 300.0).abs() < f64::EPSILON);
1662
1663        // With no extent there is no edge to sit on, and a drag box has to
1664        // start somewhere. The one number this renderer invents, invented where
1665        // the description declined to say anything.
1666        let open = Axis {
1667            extent: None,
1668            step: None,
1669            unit: None,
1670        };
1671        assert!((open.edge(Bound::Low) - 0.0).abs() < f64::EPSILON);
1672        assert!((open.edge(Bound::High) - 0.0).abs() < f64::EPSILON);
1673    }
1674
1675    #[test]
1676    fn the_step_decides_how_a_dragged_value_is_written_back() {
1677        // Without it a 0-to-1 threshold writes back whatever float the drag
1678        // landed on, which is the host's granularity and is what the
1679        // description says an absent step means.
1680        assert_eq!(decimals(None), None);
1681        assert_eq!(decimals(Some("1")), Some(0));
1682        assert_eq!(decimals(Some("0.01")), Some(2));
1683        // Trailing zeros are not precision: 0.10 is a one-decimal question.
1684        assert_eq!(decimals(Some("0.10")), Some(1));
1685    }
1686
1687    #[test]
1688    fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1689        // The tone rule, at the one place it is a claim rather than a
1690        // preference: this option genuinely will not answer, so muted is the
1691        // truth. The available ones beside it keep the secondary intent.
1692        let p = palette(Color32::from_rgb(9, 9, 9));
1693        let options = [
1694            Choice::new("chromatic", "Chromatic"),
1695            Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1696        ];
1697        assert!(options[0].available());
1698        assert!(!options[1].available());
1699        assert_eq!(
1700            option_color("chromatic", options[0].value, &p),
1701            p.content,
1702            "the chosen option is the emphasised thing"
1703        );
1704        assert_eq!(
1705            option_color("chromatic", options[1].value, &p),
1706            p.content_secondary,
1707            "and `option_color` never mutes: the unavailable path is what does"
1708        );
1709    }
1710
1711    #[test]
1712    fn only_a_required_field_is_marked() {
1713        let style = FieldStyle::default();
1714        let plain = Field::new(FieldKind::Text, "title", "Title");
1715        assert_eq!(label_text(&plain, &style), "Title");
1716
1717        let required = Field {
1718            required: true,
1719            ..plain
1720        };
1721        assert_eq!(label_text(&required, &style), "Title *");
1722
1723        // The marker is copy and the app owns it, which is why it is a knob.
1724        let house = FieldStyle {
1725            required_marker: "(required)",
1726            ..style
1727        };
1728        assert_eq!(label_text(&required, &house), "Title (required)");
1729    }
1730
1731    #[test]
1732    fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1733        // What decides whether the control gets a well. A well is for what the
1734        // user looks into, and only one of these is.
1735        assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1736        // Not the wildcard. A theme picker falling to `Control::Typed` would
1737        // draw a text box over a resolved list, which is worse than the select
1738        // every app had before the member existed.
1739        assert_eq!(control_shape(FieldKind::Theme), Control::Themed);
1740        assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1741        assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1742        for k in [
1743            FieldKind::Text,
1744            FieldKind::Secret,
1745            FieldKind::Number,
1746            FieldKind::Email,
1747            FieldKind::Url,
1748            FieldKind::Tel,
1749            FieldKind::Textarea,
1750            FieldKind::Rich,
1751        ] {
1752            assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1753        }
1754        // And the two multi-line ones get a multi-line edit, which is the half
1755        // `control_shape` alone does not say: both are typed into, and only one
1756        // of the two edit shapes can hold a markdown document.
1757        assert!(FieldKind::Rich.multiline());
1758        assert!(FieldKind::Textarea.multiline());
1759        assert!(!FieldKind::Text.multiline());
1760    }
1761
1762    #[test]
1763    fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1764        // The description holds Select and Radio apart, and a renderer that
1765        // collapsed them would silently answer a question the app did not ask:
1766        // audiofiles' storage style is irreversible and its alternatives have
1767        // to be readable without opening anything. Asserting the two shapes
1768        // differ is asserting that distinction survives the trip.
1769        assert!(FieldKind::Select.offers_options());
1770        assert!(FieldKind::Radio.offers_options());
1771        assert_ne!(
1772            control_shape(FieldKind::Select),
1773            control_shape(FieldKind::Radio)
1774        );
1775    }
1776
1777    #[test]
1778    fn an_unchosen_option_is_secondary_and_never_muted() {
1779        let p = palette(Color32::from_rgb(4, 4, 4));
1780        assert_eq!(option_color("wav", "wav", &p), p.content);
1781        assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1782        // The whole point of the distinction: muted is what Disabled resolves
1783        // to, so an option wearing it would claim it does not answer a press.
1784        assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1785    }
1786
1787    /// What the accessibility tree says a screen drew, as `(role, name)` pairs.
1788    ///
1789    /// egui builds this from the same `WidgetInfo` every widget already reports,
1790    /// so it is what a screen reader would be handed rather than a second
1791    /// opinion about it. A name that arrives through `labelled_by` is resolved
1792    /// the way a client resolves it: the relation names another node, and that
1793    /// node's text is the control's accessible name.
1794    fn announced(draw: impl FnMut(&mut egui::Ui)) -> Vec<(egui::accesskit::Role, String)> {
1795        let ctx = egui::Context::default();
1796        ctx.enable_accesskit();
1797        let mut draw = draw;
1798        let input = || egui::RawInput {
1799            screen_rect: Some(egui::Rect::from_min_size(
1800                egui::Pos2::ZERO,
1801                egui::vec2(800.0, 600.0),
1802            )),
1803            ..Default::default()
1804        };
1805        // Two passes: egui lays out against the previous frame, so the first
1806        // sees widgets at the wrong rect.
1807        let _ = ctx.run_ui(input(), &mut draw);
1808        let out = ctx.run_ui(input(), &mut draw);
1809
1810        let update = out
1811            .platform_output
1812            .accesskit_update
1813            .expect("accesskit is on, so a tree was built");
1814        let by_id: std::collections::HashMap<_, _> = update.nodes.iter().cloned().collect();
1815        update
1816            .nodes
1817            .iter()
1818            .map(|(_, node)| {
1819                let named = node.label().map(str::to_owned).or_else(|| {
1820                    node.labelled_by()
1821                        .iter()
1822                        .find_map(|id| by_id.get(id))
1823                        .and_then(|by| by.label().or_else(|| by.value()).map(str::to_owned))
1824                });
1825                (node.role(), named.unwrap_or_default())
1826            })
1827            .collect()
1828    }
1829
1830    #[test]
1831    fn a_fields_label_names_its_control_rather_than_sitting_beside_it() {
1832        let f = Field::new(FieldKind::Text, "name", "Vault name");
1833        let p = palette(Color32::from_rgb(9, 9, 9));
1834        let drawn = announced(|ui| {
1835            let mut text = String::new();
1836            field(
1837                ui,
1838                &f,
1839                Filling::Text(&mut text),
1840                None,
1841                &p,
1842                &FieldStyle::default(),
1843            );
1844        });
1845
1846        let box_ = drawn
1847            .iter()
1848            .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1849            .expect("a text field draws a text input");
1850        assert_eq!(
1851            box_.1, "Vault name",
1852            "the box is announced by the question rather than unnamed: {drawn:?}"
1853        );
1854    }
1855
1856    #[test]
1857    fn a_prefilled_box_is_still_announced_by_its_question() {
1858        // The sharper half. With nothing attached, a box carrying a value is
1859        // announced as that value, so a rename field read out the name it was
1860        // seeded with and never said what was being asked.
1861        let f = Field::new(FieldKind::Text, "name", "New name");
1862        let p = palette(Color32::from_rgb(9, 9, 9));
1863        let drawn = announced(|ui| {
1864            let mut text = String::from("Drums");
1865            field(
1866                ui,
1867                &f,
1868                Filling::Text(&mut text),
1869                None,
1870                &p,
1871                &FieldStyle::default(),
1872            );
1873        });
1874
1875        let box_ = drawn
1876            .iter()
1877            .find(|(role, _)| *role == egui::accesskit::Role::TextInput)
1878            .expect("a text field draws a text input");
1879        assert_eq!(box_.1, "New name", "{drawn:?}");
1880    }
1881
1882    #[test]
1883    fn both_ends_of_an_interval_are_named_by_the_one_question() {
1884        // A union response carries the first id, so labelling the pair outside
1885        // the arm named the lower box and left the upper one announced as
1886        // whatever number was in it.
1887        let f = Field::new(FieldKind::Interval, "bpm", "BPM Range");
1888        let p = palette(Color32::from_rgb(9, 9, 9));
1889        let drawn = announced(|ui| {
1890            let mut lower = String::from("90");
1891            let mut upper = String::from("300");
1892            field(
1893                ui,
1894                &f,
1895                Filling::Between {
1896                    lower: &mut lower,
1897                    upper: &mut upper,
1898                },
1899                None,
1900                &p,
1901                &FieldStyle::default(),
1902            );
1903        });
1904
1905        // A `SpinButton`: an interval's ends are drag values, not text boxes.
1906        let ends: Vec<_> = drawn
1907            .iter()
1908            .filter(|(role, _)| *role == egui::accesskit::Role::SpinButton)
1909            .collect();
1910        assert_eq!(ends.len(), 2, "an interval draws two boxes: {drawn:?}");
1911        for end in ends {
1912            assert_eq!(end.1, "BPM Range", "{drawn:?}");
1913        }
1914    }
1915
1916    #[test]
1917    fn a_checkbox_keeps_naming_itself() {
1918        // `FieldKind::labels_itself` routes past the label, and egui names a
1919        // checkbox from its own text, so there is nothing to attach and
1920        // attaching one would say the name twice.
1921        let f = Field::new(FieldKind::Checkbox, "loop", "Loop playback");
1922        let p = palette(Color32::from_rgb(9, 9, 9));
1923        let drawn = announced(|ui| {
1924            let mut ticked = false;
1925            field(
1926                ui,
1927                &f,
1928                Filling::On(&mut ticked),
1929                None,
1930                &p,
1931                &FieldStyle::default(),
1932            );
1933        });
1934
1935        assert!(
1936            drawn
1937                .iter()
1938                .any(|(role, name)| *role == egui::accesskit::Role::CheckBox
1939                    && name == "Loop playback"),
1940            "{drawn:?}"
1941        );
1942    }
1943
1944    #[test]
1945    fn a_hidden_field_draws_nothing_and_answers_nothing() {
1946        // Where the two renderers legitimately part: a webview still emits an
1947        // input because the form submits, and there is no form here.
1948        let f = Field::new(FieldKind::Hidden, "id", "Id");
1949        let p = palette(Color32::from_rgb(9, 9, 9));
1950        egui::__run_test_ui(|ui| {
1951            let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1952            assert!(drawn.is_none());
1953        });
1954    }
1955
1956    #[test]
1957    fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1958        let f = Field::new(FieldKind::Text, "title", "Title");
1959        let p = palette(Color32::from_rgb(9, 9, 9));
1960        let style = FieldStyle::default();
1961        egui::__run_test_ui(|ui| {
1962            let mut text = String::from("x");
1963            let disabled = field(
1964                ui,
1965                &f,
1966                Filling::Text(&mut text),
1967                Some(State::Disabled),
1968                &p,
1969                &style,
1970            )
1971            .unwrap();
1972            assert!(!disabled.enabled());
1973
1974            // Stating no state is the ordinary case and answers. Focus used to
1975            // be the counter-example here; it is egui's now and a description
1976            // cannot state it at all.
1977            let mut text = String::from("x");
1978            let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1979            assert!(plain.enabled(), "an unstated field still answers");
1980        });
1981    }
1982
1983    #[test]
1984    fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1985        // No panic and no write-through. A checkbox handed a string cannot be
1986        // filled, so it is drawn off and left alone.
1987        let f = Field::new(FieldKind::Checkbox, "done", "Done");
1988        let p = palette(Color32::from_rgb(9, 9, 9));
1989        let mut text = String::from("untouched");
1990        egui::__run_test_ui(|ui| {
1991            let drawn = field(
1992                ui,
1993                &f,
1994                Filling::Text(&mut text),
1995                None,
1996                &p,
1997                &FieldStyle::default(),
1998            );
1999            assert!(drawn.is_some());
2000        });
2001        assert_eq!(text, "untouched");
2002    }
2003
2004    #[test]
2005    fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
2006        let fields = [
2007            Field::new(FieldKind::Text, "title", "Title"),
2008            Field {
2009                extended: true,
2010                ..Field::new(FieldKind::Text, "notes", "Notes")
2011            },
2012        ];
2013        let style = FieldStyle::default();
2014
2015        let mut closed = Vec::new();
2016        egui::__run_test_ui(|ui| {
2017            group(ui, &fields, false, &style, |_, f| closed.push(f.name));
2018        });
2019        assert_eq!(closed, ["title"]);
2020
2021        let mut open = Vec::new();
2022        egui::__run_test_ui(|ui| {
2023            group(ui, &fields, true, &style, |_, f| open.push(f.name));
2024        });
2025        assert_eq!(open, ["title", "notes"]);
2026    }
2027
2028    #[test]
2029    fn the_default_frame_is_square_and_one_point() {
2030        let d = FrameStyle::default();
2031        assert_eq!(d.radius, CornerRadius::ZERO);
2032        assert_eq!(d.margin, Margin::ZERO);
2033        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
2034    }
2035
2036    #[test]
2037    fn a_theme_picker_reads_its_chosen_theme_by_name() {
2038        const THEMES: &[makeover_layout::ThemeChoice<'_>] = &[makeover_layout::ThemeChoice::new(
2039            "carbonfox",
2040            "Carbonfox",
2041            ThemeVariant::Dark,
2042            makeover_layout::Contrast::High,
2043        )];
2044        let field = Field::theme("theme", "Theme", THEMES)
2045            .following(Choice::new("system", "Follow System"));
2046
2047        assert_eq!(themed_text(&field, "carbonfox"), "Carbonfox");
2048        assert_eq!(themed_text(&field, "system"), "Follow System");
2049        // A stored id whose theme has been deleted reads as itself rather than
2050        // as an empty box, which is the honest report on the config as it
2051        // stands.
2052        assert_eq!(themed_text(&field, "gone"), "gone");
2053    }
2054}