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