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 host;
225pub mod table;
226pub mod widget;
227
228/// The resolved colours this renderer needs, as flat values.
229///
230/// Built by the app from whatever it already uses to resolve a theme, then
231/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
232/// painted per widget per frame, and a map lookup per edge is a cost with
233/// nothing to show for it.
234#[derive(Debug, Clone, Copy, PartialEq, Eq)]
235pub struct Palette {
236    /// `surface-page`.
237    pub page: Color32,
238    /// `surface-raised`.
239    pub raised: Color32,
240    /// `surface-overlay`.
241    pub overlay: Color32,
242    /// `surface-well`.
243    ///
244    /// Required, not optional. makeover derives it for every theme, so a
245    /// resolved palette without a well is not a thing that exists here.
246    /// `makeover-tui` keeps its own `Option` for a different reason, since a
247    /// terminal can have the colour and still be unable to show it.
248    pub well: Color32,
249    /// `surface-sunken`.
250    ///
251    /// A surface set back from the one it sits on, by colour and nothing else.
252    /// Not a well: a well is a hole with an edge, and this has no edge. An
253    /// immediate-mode renderer paints an arbitrary rect, so unlike
254    /// `makeover-tui` it has no excuse for declining this one.
255    ///
256    /// Required rather than optional, on the same footing as `well`: all 31
257    /// themes makeover embeds author it.
258    pub sunken: Color32,
259    /// `bevel-light`.
260    pub bevel_light: Color32,
261    /// `bevel-dark`.
262    pub bevel_dark: Color32,
263    /// `elevation`.
264    ///
265    /// What a surface that floats OVER the page is cast onto it with. The one
266    /// intent here that is about a surface's relationship to the page rather
267    /// than about the surface, which is why it is a translucent near-black on
268    /// every theme rather than something read off the palette's own ramp.
269    ///
270    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
271    /// surface *in* the layout takes a bevel, and reaching for this on a panel
272    /// or a card is how a pre-Platinum look survives a conversion under a new
273    /// name.
274    ///
275    /// egui has a real answer for this where a terminal does not: see
276    /// [`Palette::cast`], which is the shadow to hand an
277    /// [`egui::Frame`](egui::Frame).
278    pub elevation: Color32,
279    /// `content`.
280    ///
281    /// Ordinary text.
282    pub content: Color32,
283    /// `content-secondary`.
284    ///
285    /// Inactive but usable: it still answers a press. The middle tone of the
286    /// three (wiki `three-tone-convention`), and the one an unchosen option in
287    /// a choice field takes.
288    ///
289    /// Not [`content_muted`](Self::content_muted), which carries a claim:
290    /// `State::Disabled` resolves to it, so a live control wearing it tells the
291    /// user it will not answer. `makeover-tui` draws the same widget the same
292    /// way from `makeover-tui@230bf63`.
293    ///
294    /// A step of `content` toward the page, derived at load by `makeover`
295    /// rather than authored, so it is read off the resolved theme here like
296    /// any other token and never re-derived.
297    pub content_secondary: Color32,
298    /// `content-muted`.
299    ///
300    /// A field's hint, and what
301    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
302    /// resolves to. Both readings come from the description rather than from
303    /// here: `State::Disabled` names this intent by token.
304    pub content_muted: Color32,
305    /// `action-primary`.
306    ///
307    /// What a control is drawn in.
308    ///
309    /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
310    /// separate. A cell holding a control that takes the cell's text colour is
311    /// the drift `CellPart` names.
312    pub action: Color32,
313    /// `content-on-action`: ink that stays readable on [`action`](Self::action).
314    ///
315    /// Derived by the theme with `readable_on(action)` rather than picked here,
316    /// so a theme whose action hue is pale gets dark ink without this renderer
317    /// knowing which themes those are.
318    ///
319    /// The one thing that fills with `action` is the act a screen is for
320    /// ([`makeover_layout::Act::leading`]), which is why this arrived with it.
321    /// A renderer that fills with the accent and leaves the label on the
322    /// ordinary content colour is one theme change away from unreadable.
323    pub content_on_action: Color32,
324    /// `danger`.
325    ///
326    /// A field's error message, a destructive control, a bar that has run over.
327    pub danger: Color32,
328    /// `success`.
329    ///
330    /// The three status intents arrive together and not one at a time:
331    /// [`Tone`] is five members wide and a resolver missing one has to invent
332    /// a colour for it, which is the substitution [`Palette::fill`] refuses.
333    pub success: Color32,
334    /// `warning`.
335    pub warning: Color32,
336    /// `info`.
337    pub info: Color32,
338    /// `border`, the authored line colour.
339    ///
340    /// A neutral badge's edge: a badge on the raised ground is raised too, so
341    /// the edge is what draws it.
342    pub border: Color32,
343    /// `info-surface`: raised with 12 percent of `info`. A badge's fill.
344    ///
345    /// The four tone surfaces arrive together for the status intents' reason.
346    pub info_surface: Color32,
347    /// `success-surface`.
348    pub success_surface: Color32,
349    /// `warning-surface`.
350    pub warning_surface: Color32,
351    /// `danger-surface`.
352    pub danger_surface: Color32,
353    /// `row-stripe`: every second row of a table, ink mixed into raised at 5
354    /// percent (wiki `table-model`).
355    pub row_stripe: Color32,
356    /// `row-hover`: the row under the pointer, at 9 percent.
357    pub row_hover: Color32,
358    /// `row-rule`: the hairline between rows and around a table, at 26
359    /// percent.
360    pub row_rule: Color32,
361    /// `row-selected`: a selected row, raised with 18 percent of the accent.
362    ///
363    /// A fill and never a foreground, so a row that is red for a failure stays
364    /// red while it is selected.
365    pub row_selected: Color32,
366}
367
368impl Palette {
369    /// Resolve a surface intent, or `None` for one this renderer does not know.
370    ///
371    /// A plain lookup, and no substitution.
372    ///
373    /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function
374    /// over an open enum can only stay total by inventing a colour for a member
375    /// it has never heard of. Every member the description has today is
376    /// answered with `Some`.
377    #[must_use]
378    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
379        match fill {
380            Fill::Page => Some(self.page),
381            Fill::Raised => Some(self.raised),
382            Fill::Overlay => Some(self.overlay),
383            Fill::Well => Some(self.well),
384            Fill::Sunken => Some(self.sunken),
385            _ => None,
386        }
387    }
388
389    /// The colour a [`Tone`] reads as.
390    ///
391    /// Total, unlike [`fill`](Self::fill), and the difference is not an
392    /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
393    /// description layer settled tone at five members and grows surfaces, so a
394    /// total function here cannot be made to invent a colour by an upstream
395    /// release the way a total `fill` could.
396    ///
397    /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
398    /// its own, which is what "an ordinary fact" means: a neutral badge is text
399    /// in a box, not a fifth status.
400    #[must_use]
401    pub const fn tone(&self, tone: Tone) -> Color32 {
402        match tone {
403            Tone::Neutral => self.content,
404            Tone::Info => self.info,
405            Tone::Success => self.success,
406            Tone::Warning => self.warning,
407            Tone::Danger => self.danger,
408        }
409    }
410
411    /// What a badge of this tone is filled with: its tone surface, or the
412    /// raised surface for [`Tone::Neutral`], as `makeover-webview` fills one.
413    #[must_use]
414    pub const fn tone_surface(&self, tone: Tone) -> Color32 {
415        match tone {
416            Tone::Neutral => self.raised,
417            Tone::Info => self.info_surface,
418            Tone::Success => self.success_surface,
419            Tone::Warning => self.warning_surface,
420            Tone::Danger => self.danger_surface,
421        }
422    }
423
424    /// What a badge of this tone is edged with: its tone, or
425    /// [`border`](Self::border) for [`Tone::Neutral`], whose tone is the ink.
426    #[must_use]
427    pub const fn tone_edge(&self, tone: Tone) -> Color32 {
428        match tone {
429            Tone::Neutral => self.border,
430            other => self.tone(other),
431        }
432    }
433
434    /// The cast shadow for a surface that overlays the page.
435    ///
436    /// What "overlaying" means in immediate mode, answered rather than skipped.
437    /// egui already paints shadows for its menus and windows through
438    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
439    /// theme's tone instead of egui's own default, not to invent a painter here
440    /// the way [`paint_bevel`] had to.
441    ///
442    /// The geometry matches what `makeover-webview` composes, in points rather
443    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
444    /// menu sits just off the page rather than hovering above it.
445    ///
446    /// ```no_run
447    /// # let palette: makeover_immediate::Palette = unimplemented!();
448    /// # let ui: &mut egui::Ui = unimplemented!();
449    /// egui::Frame::popup(ui.style())
450    ///     .shadow(palette.cast())
451    ///     .show(ui, |ui| { ui.label("over the page"); });
452    /// ```
453    #[must_use]
454    pub const fn cast(&self) -> egui::Shadow {
455        egui::Shadow {
456            offset: [0, 2],
457            blur: 24,
458            spread: 0,
459            color: self.elevation,
460        }
461    }
462
463    /// Resolve a bevel edge intent.
464    #[must_use]
465    pub const fn edge(&self, edge: Edge) -> Color32 {
466        match edge {
467            Edge::Light => self.bevel_light,
468            Edge::Dark => self.bevel_dark,
469        }
470    }
471}
472
473/// The geometry a framed region is drawn with.
474///
475/// Every field is a value, which is why they all arrive from the caller:
476/// radius and border width belong to `makeover-geometry`, and margins come
477/// from its relational gaps.
478#[derive(Debug, Clone, Copy, PartialEq)]
479pub struct FrameStyle {
480    /// Corner radius. Square under the Platinum default.
481    pub radius: CornerRadius,
482    /// Inner margin between the frame and its contents.
483    pub margin: Margin,
484    /// Bevel stroke width, in points.
485    pub stroke: f32,
486}
487
488impl Default for FrameStyle {
489    /// A one-point square frame with no inner margin.
490    fn default() -> Self {
491        Self {
492            radius: CornerRadius::ZERO,
493            margin: Margin::ZERO,
494            stroke: 1.0,
495        }
496    }
497}
498
499/// Paint a two-tone edge just inside `rect`.
500///
501/// Fill first, bevel after: this adds two polylines and nothing else, so it
502/// composes over whatever is already there. That is what lets it go over an
503/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
504///
505/// Two three-point polylines meeting at opposite corners, rather than four
506/// segments, so egui mitres the corner joins instead of leaving a notch.
507///
508/// The dark polyline is drawn second, so the two corners where the runs meet
509/// take its tone. That is the right answer here rather than a concession.
510/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
511/// a renderer with room to divide one should; at the default one-point stroke
512/// the corner is a one-point square, so the division is sub-pixel and
513/// antialiasing resolves it to the same blend the mitre already gives. Splitting
514/// it would add a seam and no information. `makeover-tui` does split, because a
515/// terminal cell is large enough that not splitting costs a visible cell of edge
516/// weight — the same rule, at a resolution where it has something to say.
517pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
518    let (top_left, bottom_right) = bevel.edges();
519
520    // Inset by half a stroke so the line lands inside `rect` rather than
521    // straddling its edge, which on a fractional-scale display is the
522    // difference between one crisp pixel and two dim ones.
523    let r = rect.shrink(stroke / 2.0);
524
525    painter.add(Shape::line(
526        vec![r.left_bottom(), r.left_top(), r.right_top()],
527        Stroke::new(stroke, palette.edge(top_left)),
528    ));
529    // Three points close the box, two leave the bottom open: the shaded run
530    // comes down the right side and stops. That is the folder tab, and it is
531    // the same edge the browser draws by dropping the shadow's vertical
532    // offset. The lit polyline is untouched either way, so the join is the
533    // only thing that changes.
534    let shaded = if bevel.draws_bottom() {
535        vec![r.right_top(), r.right_bottom(), r.left_bottom()]
536    } else {
537        vec![r.right_top(), r.right_bottom()]
538    };
539    painter.add(Shape::line(
540        shaded,
541        Stroke::new(stroke, palette.edge(bottom_right)),
542    ));
543}
544
545/// Draw a region at a given [`Depth`]: its fill and its edge, together.
546///
547/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
548/// difference between level-with and painted-the-same-colour, and it is the
549/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
550/// page.
551pub fn frame<R>(
552    ui: &mut Ui,
553    depth: Depth,
554    palette: &Palette,
555    style: FrameStyle,
556    add_contents: impl FnOnce(&mut Ui) -> R,
557) -> R {
558    let mut f = egui::Frame::new()
559        .corner_radius(style.radius)
560        .inner_margin(style.margin);
561    // Two ways there is no fill to paint, and they collapse to the same
562    // outcome: the depth names none (Depth::Flat), or it names one this
563    // renderer cannot resolve. Either way the frame goes unfilled and the
564    // bevel below carries the depth on its own, which is the rule this
565    // module already documents for Flat.
566    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
567        f = f.fill(fill);
568    }
569    // A surface that overlays the page is cast onto it. [`Palette::cast`] has
570    // answered what that means here since 0.10.0 and nothing could reach it: a
571    // description had no way to say Overlay until makeover-layout 0.14.0, so
572    // the answer sat beside the question. Keyed off the fill rather than the
573    // variant, so it stays right for whatever else the description calls an
574    // overlay later.
575    if depth.fill() == Some(Fill::Overlay) {
576        f = f.shadow(palette.cast());
577    }
578    let framed = f.show(ui, add_contents);
579    if let Some(bevel) = depth.bevel() {
580        paint_bevel(
581            ui.painter(),
582            framed.response.rect,
583            bevel,
584            palette,
585            style.stroke,
586        );
587    }
588    framed.inner
589}
590
591/// The geometry a field group is drawn with.
592///
593/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
594/// `makeover-geometry` and arrives already resolved.
595#[derive(Debug, Clone, Copy, PartialEq)]
596pub struct FieldStyle {
597    /// The well a text control sits in.
598    pub frame: FrameStyle,
599    /// Between a field's own parts: its label, its control, its hint and its
600    /// error.
601    pub gap: f32,
602    /// Between one field and the next.
603    pub group_gap: f32,
604    /// What marks a required field, appended to its label.
605    ///
606    /// A knob rather than a constant, because it is the one piece of *copy* in
607    /// this crate and copy is not a renderer's call. A webview does not need it
608    /// at all — it emits the `required` attribute and the browser answers — so
609    /// this renderer is the first place where a compulsory field either shows
610    /// that it is or silently does not.
611    pub required_marker: &'static str,
612}
613
614impl Default for FieldStyle {
615    /// The default frame, no gaps, and an asterisk.
616    fn default() -> Self {
617        Self {
618            frame: FrameStyle::default(),
619            gap: 0.0,
620            group_gap: 0.0,
621            required_marker: "*",
622        }
623    }
624}
625
626/// What the field currently holds, borrowed from wherever the app keeps it.
627///
628/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
629/// place the two renderers are forced apart: there the value is read back out
630/// of the DOM after the fact, and here the widget writes through this borrow as
631/// it is edited. Same reason the description carries neither.
632///
633/// An enum rather than a bag of options, on the reasoning
634/// `makeover_webview::form::Value` records: a checkbox holding a string is
635/// unsayable here, where a struct would let it be said and then have to cope.
636///
637/// `#[non_exhaustive]` since [`Ticked`](Self::Ticked) arrived, which is the
638/// breaking change that made room for it: a host builds these and never matches
639/// on them, so the next shape of held value costs nobody a match arm.
640#[derive(Debug, Default)]
641#[non_exhaustive]
642pub enum Filling<'a> {
643    /// Nothing to edit. The control is drawn and does not answer.
644    #[default]
645    Absent,
646    /// The buffer behind anything that takes typed text, a select included:
647    /// what a select holds is the `value` of one of its [`Choice`]s.
648    ///
649    /// [`Choice`]: makeover_layout::Choice
650    Text(&'a mut String),
651    /// A checkbox, on or off.
652    On(&'a mut bool),
653    /// The values of a [`FieldKind::Checklist`]'s ticked options.
654    ///
655    /// The values rather than a bool per option, because the options are the
656    /// description's and the set is the app's: a host keeps what was ticked
657    /// under the option values it submits, and a parallel list of bools would
658    /// have to be re-aligned with the options every time the list changed.
659    /// Ticking pushes the option's value and unticking removes it, so the order
660    /// is the order things were ticked in, which is no order a handler should
661    /// read anything into.
662    Ticked(&'a mut Vec<String>),
663    /// The two buffers behind a [`FieldKind::Interval`], lower first.
664    ///
665    /// Two buffers rather than one string with a separator, which is
666    /// [`makeover_layout::Field::upper_name`]'s reason one level down: an
667    /// interval is submitted under two names, so it is edited as two values,
668    /// and a delimiter this crate owned could appear inside either of them.
669    ///
670    /// Either end may be empty while the other stands. An open end is an
671    /// answer -- "over 120 BPM" -- rather than a half-filled box.
672    Between {
673        /// The lower end's buffer.
674        lower: &'a mut String,
675        /// The upper end's buffer.
676        upper: &'a mut String,
677    },
678}
679
680/// The label, marked if the field is compulsory.
681fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
682    if field.required {
683        format!("{} {}", field.label, style.required_marker)
684    } else {
685        field.label.to_owned()
686    }
687}
688
689/// The four shapes a control comes in here, which is fewer than there are
690/// kinds.
691///
692/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
693/// ways egui has of asking for a value do not. Reducing the open set to this
694/// closed one in one total function is what keeps a new kind from needing a new
695/// arm at every match below.
696#[derive(Debug, Clone, Copy, PartialEq, Eq)]
697enum Control {
698    /// Typed into, so it is drawn as a well: the user looks into it.
699    Typed,
700    /// Picked from a control that shows one option at a time. Pressed rather
701    /// than looked into, so egui's own control painting stands.
702    Chosen,
703    /// Picked from options that are all on screen at once.
704    ///
705    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
706    /// apart, and holding them apart is the whole content of
707    /// [`FieldKind::Radio`]: same question, and an answer the user can read
708    /// without opening anything.
709    Listed,
710    /// Ticked from options that are all on screen at once, as many as apply.
711    ///
712    /// Apart from [`Listed`](Self::Listed) because picking one leaves the
713    /// others standing, and apart from [`Toggled`](Self::Toggled) because it is
714    /// one question: [`FieldKind::Checklist`] asks it above its boxes, where a
715    /// checkbox is its own label.
716    Ticked,
717    /// Held on or off.
718    Toggled,
719    /// Dragged across an extent that is on screen the whole time.
720    ///
721    /// Apart from [`Typed`](Self::Typed) for the reason
722    /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
723    /// question means, so a well with a figure in it is not a quieter version
724    /// of this control, it is a different one.
725    Slid,
726    /// Picked from a list of themes that arrives grouped and marked.
727    ///
728    /// Apart from [`Chosen`](Self::Chosen) rather than folded into it, and the
729    /// distinction is the same one [`Listed`](Self::Listed) draws: it is not a
730    /// different question, it is a different amount of structure on screen. A
731    /// theme picker's rows carry a group heading and a contrast mark, and both
732    /// come from members [`Field::options`] does not have, so a shared arm
733    /// would be a `matches!` on the kind inside the loop rather than one arm
734    /// less.
735    Themed,
736    /// Two values dragged across one axis, drawn as one question.
737    ///
738    /// Apart from [`Typed`](Self::Typed) for the reason
739    /// [`FieldKind::Interval`] is apart from `Number`: two wells one under the
740    /// other are two questions on screen, whatever the description says, and
741    /// the arrangement is the whole content of the kind.
742    Spanned,
743}
744
745/// Which shape a kind takes.
746///
747/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
748/// description since this renderer was built degrades to a text box, which
749/// accepts any value the others would, rather than to nothing drawn at all.
750///
751/// `FieldKind::File` lands there rather than growing a shape of its own. egui's
752/// honest answer is a button that opens a native picker, which is a fifth
753/// control and a file-dialog dependency, and no consumer of this crate asks for
754/// a file field. The membership test is that every renderer *could* answer
755/// honestly, not that each one does on the day. A path in a text box is not
756/// nothing.
757///
758/// `Field::accept` and `Field::multiple` land on the same position: both are the picker's arguments, and this
759/// renderer has no picker to give them to. They are not lost — the description
760/// still carries them, and the day the native dialog arrives here it is opened
761/// with them rather than with a filter written twice.
762///
763/// `FieldKind::Date` and `FieldKind::DateTime` land there too, on the same
764/// footing and with one thing owed. A
765/// calendar is a sixth control and bare `egui` has none, so a typed value is
766/// the honest answer here; what the app gets is the format the description
767/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
768/// those are constants rather than a sentence. audiofiles is the only consumer
769/// of this crate and asks for neither today. A calendar popup is the upgrade
770/// whenever one does.
771///
772/// `Field::as_instant` is carried and not honoured, on
773/// the same footing. It asks for the typed wall-clock value to be submitted as
774/// the moment it names, and this renderer has no submission to convert on: it
775/// draws the control and the app reads the value back, so the conversion would
776/// belong wherever that read happens rather than here. What the app gets is the
777/// local value in `DATETIME_FORMAT`, which is what it got before the member
778/// existed. No described site on this host asks for it today.
779/// One row of a closed chooser, as the single string it has room for.
780///
781/// A combo hides its list, so everything an option carries has to travel with
782/// the row it belongs to: there is no second line to put a detail on and no
783/// space beside the row to put a reason in. That is the same constraint a
784/// `<select>`'s option has in the webview, and it takes the same answer.
785///
786/// The order is what the option *is* before why it cannot be picked, which is
787/// the order the two read in and the order the radio group draws them in.
788fn combo_row(opt: &Choice<'_>) -> String {
789    let mut text = opt.label.to_owned();
790    for extra in [opt.detail, opt.unavailable].into_iter().flatten() {
791        text.push_str("  ");
792        text.push_str(extra);
793    }
794    text
795}
796
797/// How far an option's second line is inset, in points.
798///
799/// 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
800/// magnitude, which is `makeover-geometry`'s subject and not this crate's --
801/// but this one is measured off a widget egui draws and sizes, so there is
802/// nothing for a spacing scale to say about it.
803const OPTION_DETAIL_INDENT: f32 = 22.0;
804
805const fn control_shape(kind: FieldKind) -> Control {
806    match kind {
807        FieldKind::Select => Control::Chosen,
808        FieldKind::Radio => Control::Listed,
809        FieldKind::Checklist => Control::Ticked,
810        FieldKind::Checkbox => Control::Toggled,
811        FieldKind::Range => Control::Slid,
812        FieldKind::Interval => Control::Spanned,
813        FieldKind::Theme => Control::Themed,
814        _ => Control::Typed,
815    }
816}
817
818/// The shape the field actually gets, which is the kind's unless the field is
819/// missing what that shape needs.
820///
821/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
822/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
823/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
824/// inventing one would be this renderer picking bounds the app never stated and
825/// the user then dragging against them.
826///
827/// It falls back to [`Control::Typed`], which is where every kind this renderer
828/// cannot draw natively already lands: a number in a well is a true report of
829/// the value and takes any answer the slider would.
830fn shape_of(field: &Field<'_>) -> Control {
831    match control_shape(field.kind) {
832        Control::Slid if !field.bounded() => Control::Typed,
833        shape => shape,
834    }
835}
836
837/// The unit to draw beside this field's value, if there is one to draw.
838///
839/// Two conditions rather than one: the field has to carry a unit and its kind
840/// has to be one that means anything by it. `FieldKind::measurable` is the
841/// description answering the second, so this renderer does not keep its own
842/// list of which kinds are quantities -- which is the drift that predicate
843/// exists to stop.
844fn unit_of<'a>(field: &Field<'a>) -> Option<&'a str> {
845    field.unit.filter(|_| field.kind.measurable())
846}
847
848/// The two ends of a range, as egui wants them.
849///
850/// `None` when either end is missing or is not a number this host can read.
851/// The description carries the bounds as text on purpose — the bound of a date
852/// is a date — so parsing them is the renderer's job and failing to is a real
853/// outcome rather than an assertion.
854///
855/// A bound that parses but is not finite (`inf`, `NaN`, `1e400`) is not a
856/// number this host can read either: egui's slider asserts on it in debug and
857/// writes `NaN` back into the app's value in release.
858fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
859    let min = field.min?.parse::<f64>().ok().filter(|n| n.is_finite())?;
860    let max = field.max?.parse::<f64>().ok().filter(|n| n.is_finite())?;
861    Some(min..=max)
862}
863
864/// The step as a number, the way HTML reads `step`.
865///
866/// `any` is no step, and so is anything that is not a finite number above
867/// zero: HTML ignores an invalid step rather than refusing the input, and
868/// the webview hands the string to the browser, so this matches what the
869/// same field does there.
870fn step_value(step: Option<&str>) -> Option<f64> {
871    step?
872        .trim()
873        .parse::<f64>()
874        .ok()
875        .filter(|n| n.is_finite() && *n > 0.0)
876}
877
878/// The most decimals a step is read to, which is `f64`'s own precision and
879/// under emath's limit.
880const MAX_DECIMALS: usize = 15;
881
882/// How many decimals to write a dragged value back with.
883///
884/// Read off [`Field::step`], which is the only thing that says what
885/// granularity the question has: a step of `0.01` is a two-decimal question and
886/// a step of `1` is a whole-number one. Without a step the host's own
887/// granularity stands, and egui's is continuous, so the value is written back
888/// at whatever precision it round-trips at.
889///
890/// Read off the number rather than the spelling, so `1e-3` is three decimals
891/// like `0.001`, and `any` or a step that is not a number is none: it takes
892/// egui's continuous granularity, which is what HTML does with it.
893fn decimals(step: Option<&str>) -> Option<usize> {
894    let step = step_value(step)?;
895    // The shortest decimal that round-trips, which is how the step was
896    // written, and its digits after the point are the precision it asks for.
897    let written = format!("{step}");
898    Some(
899        written
900            .split_once('.')
901            .map_or(0, |(_, fraction)| fraction.len())
902            .min(MAX_DECIMALS),
903    )
904}
905
906/// A dragged number as the text written back, or `None` when there is no
907/// number to write. egui can hand back `NaN` from a range it could not
908/// resolve, and an app's value should keep what it had rather than read "NaN".
909fn written_back(number: f64, step: Option<&str>) -> Option<String> {
910    if !number.is_finite() {
911        return None;
912    }
913    Some(match decimals(step) {
914        Some(places) => format!("{number:.places$}"),
915        None => number.to_string(),
916    })
917}
918
919/// What a select shows for the value it currently holds.
920///
921/// A value no option carries stays on screen as itself rather than reading as
922/// whichever option happens to be first. goingson saved a backup retention of
923/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
924/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
925/// stray `<option>` and this is the same fix in the shape egui allows.
926///
927/// The empty value is the one case that reads as unanswered rather than as an
928/// answer, and [`chosen_text`] is what puts the field's ghost text there.
929fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
930    options
931        .iter()
932        .find(|opt| opt.value == value)
933        .map_or(value, |opt| opt.label)
934}
935
936/// What a select's closed control reads, and in which tone.
937///
938/// A chooser with nothing chosen showed an empty box: `shown_label` falls back
939/// to the value, and the unanswered value is the empty string. So an app with
940/// an instruction to give — audiofiles' "Select device..." — had nowhere to put
941/// it but a disabled button elsewhere on the screen, which is the affordance
942/// this vocabulary keeps moving messages *off*.
943///
944/// [`Field::placeholder`] is already the description's word for "what the field
945/// reads while it is empty" and was honoured by the typed kinds alone, so
946/// nothing new is said here; the renderer is what had not caught up. Muted
947/// because it is not an answer, the same tone the typed kinds' ghost text takes
948/// three lines up.
949///
950/// A value no option carries but that is *not* empty stays as itself, in
951/// `content`: that is the goingson retention bug and it is a wrong answer
952/// rather than an absent one.
953///
954/// Returns the words and the tone rather than a built [`RichText`], because
955/// what it decides is both of them and only one of them is readable back off a
956/// `RichText`.
957///
958/// [`Field::placeholder`]: makeover_layout::Field::placeholder
959fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
960    match field.placeholder {
961        Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
962        _ => (shown_label(field.options, value), palette.content),
963    }
964}
965
966/// What one option in a choice field is drawn in.
967///
968/// The chosen one is the emphasised thing and takes `content`; the rest take
969/// [`content_secondary`](Palette::content_secondary), because an option that is
970/// not chosen is still an option and pressing it chooses it. Muted would be the
971/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
972/// live row and four dead ones. `makeover-tui` draws it the same way
973/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
974fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
975    if value == option {
976        palette.content
977    } else {
978        palette.content_secondary
979    }
980}
981
982/// Which end of an interval a box is.
983///
984/// Named rather than a bool, because what it selects is not a side but a
985/// fallback: an empty end reads as the bound it stands for, and which bound
986/// that is depends on the end.
987#[derive(Debug, Clone, Copy, PartialEq, Eq)]
988enum Bound {
989    /// The lower end, falling back to the start of the extent.
990    Low,
991    /// The upper end, falling back to its end.
992    High,
993}
994
995/// The facts an interval's two boxes share.
996///
997/// One struct because they are one axis: [`Field::min`], [`Field::max`],
998/// [`Field::step`] and [`Field::unit`] describe the question rather than either
999/// end of it, so reading them once is what stops the two boxes drifting apart.
1000struct Axis<'a> {
1001    /// The extent both ends are dragged inside, when it is one this host can
1002    /// read.
1003    extent: Option<RangeInclusive<f64>>,
1004    /// The granularity, as the description writes it.
1005    step: Option<&'a str>,
1006    /// What the axis is measured in.
1007    unit: Option<&'a str>,
1008}
1009
1010impl Axis<'_> {
1011    /// What an empty end reads as: the bound it stands for.
1012    ///
1013    /// Zero with no extent to fall back on. That is the one number this
1014    /// renderer invents, and it invents it where the description declined to
1015    /// say anything: an unbounded interval has no edge for the end to sit on,
1016    /// and a drag box has to start somewhere.
1017    fn edge(&self, which: Bound) -> f64 {
1018        self.extent.as_ref().map_or(0.0, |extent| match which {
1019            Bound::Low => *extent.start(),
1020            Bound::High => *extent.end(),
1021        })
1022    }
1023
1024    /// One end of the interval, as a drag box.
1025    ///
1026    /// # An empty end reads as its bound
1027    ///
1028    /// Which is what the shipped control did before it was described: an unset
1029    /// minimum sits on the low edge and stores no filter. egui's `DragValue`
1030    /// holds a number and has no empty state to offer, so the alternative was a
1031    /// text box, and that would cost the app a control on the way into being
1032    /// described.
1033    ///
1034    /// With no extent to fall back on, an empty end reads zero. That is the one
1035    /// number this renderer invents, and it invents it where the description
1036    /// declined to say anything: an unbounded interval has no edge for the end
1037    /// to sit on, and a drag box has to start somewhere.
1038    ///
1039    /// Nothing is written back until the user drags, so a value the app put
1040    /// there survives being looked at -- the same guarantee the slider makes.
1041    fn end(&self, ui: &mut Ui, value: &mut String, which: Bound) -> Response {
1042        let mut number = value
1043            .parse::<f64>()
1044            .ok()
1045            .filter(|n| n.is_finite())
1046            .unwrap_or(self.edge(which));
1047        let mut drag = DragValue::new(&mut number);
1048        if let Some(extent) = self.extent.clone() {
1049            drag = drag.range(extent);
1050        }
1051        if let Some(places) = decimals(self.step) {
1052            drag = drag.max_decimals(places);
1053        }
1054        if let Some(step) = step_value(self.step) {
1055            drag = drag.speed(step);
1056        }
1057        // Inside the control, beside the readout, which is where `Field::unit`
1058        // was decided to belong and where these boxes already put it.
1059        if let Some(unit) = self.unit {
1060            drag = drag.suffix(format!(" {unit}"));
1061        }
1062        let response = ui.add(drag);
1063        if response.changed()
1064            && let Some(text) = written_back(number, self.step)
1065        {
1066            *value = text;
1067        }
1068        response
1069    }
1070}
1071
1072/// The control alone, without its label, hint or error.
1073fn control(
1074    ui: &mut Ui,
1075    field: &Field<'_>,
1076    filling: Filling<'_>,
1077    palette: &Palette,
1078    style: &FieldStyle,
1079    named_by: Option<egui::Id>,
1080) -> Response {
1081    // The mismatch path: described as one thing and filled as another. Nothing
1082    // here can fix it, so it is drawn as the empty, inert version of what was
1083    // described — visible on screen, in the way an empty select is at the
1084    // webview renderer, rather than reported in a log nobody reads.
1085    let mut discard = String::new();
1086    // The interval's second scratch buffer. Two ends means the mismatch path
1087    // needs two places to write nothing to.
1088    let mut spare = String::new();
1089    let mut off = false;
1090
1091    match shape_of(field) {
1092        Control::Slid => {
1093            let value = match filling {
1094                Filling::Text(text) => text,
1095                _ => &mut discard,
1096            };
1097            // `shape_of` has already refused an unbounded range, so the extent
1098            // is only missing here if a bound is not a number — a date range,
1099            // say, which this control cannot draw either.
1100            let Some(extent) = extent(field) else {
1101                return ui.label(RichText::new(value.as_str()).color(palette.content));
1102            };
1103
1104            // A value the host cannot read starts at the low end rather than at
1105            // zero, which may be outside the extent entirely. Nothing is
1106            // written back until the user drags, so an unreadable value the app
1107            // put there survives being looked at.
1108            let mut number = value
1109                .parse::<f64>()
1110                .ok()
1111                .filter(|n| n.is_finite())
1112                .unwrap_or(*extent.start());
1113            // The granularity is the curve's as of makeover-layout 0.32.0. It
1114            // is still in the value's own units, so the display precision is
1115            // read off it exactly as before.
1116            let step = field.curve.step();
1117            let mut slider = Slider::new(&mut number, extent.clone()).text("");
1118            if let Some(places) = decimals(step) {
1119                slider = slider.max_decimals(places);
1120            }
1121            if let Some(step) = step_value(step) {
1122                slider = slider.step_by(step);
1123            }
1124            // egui's own constant-ratio track, which is this host's answer to
1125            // `Curve::Logarithmic`. `is_ratio` rather than a match on the
1126            // variant, because a ratio across zero is not one: makeover-layout
1127            // decides the fallback so that four renderers cannot disagree about
1128            // when it applies.
1129            if field.curve.is_ratio(*extent.start(), *extent.end()) {
1130                slider = slider.logarithmic(true);
1131            }
1132            // The unit goes inside the control, beside the readout egui already
1133            // draws. That placement is the argument `Field::unit` was decided
1134            // on: it is where these controls put it before they were described,
1135            // and it is the one a label could never reach.
1136            if let Some(unit) = unit_of(field) {
1137                slider = slider.suffix(format!(" {unit}"));
1138            }
1139            let response = ui.add(slider);
1140            if response.changed()
1141                && let Some(text) = written_back(number, step)
1142            {
1143                *value = text;
1144            }
1145            response
1146        }
1147        // One question, so one row. Two wells stacked would be two questions on
1148        // screen whatever the description said, which is the reading
1149        // `FieldKind::Interval` exists to prevent.
1150        //
1151        // Dragged rather than typed, because that is what these controls
1152        // already were: audiofiles' six filter axes are `DragValue` pairs with
1153        // a shared extent, a speed and a suffix, and a port that turned them
1154        // into text boxes would be a description costing the app a control.
1155        Control::Spanned => {
1156            let (lower, upper) = match filling {
1157                Filling::Between { lower, upper } => (lower, upper),
1158                _ => (&mut discard, &mut spare),
1159            };
1160            let axis = Axis {
1161                extent: extent(field),
1162                step: field.step,
1163                unit: unit_of(field),
1164            };
1165            ui.horizontal(|ui| {
1166                let low = axis.end(ui, lower, Bound::Low);
1167                // The word rather than a dash. A dash between two numbers is a
1168                // minus sign on a signed axis, and audiofiles filters loudness
1169                // in dBFS.
1170                ui.label(RichText::new("to").color(palette.content_secondary));
1171                let high = axis.end(ui, upper, Bound::High);
1172                // Both ends, by name. A union response carries the first id, so
1173                // labelling the union outside this arm names the lower box and
1174                // leaves the upper one announced as whatever number is in it --
1175                // which is how an interval half-kept the fix that gave every
1176                // other shape its question.
1177                if let Some(id) = named_by {
1178                    low.clone().labelled_by(id);
1179                    high.clone().labelled_by(id);
1180                }
1181                low | high
1182            })
1183            .inner
1184        }
1185        Control::Typed => {
1186            let text = match filling {
1187                Filling::Text(text) => text,
1188                _ => &mut discard,
1189            };
1190            // An empty frame and no margin: the well is this crate's, and egui's
1191            // own control background and padding would sit underneath it saying
1192            // something different about both.
1193            // Keyed on the description's own `multiline` and not on the
1194            // member: a markdown field is several lines by definition, and a
1195            // single-line edit would be a control the value cannot fit in. egui
1196            // does nothing else with the markdown, which is the honest answer
1197            // rather than a gap -- the source is text, and editing it as text
1198            // loses none of it.
1199            let mut edit = if field.kind.multiline() {
1200                TextEdit::multiline(text)
1201            } else {
1202                TextEdit::singleline(text)
1203            }
1204            .frame(egui::Frame::NONE)
1205            .margin(Margin::ZERO)
1206            .text_color(palette.content)
1207            .password(field.kind.confidential());
1208            if let Some(ghost) = field.placeholder {
1209                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
1210            }
1211            let response = frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit));
1212            // A typed number has no readout of its own to sit beside, so the
1213            // unit follows the box. Muted, because it is a fact about the value
1214            // rather than a second thing to read.
1215            match unit_of(field) {
1216                Some(unit) => {
1217                    ui.label(RichText::new(unit).color(palette.content_muted));
1218                    response
1219                }
1220                None => response,
1221            }
1222        }
1223        Control::Toggled => {
1224            let on = match filling {
1225                Filling::On(on) => on,
1226                _ => &mut off,
1227            };
1228            ui.checkbox(on, RichText::new(field.label).color(palette.content))
1229        }
1230        Control::Listed => {
1231            let value = match filling {
1232                Filling::Text(text) => text,
1233                _ => &mut discard,
1234            };
1235            // No `shown_label` counterpart, and none is needed: a value no
1236            // option carries leaves every button unfilled, which is already
1237            // the honest report on screen. The select needs the fix because it
1238            // has one slot and must put *something* in it.
1239            let group = ui.vertical(|ui| {
1240                let mut answered: Option<Response> = None;
1241                for opt in field.options {
1242                    // An option that cannot be picked yet is drawn and does not
1243                    // answer, with the precondition beside it rather than
1244                    // behind a hover: a greyed row with no reason reads as a
1245                    // dead end, which is the state `Choice::unavailable` exists
1246                    // to stop being sayable.
1247                    let picked = if let Some(reason) = opt.unavailable {
1248                        ui.horizontal(|ui| {
1249                            let picked = ui
1250                                .add_enabled_ui(false, |ui| {
1251                                    ui.radio_value(
1252                                        value,
1253                                        opt.value.to_owned(),
1254                                        RichText::new(opt.label).color(palette.content_muted),
1255                                    )
1256                                })
1257                                .inner;
1258                            ui.label(RichText::new(reason).color(palette.content_muted));
1259                            picked
1260                        })
1261                        .inner
1262                    } else {
1263                        ui.radio_value(
1264                            value,
1265                            opt.value.to_owned(),
1266                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
1267                        )
1268                    };
1269                    // What picking it means, under the option rather than
1270                    // beside it. makeover-layout 0.39.0, and the placement is
1271                    // the difference from the reason above: a precondition is
1272                    // short enough to sit on the line, and a sentence saying
1273                    // what a tier is would push every option's control out of
1274                    // line with its neighbours.
1275                    //
1276                    // Indented past the radio, so it reads as belonging to the
1277                    // option above rather than as a label of its own. Muted,
1278                    // the same reading `.form-option-detail` takes in the
1279                    // webview: the line orients the label, it does not compete
1280                    // with it.
1281                    if let Some(detail) = opt.detail {
1282                        ui.horizontal(|ui| {
1283                            ui.add_space(OPTION_DETAIL_INDENT);
1284                            ui.label(RichText::new(detail).color(palette.content_muted));
1285                        });
1286                    }
1287                    answered = Some(match answered {
1288                        Some(prev) => prev.union(picked),
1289                        None => picked,
1290                    });
1291                }
1292                answered
1293            });
1294            // A group described with no options answers as its own empty area
1295            // rather than as no response at all, which keeps the caller's
1296            // `.changed()` chain working on a field whose option list has not
1297            // loaded yet.
1298            group.inner.unwrap_or(group.response)
1299        }
1300        Control::Ticked => {
1301            // A host that lends no set still draws what the description
1302            // marked, which is `Choice::chosen` and the whole of what a
1303            // checklist carries about its answer.
1304            let mut seeded: Vec<String>;
1305            let ticked = if let Filling::Ticked(ticked) = filling {
1306                ticked
1307            } else {
1308                seeded = field
1309                    .options
1310                    .iter()
1311                    .filter(|opt| opt.chosen)
1312                    .map(|opt| opt.value.to_owned())
1313                    .collect();
1314                &mut seeded
1315            };
1316            let group = ui.vertical(|ui| {
1317                let mut answered: Option<Response> = None;
1318                for opt in field.options {
1319                    let mut on = ticked.iter().any(|value| value == opt.value);
1320                    let before = on;
1321                    // The radio group's rule for an option that cannot be
1322                    // picked yet: drawn, inert, and saying why on its own line.
1323                    let color = if !opt.available() {
1324                        palette.content_muted
1325                    } else if on {
1326                        palette.content
1327                    } else {
1328                        palette.content_secondary
1329                    };
1330                    let picked = ui
1331                        .horizontal(|ui| {
1332                            let picked = ui
1333                                .add_enabled_ui(opt.available(), |ui| {
1334                                    ui.checkbox(&mut on, RichText::new(opt.label).color(color))
1335                                })
1336                                .inner;
1337                            if let Some(reason) = opt.unavailable {
1338                                ui.label(RichText::new(reason).color(palette.content_muted));
1339                            }
1340                            picked
1341                        })
1342                        .inner;
1343                    if on != before {
1344                        if on {
1345                            ticked.push(opt.value.to_owned());
1346                        } else {
1347                            ticked.retain(|value| value != opt.value);
1348                        }
1349                    }
1350                    // Under the option, indented past the box, for the reason
1351                    // the radio group gives.
1352                    if let Some(detail) = opt.detail {
1353                        ui.horizontal(|ui| {
1354                            ui.add_space(OPTION_DETAIL_INDENT);
1355                            ui.label(RichText::new(detail).color(palette.content_muted));
1356                        });
1357                    }
1358                    answered = Some(match answered {
1359                        Some(prev) => prev.union(picked),
1360                        None => picked,
1361                    });
1362                }
1363                answered
1364            });
1365            group.inner.unwrap_or(group.response)
1366        }
1367        Control::Chosen => {
1368            let value = match filling {
1369                Filling::Text(text) => text,
1370                _ => &mut discard,
1371            };
1372            let (shown, tone) = chosen_text(field, value, palette);
1373            ComboBox::from_id_salt(field.name)
1374                .selected_text(RichText::new(shown).color(tone))
1375                .show_ui(ui, |ui| {
1376                    for opt in field.options {
1377                        // Same rule as the radio group: shown, inert, and
1378                        // saying why. A closed control hides its list, so the
1379                        // reason has to travel with the row it belongs to.
1380                        // A closed control hides its list, so everything an
1381                        // option carries has to travel with the row it belongs
1382                        // to. That is why both extra strings run into the text
1383                        // here and neither does in the group above: a combo
1384                        // row is a row, the way a `<select>`'s option is.
1385                        let text = combo_row(opt);
1386                        if opt.unavailable.is_some() {
1387                            ui.add_enabled_ui(false, |ui| {
1388                                ui.selectable_value(
1389                                    value,
1390                                    opt.value.to_owned(),
1391                                    RichText::new(text).color(palette.content_muted),
1392                                );
1393                            });
1394                            continue;
1395                        }
1396                        ui.selectable_value(
1397                            value,
1398                            opt.value.to_owned(),
1399                            RichText::new(text).color(option_color(value, opt.value, palette)),
1400                        );
1401                    }
1402                })
1403                .response
1404        }
1405        // The grouping comes out of the order rather than out of a group list:
1406        // `Field::themes` arrives sorted by variant, so the run of one variant
1407        // is the group and a heading opens whenever the variant changes. Same
1408        // walk as `makeover-webview`'s `<optgroup>` emission, which is what
1409        // keeps two renderers from disagreeing about where a group starts.
1410        Control::Themed => {
1411            let value = match filling {
1412                Filling::Text(text) => text,
1413                _ => &mut discard,
1414            };
1415            let shown = themed_text(field, value);
1416            ComboBox::from_id_salt(field.name)
1417                .selected_text(RichText::new(shown).color(palette.content))
1418                .show_ui(ui, |ui| {
1419                    if let Some(follow) = field.follows {
1420                        // First and outside every heading. It names no theme
1421                        // and sits in no variant, so a heading over it would be
1422                        // inventing a fourth variant for one row.
1423                        ui.selectable_value(
1424                            value,
1425                            follow.value.to_owned(),
1426                            RichText::new(follow.label).color(option_color(
1427                                value,
1428                                follow.value,
1429                                palette,
1430                            )),
1431                        );
1432                    }
1433                    let mut open: Option<ThemeVariant> = None;
1434                    for theme in field.themes {
1435                        if open != Some(theme.variant) {
1436                            // A heading rather than a `selectable_value`: it is
1437                            // not pickable, and egui has no inert row that
1438                            // still reads as a row. `content_muted` is the tone
1439                            // for something that is not an answer, which is the
1440                            // ghost text's tone eight lines up.
1441                            if open.is_some() {
1442                                ui.separator();
1443                            }
1444                            ui.label(
1445                                RichText::new(theme.variant.heading()).color(palette.content_muted),
1446                            );
1447                            open = Some(theme.variant);
1448                        }
1449                        ui.selectable_value(
1450                            value,
1451                            theme.id.to_owned(),
1452                            RichText::new(format!("{}  {}", theme.name, theme.contrast.badge()))
1453                                .color(option_color(value, theme.id, palette)),
1454                        );
1455                    }
1456                })
1457                .response
1458        }
1459    }
1460}
1461
1462/// What a theme picker's closed control reads.
1463///
1464/// [`chosen_text`]'s counterpart, and it is separate for the reason
1465/// [`Control::Themed`] is: the label lives on a [`makeover_layout::ThemeChoice`]
1466/// rather than on a [`Choice`], and the follow row is a third place to look.
1467///
1468/// No placeholder arm. A theme picker is never unanswered in the way a select
1469/// is — an app that resolved a theme to paint this control with has one — and
1470/// falling back to the raw value is the honest report on a stored id whose
1471/// theme has since been deleted.
1472fn themed_text<'a>(field: &'a Field<'a>, value: &'a str) -> &'a str {
1473    if let Some(follow) = field.follows
1474        && follow.value == value
1475    {
1476        return follow.label;
1477    }
1478    field
1479        .themes
1480        .iter()
1481        .find(|theme| theme.id == value)
1482        .map_or(value, |theme| theme.name)
1483}
1484
1485/// One field, as the column the app drops into its form.
1486///
1487/// The anatomy is `makeover-webview`'s, so the two renderers put a form
1488/// together the same way: label, control, hint, error, top to bottom, with a
1489/// checkbox labelling itself instead of taking a label above.
1490///
1491/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
1492/// [`FieldKind::visible`] means and is the honest answer here: a webview still
1493/// emits an input for it because the form submits, and an immediate-mode
1494/// renderer has no form and no submission, so a hidden field is a value the app
1495/// already holds and there is nothing to draw or to respond to.
1496///
1497/// `state` is the description's interaction axis.
1498/// [`State::Disabled`] greys the field and stops it answering, through
1499/// [`State::suppresses_interaction`] rather than through a second reading of
1500/// what disabled means. Focus is not on that axis and never reaches here: egui
1501/// owns reach, focus and the ring for this renderer, and one ring means not a
1502/// second one per renderer that happens to have opinions.
1503pub fn field(
1504    ui: &mut Ui,
1505    field: &Field<'_>,
1506    filling: Filling<'_>,
1507    state: Option<State>,
1508    palette: &Palette,
1509    style: &FieldStyle,
1510) -> Option<Response> {
1511    if !field.kind.visible() {
1512        return None;
1513    }
1514    let enabled = !state.is_some_and(State::suppresses_interaction);
1515    let text = if enabled {
1516        palette.content
1517    } else {
1518        palette.content_muted
1519    };
1520
1521    let response = ui
1522        .vertical(|ui| {
1523            ui.spacing_mut().item_spacing.y = style.gap;
1524
1525            // A checkbox labels itself, on the right of the box.
1526            // `FieldKind::labels_itself` is the description saying so, and both
1527            // webview apps special-cased it inline before it did.
1528            let named_by = (!field.kind.labels_itself())
1529                .then(|| ui.label(RichText::new(label_text(field, style)).color(text)));
1530
1531            let response = ui
1532                .add_enabled_ui(enabled, |ui| {
1533                    control(
1534                        ui,
1535                        field,
1536                        filling,
1537                        palette,
1538                        style,
1539                        named_by.as_ref().map(|l| l.id),
1540                    )
1541                })
1542                .inner;
1543
1544            // The label, attached rather than merely adjacent.
1545            //
1546            // Drawing it above the control and stopping there is what this did
1547            // until 2026-08-22, and it put an unnamed box in the accessibility
1548            // tree with some text near it: a screen reader announced a text
1549            // field with no question, and a prefilled one announced its own
1550            // contents instead. audiofiles' four name modals were the site that
1551            // measured it, through a harness reading what the panel drew.
1552            //
1553            // Worth stating why it was worth fixing here rather than in each
1554            // app: `Field::label` is a member the description carries so a
1555            // renderer does not have to guess, `makeover-webview` has always
1556            // named it in `aria-describedby`, and the two renderers disagreeing
1557            // about a fact the description states is the one thing this layer
1558            // exists to prevent. A checkbox is unaffected -- egui names one from
1559            // its own text, which is what `labels_itself` already says.
1560            let response = match named_by {
1561                Some(label) => response.labelled_by(label.id),
1562                None => response,
1563            };
1564
1565            // Standing help, then what the answer costs, then what is wrong
1566            // now. All three, in that order, for the reason the webview
1567            // renderer names all three in `aria-describedby`: an error
1568            // appearing must not take the hint away with it. This host has the
1569            // room, so unlike makeover-tui it never has to choose -- the
1570            // precedence rule on `Field::note` is for the renderer that does.
1571            if let Some(hint) = field.hint {
1572                ui.label(RichText::new(hint).color(palette.content_muted));
1573            }
1574            // The note carries its own tone, and `Palette::tone` is what
1575            // resolves it, so a Neutral note is ordinary content rather than
1576            // a colour this renderer picked.
1577            if let Some((tone, note)) = field.note {
1578                ui.label(RichText::new(note).color(palette.tone(tone)));
1579            }
1580            if let Some(error) = field.error {
1581                ui.label(RichText::new(error).color(palette.danger));
1582            }
1583            response
1584        })
1585        .inner;
1586
1587    Some(response)
1588}
1589
1590/// A set of fields, laid down a column.
1591///
1592/// `show_extended` is the disclosure, and it is a parameter rather than state
1593/// held here because the disclosure belongs to the *form* and not to any field:
1594/// [`Field::extended`] marks which fields are behind one, and the app owns
1595/// whether it is open. That is the same division `makeover-webview` draws when
1596/// it marks the group `data-extended` and emits no control to toggle it.
1597///
1598/// `draw` is called once per field that should be visible, in order. Taking a
1599/// callback rather than a slice of [`Filling`]s is what keeps the app's own
1600/// values borrowed one at a time: a form's fields usually live in different
1601/// structs, and a parallel array would have to be built each frame and kept in
1602/// step with the description by hand.
1603pub fn group<'a>(
1604    ui: &mut Ui,
1605    fields: &'a [Field<'a>],
1606    show_extended: bool,
1607    style: &FieldStyle,
1608    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1609) {
1610    ui.vertical(|ui| {
1611        ui.spacing_mut().item_spacing.y = style.group_gap;
1612        for f in fields {
1613            if f.extended && !show_extended {
1614                continue;
1615            }
1616            draw(ui, f);
1617        }
1618    });
1619}
1620
1621#[cfg(test)]
1622mod tests;