Skip to main content

makeover_immediate/
lib.rs

1//! The immediate-mode renderer for [`makeover_layout`].
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Named for the mode, not the library, the way `makeover-tui` is named for
6//! the target and not for ratatui. Immediate mode is the constraint that
7//! actually separates this renderer from the other two, and egui is the
8//! backend it is written against.
9//!
10//! It is the harshest renderer the description has to survive: no
11//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
12//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
13//! A two-tone lit edge is not something egui can be configured into producing,
14//! so it gets painted by hand here, once, instead of in every consuming app.
15//!
16//! # What this crate does and does not own
17//!
18//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
19//! for a filled region. It owns no colours and no sizes, and no longer owns a
20//! substitution: it briefly supplied the page for a well, which was a stand-in
21//! for `surface-well` before makeover derived it, and every consumer reads the
22//! real token now. [`Palette`] is supplied by the caller,
23//! already resolved, and every radius, margin and stroke width arrives in
24//! [`FrameStyle`].
25//!
26//! That split is why the crate has no dependency on `makeover` itself: the app
27//! already resolves a theme, and coupling a renderer to a colour crate's
28//! version would buy nothing.
29//!
30//! # The cascade is the real difference
31//!
32//! A stylesheet can say "a pressed button inverts its bevel" once and let the
33//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
34//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
35//! the decision from being re-derived per widget.
36//!
37//! # 0.11.0: the overlay becomes reachable
38//!
39//! 0.10.0 answered what overlaying means in immediate mode with
40//! [`Palette::cast`], and nothing could ask: the description had no
41//! `Depth::Overlay` until `makeover-layout` 0.14.0, so the answer sat beside a
42//! question that could not be posed. [`frame`] now hands the cast shadow to the
43//! `egui::Frame` for any depth whose fill is [`Fill::Overlay`], keyed off the
44//! fill rather than the variant.
45//!
46//! The same release brings `makeover_layout::CellPart`, which 0.11.0 carried
47//! and did not draw. [`table`] draws it, below.
48//!
49//! # 0.12.0: the table
50//!
51//! [`table`] is the vocabulary 0.11.0 took without using. The consumer is
52//! audiofiles, whose file list is the only table in the tree exercising all four
53//! of what the description says about one at once: sortable headings with
54//! carets, fixed and remainder tracks, and buttons inside cells.
55//!
56//! Two things it forces, both named where they land:
57//!
58//! - **`egui_extras`**, this crate's first dependency past egui. egui has no
59//!   table, and `Grid` gives no per-column sizing, no sticky header and no
60//!   scroll sync, which is why audiofiles reached for `egui_extras` rather than
61//!   building on `Grid`. A third answer here would reimplement that crate worse.
62//! - **[`Palette::action`]**, on the footing [`Palette::content`] arrived on: a
63//!   link in a cell is the first thing here needing the action intent.
64//!
65//! Narrowing works differently from the terminal's and the module header says
66//! why: a content column cannot be measured before the app's closure has drawn
67//! it, so `egui_extras` sizes it and the declared floor budgets it.
68//!
69//! # 0.13.0: what the adoption found missing
70//!
71//! 0.12.0 shipped [`table`] before audiofiles had taken it, and taking it found
72//! three things the file list already did that the function could not say. All
73//! three are host idiom rather than description, which is why they land here and
74//! not in `makeover-layout`, and all three are answered on a handle the app
75//! never sees: the `egui_extras` row and builder this crate owns. That is
76//! [`table::cell`]'s reasoning again: what the app cannot reach, the renderer
77//! owes it.
78//!
79//! - **A selected row.** [`table::Body::selected`], a predicate asked per row,
80//!   because `set_selected` is a method on the row. Without it a file list has
81//!   no way to show what is selected, which is most of what a file list does.
82//! - **Scrolling a row into view.** [`table::Body::scroll_to`], because
83//!   `scroll_to_row` is a method on the builder. A keyboard cursor that moves
84//!   off-screen and stays there is the bug this prevents.
85//! - **Dragging a divider.** [`table::TableStyle::resizable`], which passes the
86//!   test `sticky_header` failed in 0.12.0: egui_extras offers two settings here
87//!   and a renderer can honestly make either choice.
88//!
89//! A fourth was found and is not a knob. Cells are centred on the row's centre
90//! line, always, because there is no second honest answer and egui's own default
91//! (top-aligned) is the one thing it cannot be.
92//!
93//! [`table::Body`] is also what splits a table's per-frame facts from its
94//! description and from its style. A row count, a selection and a scroll request
95//! are none of them style, and none of them survive the frame.
96//!
97//! # 0.18.0: the nodes that were not fields, tables or frames
98//!
99//! [`widget`] draws a meter, a token, a control and a figure. `makeover-tui` has
100//! had all four for releases and this crate had none of them, which stayed
101//! invisible while the only consumer was an app calling [`field`] and [`table`]
102//! directly. It stopped being invisible the moment anything tried to draw a
103//! whole `quasi_router::Screen` in egui: the four are ordinary nodes, so a
104//! screen walk would have had to draw them itself, one copy per consumer.
105//!
106//! [`Palette`] grows the three status intents with it. They arrive together
107//! rather than one per widget for the reason [`Palette::fill`] is an `Option`:
108//! `Tone` is five members wide, and a resolver missing one has to invent a
109//! colour, which is the substitution 0.2.0 spent a release removing.
110//!
111//! # Forms
112//!
113//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
114//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
115//! of them laid down a column in [`group`]. Before it, a description saying
116//! "text field, labelled, required, with this hint" had no way to become a
117//! widget here, and audiofiles' forms stayed hand-rolled.
118//!
119//! `makeover-webview` got there first and its form emitter is the precedent
120//! followed rather than re-derived, including the parts that are bug fixes: a
121//! select handed a value none of its options carries keeps that value visible
122//! instead of silently reading as the first option, which is a save-the-wrong-
123//! thing bug goingson hit for real.
124//!
125//! What differs is forced by the mode and not chosen:
126//!
127//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
128//!   and the widget writes through it. There is no DOM to read back out of,
129//!   which is also why the description deliberately does not carry the value.
130//! - **A text control is drawn as a well and a select is not.** The description
131//!   holds that a well is for anything the user looks *into*, and a text field
132//!   is its own example; a select and a checkbox are pressed rather than looked
133//!   into, so they keep egui's own control painting.
134//! - **Focus is not describable, and egui owns all of it here.** **Reach**,
135//!   **focus** and the **focus ring** are this renderer's three answers and
136//!   egui already has all three: its own id stack decides what is reachable,
137//!   its own state decides what holds the keyboard, and it paints exactly one
138//!   ring. A description states none of them — `makeover_layout` removed the
139//!   member that used to try in 0.19.0 — and drawing a second ring on top of
140//!   egui's would break the one-ring rule it would have come from. The terms
141//!   are defined once in `makeover_layout`'s crate header, "Reach, focus and
142//!   the focus ring". [`makeover_layout::State::Disabled`] *is* drawn, because
143//!   egui has no opinion about it until told.
144//! - **App-level chrome is not drawn here, and it is not this crate's to
145//!   draw.** `quasi-router` names the affordances that outlive one screen: a
146//!   `Chrome` of key bindings, and an `Outcome::Over` for a screen drawn over
147//!   another. Both are answered by `quasi-webview` and `quasi-tui`, and neither
148//!   is answerable here, because this crate depends on `makeover-layout` and
149//!   not on `quasi-router` — it is the peer of `makeover-webview` and
150//!   `makeover-tui`, one layer below the renderers that consume a `Screen`.
151//!   What is missing is the egui crate at *that* layer, which does not exist:
152//!   nothing renders a quasi `Screen` in egui at all, and chrome is one item on
153//!   the list such a crate would owe. Said here because this is where a reader
154//!   looks for it, and because the silent version reads as "egui does not need
155//!   a palette" rather than "nobody has built the renderer yet".
156
157//! # 0.31.0: the slider's track is a curve
158//!
159//! `makeover-layout` 0.32.0 says what a slider is: a fraction and a function
160//! taking numbers to numbers, with `min` and `max` being `f(0)` and `f(1)`
161//! rather than the control's extent. This host has the easiest job of the
162//! three, because egui already has the control -- `Slider::logarithmic` is a
163//! constant-ratio track, so the mapping is a builder call rather than an
164//! arithmetic of its own.
165//!
166//! Two things worth knowing. The granularity moved onto the curve, so a range
167//! reads `Field::curve.step()` and every other kind still reads `Field::step`;
168//! the step is in the value's own units under either curve, so the display
169//! precision is derived exactly as before. And the fallback for a ratio curve
170//! across zero is asked of `Curve::is_ratio` rather than matched on the
171//! variant, so this renderer and a terminal cannot disagree about when a
172//! logarithmic request is honoured.
173//!
174//! # 0.28.0: the slider, the unanswered chooser, and the option that is not
175//! offered yet
176//!
177//! Three things `makeover-layout` 0.28.0 lets a description say, all three
178//! found by audiofiles' forms port hitting a wall it could not describe its way
179//! past.
180//!
181//! - **[`FieldKind::Range`] is a fifth control shape**, `Control::Slid`, and
182//!   the first one added since 0.5.0. egui has `Slider` and this crate had no
183//!   way to be asked for one, so four sliders in the only consuming app stayed
184//!   hand-rolled against a vocabulary that could not name them. A range missing
185//!   an end falls back to a well rather than to invented bounds, which is what
186//!   `makeover_layout::Field::bounded` is for.
187//! - **`Field::placeholder` finally reads on a chooser.** It was sayable and
188//!   this renderer ignored it, so a select with nothing chosen showed an empty
189//!   box. Nothing new is described; the renderer caught up.
190//! - **`Choice::unavailable` is drawn rather than dropped.** The option stays
191//!   in the list, inert, with its precondition beside it instead of behind a
192//!   hover — a greyed row with no reason reads as a dead end, which is the
193//!   whole finding.
194//!
195//! The value still arrives as a `&mut String` and a slider is a number, so the
196//! parse and the write-back are this renderer's, and the write happens only on
197//! a real drag: a value the app put there that this host cannot read survives
198//! being looked at.
199
200#![forbid(unsafe_code)]
201
202use egui::{
203    Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Slider,
204    Stroke, TextEdit, Ui,
205};
206use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, Tone};
207use std::ops::RangeInclusive;
208
209/// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
210pub mod table;
211pub mod widget;
212
213/// The resolved colours this renderer needs, as flat values.
214///
215/// Built by the app from whatever it already uses to resolve a theme, then
216/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
217/// painted per widget per frame, and a map lookup per edge is a cost with
218/// nothing to show for it.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub struct Palette {
221    /// `surface-page`.
222    pub page: Color32,
223    /// `surface-raised`.
224    pub raised: Color32,
225    /// `surface-overlay`.
226    pub overlay: Color32,
227    /// `surface-well`.
228    ///
229    /// Required, not optional. makeover derives it for every theme from 2.3.0,
230    /// so a resolved palette without a well is not a thing that exists here.
231    /// It was an `Option` while that was untrue, and this renderer substituted
232    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
233    /// since a terminal can have the colour and still be unable to show it.
234    pub well: Color32,
235    /// `surface-sunken`.
236    ///
237    /// A surface set back from the one it sits on, by colour and nothing else.
238    /// Not a well: a well is a hole with an edge, and this has no edge. An
239    /// immediate-mode renderer paints an arbitrary rect, so unlike
240    /// `makeover-tui` it has no excuse for declining this one.
241    ///
242    /// Required rather than optional, on the same footing as `well`: all 31
243    /// themes makeover embeds author it.
244    pub sunken: Color32,
245    /// `bevel-light`.
246    pub bevel_light: Color32,
247    /// `bevel-dark`.
248    pub bevel_dark: Color32,
249    /// `elevation`.
250    ///
251    /// What a surface that floats OVER the page is cast onto it with. The one
252    /// intent here that is about a surface's relationship to the page rather
253    /// than about the surface, which is why it is a translucent near-black on
254    /// every theme rather than something read off the palette's own ramp.
255    ///
256    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
257    /// surface *in* the layout takes a bevel, and reaching for this on a panel
258    /// or a card is how a pre-Platinum look survives a conversion under a new
259    /// name.
260    ///
261    /// egui has a real answer for this where a terminal does not: see
262    /// [`Palette::cast`], which is the shadow to hand an
263    /// [`egui::Frame`](egui::Frame).
264    pub elevation: Color32,
265    /// `content`.
266    ///
267    /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
268    /// thing here that draws any: until then this crate painted surfaces and
269    /// edges and let the caller's own egui visuals answer for text.
270    pub content: Color32,
271    /// `content-secondary`.
272    ///
273    /// Inactive but usable: it still answers a press. The middle tone of the
274    /// three (wiki `three-tone-convention`), and the one an unchosen option in
275    /// a choice field takes. Added 0.26.0 for that widget, which drew every
276    /// option at full `content` and so said nothing about which one was
277    /// chosen beyond the dot egui paints.
278    ///
279    /// Not [`content_muted`](Self::content_muted), which carries a claim:
280    /// `State::Disabled` resolves to it, so a live control wearing it tells the
281    /// user it will not answer. `makeover-tui` draws the same widget the same
282    /// way from `makeover-tui@230bf63`.
283    ///
284    /// A step of `content` toward the page, derived at load by `makeover`
285    /// rather than authored, so it is read off the resolved theme here like
286    /// any other token and never re-derived.
287    pub content_secondary: Color32,
288    /// `content-muted`.
289    ///
290    /// A field's hint, and what
291    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
292    /// resolves to. Both readings come from the description rather than from
293    /// here: `State::Disabled` names this intent by token.
294    pub content_muted: Color32,
295    /// `action-primary`.
296    ///
297    /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
298    /// reason `content` was added 0.5.0 with the field renderer: a link in a
299    /// cell is the first thing here that needs the action intent, and a palette
300    /// should carry what is used.
301    ///
302    /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
303    /// separate. A cell holding a control took the cell's text colour until the
304    /// description could say otherwise, which is the drift `makeover-layout`
305    /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
306    pub action: Color32,
307    /// `danger`.
308    ///
309    /// A field's error message, a destructive control, a bar that has run over.
310    pub danger: Color32,
311    /// `success`.
312    ///
313    /// Added 0.18.0 with [`widget`], which is the first thing here that draws a
314    /// [`Tone`]. The three status intents arrive together and not one at a
315    /// time: [`Tone`] is five members wide and a resolver missing one has to
316    /// invent a colour for it, which is the substitution this crate spent
317    /// 0.2.0 removing from [`Palette::fill`].
318    pub success: Color32,
319    /// `warning`.
320    pub warning: Color32,
321    /// `info`.
322    pub info: Color32,
323}
324
325impl Palette {
326    /// Resolve a surface intent, or `None` for one this renderer does not know.
327    ///
328    /// A plain lookup. There is still no substitution: the old one existed only
329    /// while `surface-well` was underived, and every consumer reads the real
330    /// token now.
331    ///
332    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
333    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
334    /// stay total by inventing a colour for a member it has never heard of.
335    /// That is the substitution this crate spent 0.2.0 removing, so the return
336    /// type moved instead. Every member the description has today is answered
337    /// with `Some`.
338    #[must_use]
339    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
340        match fill {
341            Fill::Page => Some(self.page),
342            Fill::Raised => Some(self.raised),
343            Fill::Overlay => Some(self.overlay),
344            Fill::Well => Some(self.well),
345            Fill::Sunken => Some(self.sunken),
346            _ => None,
347        }
348    }
349
350    /// The colour a [`Tone`] reads as.
351    ///
352    /// Total, unlike [`fill`](Self::fill), and the difference is not an
353    /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
354    /// description layer settled tone at five members and grows surfaces, so a
355    /// total function here cannot be made to invent a colour by an upstream
356    /// release the way a total `fill` could.
357    ///
358    /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
359    /// its own, which is what "an ordinary fact" means: a neutral badge is text
360    /// in a box, not a fifth status.
361    #[must_use]
362    pub const fn tone(&self, tone: Tone) -> Color32 {
363        match tone {
364            Tone::Neutral => self.content,
365            Tone::Info => self.info,
366            Tone::Success => self.success,
367            Tone::Warning => self.warning,
368            Tone::Danger => self.danger,
369        }
370    }
371
372    /// The cast shadow for a surface that overlays the page.
373    ///
374    /// What "overlaying" means in immediate mode, answered rather than skipped.
375    /// egui already paints shadows for its menus and windows through
376    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
377    /// theme's tone instead of egui's own default, not to invent a painter here
378    /// the way [`paint_bevel`] had to.
379    ///
380    /// The geometry matches what `makeover-webview` composes, in points rather
381    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
382    /// menu sits just off the page rather than hovering above it.
383    ///
384    /// ```no_run
385    /// # let palette: makeover_immediate::Palette = unimplemented!();
386    /// # let ui: &mut egui::Ui = unimplemented!();
387    /// egui::Frame::popup(ui.style())
388    ///     .shadow(palette.cast())
389    ///     .show(ui, |ui| { ui.label("over the page"); });
390    /// ```
391    #[must_use]
392    pub const fn cast(&self) -> egui::Shadow {
393        egui::Shadow {
394            offset: [0, 2],
395            blur: 24,
396            spread: 0,
397            color: self.elevation,
398        }
399    }
400
401    /// Resolve a bevel edge intent.
402    #[must_use]
403    pub const fn edge(&self, edge: Edge) -> Color32 {
404        match edge {
405            Edge::Light => self.bevel_light,
406            Edge::Dark => self.bevel_dark,
407        }
408    }
409}
410
411/// The geometry a framed region is drawn with.
412///
413/// Every field is a value, which is why they all arrive from the caller:
414/// radius and border width belong to `makeover-geometry`, and margins come
415/// from its relational gaps.
416#[derive(Debug, Clone, Copy, PartialEq)]
417pub struct FrameStyle {
418    /// Corner radius. Square under the Platinum default.
419    pub radius: CornerRadius,
420    /// Inner margin between the frame and its contents.
421    pub margin: Margin,
422    /// Bevel stroke width, in points.
423    pub stroke: f32,
424}
425
426impl Default for FrameStyle {
427    /// A one-point square frame with no inner margin.
428    fn default() -> Self {
429        Self {
430            radius: CornerRadius::ZERO,
431            margin: Margin::ZERO,
432            stroke: 1.0,
433        }
434    }
435}
436
437/// Paint a two-tone edge just inside `rect`.
438///
439/// Fill first, bevel after: this adds two polylines and nothing else, so it
440/// composes over whatever is already there. That is what lets it go over an
441/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
442///
443/// Two three-point polylines meeting at opposite corners, rather than four
444/// segments, so egui mitres the corner joins instead of leaving a notch.
445///
446/// The dark polyline is drawn second, so the two corners where the runs meet
447/// take its tone. That is the right answer here rather than a concession.
448/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
449/// a renderer with room to divide one should; at the default one-point stroke
450/// the corner is a one-point square, so the division is sub-pixel and
451/// antialiasing resolves it to the same blend the mitre already gives. Splitting
452/// it would add a seam and no information. `makeover-tui` does split, because a
453/// terminal cell is large enough that not splitting costs a visible cell of edge
454/// weight — the same rule, at a resolution where it has something to say.
455pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
456    let (top_left, bottom_right) = bevel.edges();
457
458    // Inset by half a stroke so the line lands inside `rect` rather than
459    // straddling its edge, which on a fractional-scale display is the
460    // difference between one crisp pixel and two dim ones.
461    let r = rect.shrink(stroke / 2.0);
462
463    painter.add(Shape::line(
464        vec![r.left_bottom(), r.left_top(), r.right_top()],
465        Stroke::new(stroke, palette.edge(top_left)),
466    ));
467    painter.add(Shape::line(
468        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
469        Stroke::new(stroke, palette.edge(bottom_right)),
470    ));
471}
472
473/// Draw a region at a given [`Depth`]: its fill and its edge, together.
474///
475/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
476/// difference between level-with and painted-the-same-colour, and it is the
477/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
478/// page.
479pub fn frame<R>(
480    ui: &mut Ui,
481    depth: Depth,
482    palette: &Palette,
483    style: FrameStyle,
484    add_contents: impl FnOnce(&mut Ui) -> R,
485) -> R {
486    let mut f = egui::Frame::new()
487        .corner_radius(style.radius)
488        .inner_margin(style.margin);
489    // Two ways there is no fill to paint, and they collapse to the same
490    // outcome: the depth names none (Depth::Flat), or it names one this
491    // renderer cannot resolve. Either way the frame goes unfilled and the
492    // bevel below carries the depth on its own, which is the rule this
493    // module already documents for Flat.
494    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
495        f = f.fill(fill);
496    }
497    // A surface that overlays the page is cast onto it. [`Palette::cast`] has
498    // answered what that means here since 0.10.0 and nothing could reach it: a
499    // description had no way to say Overlay until makeover-layout 0.14.0, so
500    // the answer sat beside the question. Keyed off the fill rather than the
501    // variant, so it stays right for whatever else the description calls an
502    // overlay later.
503    if depth.fill() == Some(Fill::Overlay) {
504        f = f.shadow(palette.cast());
505    }
506    let framed = f.show(ui, add_contents);
507    if let Some(bevel) = depth.bevel() {
508        paint_bevel(
509            ui.painter(),
510            framed.response.rect,
511            bevel,
512            palette,
513            style.stroke,
514        );
515    }
516    framed.inner
517}
518
519/// The geometry a field group is drawn with.
520///
521/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
522/// `makeover-geometry` and arrives already resolved.
523#[derive(Debug, Clone, Copy, PartialEq)]
524pub struct FieldStyle {
525    /// The well a text control sits in.
526    pub frame: FrameStyle,
527    /// Between a field's own parts: its label, its control, its hint and its
528    /// error.
529    pub gap: f32,
530    /// Between one field and the next.
531    pub group_gap: f32,
532    /// What marks a required field, appended to its label.
533    ///
534    /// A knob rather than a constant, because it is the one piece of *copy* in
535    /// this crate and copy is not a renderer's call. A webview does not need it
536    /// at all — it emits the `required` attribute and the browser answers — so
537    /// this renderer is the first place where a compulsory field either shows
538    /// that it is or silently does not.
539    pub required_marker: &'static str,
540}
541
542impl Default for FieldStyle {
543    /// The default frame, no gaps, and an asterisk.
544    fn default() -> Self {
545        Self {
546            frame: FrameStyle::default(),
547            gap: 0.0,
548            group_gap: 0.0,
549            required_marker: "*",
550        }
551    }
552}
553
554/// What the field currently holds, borrowed from wherever the app keeps it.
555///
556/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
557/// place the two renderers are forced apart: there the value is read back out
558/// of the DOM after the fact, and here the widget writes through this borrow as
559/// it is edited. Same reason the description carries neither.
560///
561/// An enum rather than a bag of options, on the reasoning
562/// `makeover_webview::form::Value` records: a checkbox holding a string is
563/// unsayable here, where a struct would let it be said and then have to cope.
564#[derive(Debug, Default)]
565pub enum Filling<'a> {
566    /// Nothing to edit. The control is drawn and does not answer.
567    #[default]
568    Absent,
569    /// The buffer behind anything that takes typed text, a select included:
570    /// what a select holds is the `value` of one of its [`Choice`]s.
571    ///
572    /// [`Choice`]: makeover_layout::Choice
573    Text(&'a mut String),
574    /// A checkbox, on or off.
575    On(&'a mut bool),
576}
577
578/// The label, marked if the field is compulsory.
579fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
580    if field.required {
581        format!("{} {}", field.label, style.required_marker)
582    } else {
583        field.label.to_owned()
584    }
585}
586
587/// The four shapes a control comes in here, which is fewer than there are
588/// kinds.
589///
590/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
591/// ways egui has of asking for a value do not. Reducing the open set to this
592/// closed one in one total function is what keeps a new kind from needing a new
593/// arm at every match below.
594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
595enum Control {
596    /// Typed into, so it is drawn as a well: the user looks into it.
597    Typed,
598    /// Picked from a control that shows one option at a time. Pressed rather
599    /// than looked into, so egui's own control painting stands.
600    Chosen,
601    /// Picked from options that are all on screen at once.
602    ///
603    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
604    /// apart, and holding them apart is the whole content of
605    /// [`FieldKind::Radio`]: same question, and an answer the user can read
606    /// without opening anything.
607    Listed,
608    /// Held on or off.
609    Toggled,
610    /// Dragged across an extent that is on screen the whole time.
611    ///
612    /// Apart from [`Typed`](Self::Typed) for the reason
613    /// [`FieldKind::Range`] is apart from `Number`: the two ends are what the
614    /// question means, so a well with a figure in it is not a quieter version
615    /// of this control, it is a different one.
616    Slid,
617}
618
619/// Which shape a kind takes.
620///
621/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
622/// description since this renderer was built degrades to a text box, which
623/// accepts any value the others would, rather than to nothing drawn at all.
624///
625/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
626/// there rather than grown a shape of its own. egui's honest answer is a button
627/// that opens a native picker, which is a fifth control and a file-dialog
628/// dependency; no consumer of this crate asks for a file field yet. Same
629/// position this crate took on `Meter` at 0.10.0: the membership test is that
630/// every renderer *could* answer honestly, not that each one does on the day.
631/// A path in a text box is not nothing, and it is what an app that needs this
632/// tomorrow gets today.
633///
634/// makeover-layout 0.31.0 added `Field::accept` and `Field::multiple`, and this
635/// position is what they land on: both are the picker's arguments, and this
636/// renderer has no picker to give them to. They are not lost — the description
637/// still carries them, and the day the native dialog arrives here it is opened
638/// with them rather than with a filter written twice.
639///
640/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
641/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
642/// calendar is a sixth control and bare `egui` has none, so a typed value is
643/// the honest answer here; what the app gets is the format the description
644/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
645/// those are constants rather than a sentence. audiofiles is the only consumer
646/// of this crate and asks for neither today. A calendar popup is the upgrade
647/// whenever one does.
648const fn control_shape(kind: FieldKind) -> Control {
649    match kind {
650        FieldKind::Select => Control::Chosen,
651        FieldKind::Radio => Control::Listed,
652        FieldKind::Checkbox => Control::Toggled,
653        FieldKind::Range => Control::Slid,
654        _ => Control::Typed,
655    }
656}
657
658/// The shape the field actually gets, which is the kind's unless the field is
659/// missing what that shape needs.
660///
661/// One case, and `makeover-layout` names it: a [`FieldKind::Range`] carries its
662/// extent in [`Field::min`] and [`Field::max`], and a range missing an end has
663/// nothing to slide across. egui's `Slider` demands a `RangeInclusive`, so
664/// inventing one would be this renderer picking bounds the app never stated and
665/// the user then dragging against them.
666///
667/// It falls back to [`Control::Typed`], which is where every kind this renderer
668/// cannot draw natively already lands: a number in a well is a true report of
669/// the value and takes any answer the slider would.
670fn shape_of(field: &Field<'_>) -> Control {
671    match control_shape(field.kind) {
672        Control::Slid if !field.bounded() => Control::Typed,
673        shape => shape,
674    }
675}
676
677/// The two ends of a range, as egui wants them.
678///
679/// `None` when either end is missing or is not a number this host can read.
680/// The description carries the bounds as text on purpose — the bound of a date
681/// is a date — so parsing them is the renderer's job and failing to is a real
682/// outcome rather than an assertion.
683fn extent(field: &Field<'_>) -> Option<RangeInclusive<f64>> {
684    let min = field.min?.parse::<f64>().ok()?;
685    let max = field.max?.parse::<f64>().ok()?;
686    Some(min..=max)
687}
688
689/// How many decimals to write a dragged value back with.
690///
691/// Read off [`Field::step`], which is the only thing that says what
692/// granularity the question has: a step of `0.01` is a two-decimal question and
693/// a step of `1` is a whole-number one. Without a step the host's own
694/// granularity stands, and egui's is continuous, so the value is written back
695/// at whatever precision it round-trips at.
696fn decimals(step: Option<&str>) -> Option<usize> {
697    let step = step?;
698    Some(match step.split_once('.') {
699        Some((_, fraction)) => fraction.trim_end_matches('0').len(),
700        None => 0,
701    })
702}
703
704/// What a select shows for the value it currently holds.
705///
706/// A value no option carries stays on screen as itself rather than reading as
707/// whichever option happens to be first. goingson saved a backup retention of
708/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
709/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
710/// stray `<option>` and this is the same fix in the shape egui allows.
711///
712/// The empty value is the one case that reads as unanswered rather than as an
713/// answer, and [`chosen_text`] is what puts the field's ghost text there.
714fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
715    options
716        .iter()
717        .find(|opt| opt.value == value)
718        .map_or(value, |opt| opt.label)
719}
720
721/// What a select's closed control reads, and in which tone.
722///
723/// A chooser with nothing chosen showed an empty box: `shown_label` falls back
724/// to the value, and the unanswered value is the empty string. So an app with
725/// an instruction to give — audiofiles' "Select device..." — had nowhere to put
726/// it but a disabled button elsewhere on the screen, which is the affordance
727/// this vocabulary keeps moving messages *off*.
728///
729/// [`Field::placeholder`] is already the description's word for "what the field
730/// reads while it is empty" and was honoured by the typed kinds alone, so
731/// nothing new is said here; the renderer is what had not caught up. Muted
732/// because it is not an answer, the same tone the typed kinds' ghost text takes
733/// three lines up.
734///
735/// A value no option carries but that is *not* empty stays as itself, in
736/// `content`: that is the goingson retention bug and it is a wrong answer
737/// rather than an absent one.
738///
739/// Returns the words and the tone rather than a built [`RichText`], because
740/// what it decides is both of them and only one of them is readable back off a
741/// `RichText`.
742///
743/// [`Field::placeholder`]: makeover_layout::Field::placeholder
744fn chosen_text<'a>(field: &'a Field<'a>, value: &'a str, palette: &Palette) -> (&'a str, Color32) {
745    match field.placeholder {
746        Some(ghost) if value.is_empty() => (ghost, palette.content_muted),
747        _ => (shown_label(field.options, value), palette.content),
748    }
749}
750
751/// What one option in a choice field is drawn in.
752///
753/// The chosen one is the emphasised thing and takes `content`; the rest take
754/// [`content_secondary`](Palette::content_secondary), because an option that is
755/// not chosen is still an option and pressing it chooses it. Muted would be the
756/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
757/// live row and four dead ones. `makeover-tui` draws it the same way
758/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
759fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
760    if value == option {
761        palette.content
762    } else {
763        palette.content_secondary
764    }
765}
766
767/// The control alone, without its label, hint or error.
768fn control(
769    ui: &mut Ui,
770    field: &Field<'_>,
771    filling: Filling<'_>,
772    palette: &Palette,
773    style: &FieldStyle,
774) -> Response {
775    // The mismatch path: described as one thing and filled as another. Nothing
776    // here can fix it, so it is drawn as the empty, inert version of what was
777    // described — visible on screen, in the way an empty select is at the
778    // webview renderer, rather than reported in a log nobody reads.
779    let mut discard = String::new();
780    let mut off = false;
781
782    match shape_of(field) {
783        Control::Slid => {
784            let value = match filling {
785                Filling::Text(text) => text,
786                _ => &mut discard,
787            };
788            // `shape_of` has already refused an unbounded range, so the extent
789            // is only missing here if a bound is not a number — a date range,
790            // say, which this control cannot draw either.
791            let Some(extent) = extent(field) else {
792                return ui.label(RichText::new(value.as_str()).color(palette.content));
793            };
794
795            // A value the host cannot read starts at the low end rather than at
796            // zero, which may be outside the extent entirely. Nothing is
797            // written back until the user drags, so an unreadable value the app
798            // put there survives being looked at.
799            let mut number = value.parse::<f64>().unwrap_or(*extent.start());
800            // The granularity is the curve's as of makeover-layout 0.32.0. It
801            // is still in the value's own units, so the display precision is
802            // read off it exactly as before.
803            let step = field.curve.step();
804            let mut slider = Slider::new(&mut number, extent.clone()).text("");
805            if let Some(places) = decimals(step) {
806                slider = slider.max_decimals(places);
807            }
808            if let Some(step) = step.and_then(|s| s.parse::<f64>().ok()) {
809                slider = slider.step_by(step);
810            }
811            // egui's own constant-ratio track, which is this host's answer to
812            // `Curve::Logarithmic`. `is_ratio` rather than a match on the
813            // variant, because a ratio across zero is not one: makeover-layout
814            // decides the fallback so that four renderers cannot disagree about
815            // when it applies.
816            if field.curve.is_ratio(*extent.start(), *extent.end()) {
817                slider = slider.logarithmic(true);
818            }
819            let response = ui.add(slider);
820            if response.changed() {
821                *value = match decimals(step) {
822                    Some(places) => format!("{number:.places$}"),
823                    None => number.to_string(),
824                };
825            }
826            response
827        }
828        Control::Typed => {
829            let text = match filling {
830                Filling::Text(text) => text,
831                _ => &mut discard,
832            };
833            // An empty frame and no margin: the well is this crate's, and egui's
834            // own control background and padding would sit underneath it saying
835            // something different about both.
836            // Keyed on the description's own `multiline` and not on the
837            // member: a markdown field is several lines by definition, and a
838            // single-line edit would be a control the value cannot fit in. egui
839            // does nothing else with the markdown, which is the honest answer
840            // rather than a gap -- the source is text, and editing it as text
841            // loses none of it.
842            let mut edit = if field.kind.multiline() {
843                TextEdit::multiline(text)
844            } else {
845                TextEdit::singleline(text)
846            }
847            .frame(egui::Frame::NONE)
848            .margin(Margin::ZERO)
849            .text_color(palette.content)
850            .password(field.kind.confidential());
851            if let Some(ghost) = field.placeholder {
852                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
853            }
854            frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
855        }
856        Control::Toggled => {
857            let on = match filling {
858                Filling::On(on) => on,
859                _ => &mut off,
860            };
861            ui.checkbox(on, RichText::new(field.label).color(palette.content))
862        }
863        Control::Listed => {
864            let value = match filling {
865                Filling::Text(text) => text,
866                _ => &mut discard,
867            };
868            // No `shown_label` counterpart, and none is needed: a value no
869            // option carries leaves every button unfilled, which is already
870            // the honest report on screen. The select needs the fix because it
871            // has one slot and must put *something* in it.
872            let group = ui.vertical(|ui| {
873                let mut answered: Option<Response> = None;
874                for opt in field.options {
875                    // An option that cannot be picked yet is drawn and does not
876                    // answer, with the precondition beside it rather than
877                    // behind a hover: a greyed row with no reason reads as a
878                    // dead end, which is the state `Choice::unavailable` exists
879                    // to stop being sayable.
880                    let picked = if let Some(reason) = opt.unavailable {
881                        ui.horizontal(|ui| {
882                            let picked = ui
883                                .add_enabled_ui(false, |ui| {
884                                    ui.radio_value(
885                                        value,
886                                        opt.value.to_owned(),
887                                        RichText::new(opt.label).color(palette.content_muted),
888                                    )
889                                })
890                                .inner;
891                            ui.label(RichText::new(reason).color(palette.content_muted));
892                            picked
893                        })
894                        .inner
895                    } else {
896                        ui.radio_value(
897                            value,
898                            opt.value.to_owned(),
899                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
900                        )
901                    };
902                    answered = Some(match answered {
903                        Some(prev) => prev.union(picked),
904                        None => picked,
905                    });
906                }
907                answered
908            });
909            // A group described with no options answers as its own empty area
910            // rather than as no response at all, which keeps the caller's
911            // `.changed()` chain working on a field whose option list has not
912            // loaded yet.
913            group.inner.unwrap_or(group.response)
914        }
915        Control::Chosen => {
916            let value = match filling {
917                Filling::Text(text) => text,
918                _ => &mut discard,
919            };
920            let (shown, tone) = chosen_text(field, value, palette);
921            ComboBox::from_id_salt(field.name)
922                .selected_text(RichText::new(shown).color(tone))
923                .show_ui(ui, |ui| {
924                    for opt in field.options {
925                        // Same rule as the radio group: shown, inert, and
926                        // saying why. A closed control hides its list, so the
927                        // reason has to travel with the row it belongs to.
928                        if let Some(reason) = opt.unavailable {
929                            ui.add_enabled_ui(false, |ui| {
930                                ui.selectable_value(
931                                    value,
932                                    opt.value.to_owned(),
933                                    RichText::new(format!("{}  {reason}", opt.label))
934                                        .color(palette.content_muted),
935                                );
936                            });
937                            continue;
938                        }
939                        ui.selectable_value(
940                            value,
941                            opt.value.to_owned(),
942                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
943                        );
944                    }
945                })
946                .response
947        }
948    }
949}
950
951/// One field, as the column the app drops into its form.
952///
953/// The anatomy is `makeover-webview`'s, so the two renderers put a form
954/// together the same way: label, control, hint, error, top to bottom, with a
955/// checkbox labelling itself instead of taking a label above.
956///
957/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
958/// [`FieldKind::visible`] means and is the honest answer here: a webview still
959/// emits an input for it because the form submits, and an immediate-mode
960/// renderer has no form and no submission, so a hidden field is a value the app
961/// already holds and there is nothing to draw or to respond to.
962///
963/// `state` is the description's interaction axis.
964/// [`State::Disabled`] greys the field and stops it answering, through
965/// [`State::suppresses_interaction`] rather than through a second reading of
966/// what disabled means. Focus is not on that axis and never reaches here: egui
967/// owns reach, focus and the ring for this renderer, and one ring means not a
968/// second one per renderer that happens to have opinions.
969pub fn field(
970    ui: &mut Ui,
971    field: &Field<'_>,
972    filling: Filling<'_>,
973    state: Option<State>,
974    palette: &Palette,
975    style: &FieldStyle,
976) -> Option<Response> {
977    if !field.kind.visible() {
978        return None;
979    }
980    let enabled = !state.is_some_and(State::suppresses_interaction);
981    let text = if enabled {
982        palette.content
983    } else {
984        palette.content_muted
985    };
986
987    let response = ui
988        .vertical(|ui| {
989            ui.spacing_mut().item_spacing.y = style.gap;
990
991            // A checkbox labels itself, on the right of the box.
992            // `FieldKind::labels_itself` is the description saying so, and both
993            // webview apps special-cased it inline before it did.
994            if !field.kind.labels_itself() {
995                ui.label(RichText::new(label_text(field, style)).color(text));
996            }
997
998            let response = ui
999                .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
1000                .inner;
1001
1002            // Standing help first, then what is wrong now. Both, in that order,
1003            // for the reason the webview renderer names both in
1004            // `aria-describedby`: an error appearing must not take the hint
1005            // away with it.
1006            if let Some(hint) = field.hint {
1007                ui.label(RichText::new(hint).color(palette.content_muted));
1008            }
1009            if let Some(error) = field.error {
1010                ui.label(RichText::new(error).color(palette.danger));
1011            }
1012            response
1013        })
1014        .inner;
1015
1016    Some(response)
1017}
1018
1019/// A set of fields, laid down a column.
1020///
1021/// `show_extended` is the disclosure, and it is a parameter rather than state
1022/// held here because the disclosure belongs to the *form* and not to any field:
1023/// [`Field::extended`] marks which fields are behind one, and the app owns
1024/// whether it is open. That is the same division `makeover-webview` draws when
1025/// it marks the group `data-extended` and emits no control to toggle it.
1026///
1027/// `draw` is called once per field that should be visible, in order. Taking a
1028/// callback rather than a slice of [`Filling`]s is what keeps the app's own
1029/// values borrowed one at a time: a form's fields usually live in different
1030/// structs, and a parallel array would have to be built each frame and kept in
1031/// step with the description by hand.
1032pub fn group<'a>(
1033    ui: &mut Ui,
1034    fields: &'a [Field<'a>],
1035    show_extended: bool,
1036    style: &FieldStyle,
1037    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
1038) {
1039    ui.vertical(|ui| {
1040        ui.spacing_mut().item_spacing.y = style.group_gap;
1041        for f in fields {
1042            if f.extended && !show_extended {
1043                continue;
1044            }
1045            draw(ui, f);
1046        }
1047    });
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052    use super::*;
1053
1054    fn palette(well: Color32) -> Palette {
1055        Palette {
1056            page: Color32::from_rgb(1, 1, 1),
1057            raised: Color32::from_rgb(2, 2, 2),
1058            overlay: Color32::from_rgb(3, 3, 3),
1059            well,
1060            sunken: Color32::from_rgb(4, 4, 4),
1061            bevel_light: Color32::WHITE,
1062            bevel_dark: Color32::BLACK,
1063            elevation: Color32::from_black_alpha(46),
1064            content: Color32::from_rgb(5, 5, 5),
1065            content_secondary: Color32::from_rgb(55, 55, 55),
1066            content_muted: Color32::from_rgb(6, 6, 6),
1067            action: Color32::from_rgb(7, 7, 7),
1068            danger: Color32::from_rgb(8, 8, 8),
1069            success: Color32::from_rgb(9, 9, 9),
1070            warning: Color32::from_rgb(10, 10, 10),
1071            info: Color32::from_rgb(11, 11, 11),
1072        }
1073    }
1074
1075    /// The cast is egui's own shadow type carrying the theme's tone, which is
1076    /// the whole of what this crate had to decide for it: unlike a bevel, egui
1077    /// already knows how to paint one.
1078    #[test]
1079    fn the_cast_hands_egui_the_themes_tone() {
1080        let p = palette(Color32::from_rgb(9, 9, 9));
1081        let cast = p.cast();
1082        assert_eq!(cast.color, p.elevation);
1083        assert!(cast.blur > 0, "a cast shadow is soft");
1084        assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
1085    }
1086
1087    #[test]
1088    fn a_well_resolves_to_its_own_token() {
1089        // No substitution left. The page-filled well was a stand-in for a
1090        // token that did not exist yet; it exists now.
1091        let w = Color32::from_rgb(9, 9, 9);
1092        let p = palette(w);
1093        assert_eq!(p.fill(Fill::Well), Some(w));
1094        assert_ne!(p.fill(Fill::Well), Some(p.page));
1095    }
1096
1097    #[test]
1098    fn every_intent_is_a_plain_lookup() {
1099        let p = palette(Color32::from_rgb(9, 9, 9));
1100        assert_eq!(p.fill(Fill::Page), Some(p.page));
1101        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
1102        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
1103    }
1104
1105    /// Sunken is its own colour, not the well's and not the page's. The two
1106    /// are authored in opposite directions and an earlier cut of the
1107    /// description conflated them.
1108    #[test]
1109    fn sunken_is_neither_the_well_nor_the_page() {
1110        let p = palette(Color32::from_rgb(9, 9, 9));
1111        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
1112        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
1113        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
1114    }
1115
1116    #[test]
1117    fn a_raised_region_never_resolves_to_the_well_fill() {
1118        // The cross-app bug, asserted at the renderer boundary this time.
1119        let p = palette(Color32::from_rgb(9, 9, 9));
1120        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
1121        let well = Depth::Well.fill().and_then(|f| p.fill(f));
1122        assert_eq!(raised, Some(p.raised));
1123        assert_ne!(raised, well);
1124    }
1125
1126    #[test]
1127    fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
1128        // makeover-layout 0.14.0 is what made this reachable. The answer was
1129        // already here at 0.10.0 and the question could not be asked.
1130        let p = palette(Color32::from_rgb(9, 9, 9));
1131        assert_eq!(
1132            Depth::Overlay.fill().and_then(|f| p.fill(f)),
1133            Some(p.overlay)
1134        );
1135        assert_eq!(Depth::Overlay.bevel(), None);
1136        // The shadow `frame` reaches for is the theme's tone rather than
1137        // egui's default, which is the whole reason `cast` exists.
1138        assert_eq!(p.cast().color, p.elevation);
1139    }
1140
1141    #[test]
1142    fn the_lit_edge_swaps_when_a_card_is_pressed() {
1143        let p = palette(Color32::from_rgb(9, 9, 9));
1144        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
1145        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
1146        assert_eq!(p.edge(tl), p.bevel_light);
1147        assert_eq!(p.edge(ptl), p.bevel_dark);
1148    }
1149
1150    #[test]
1151    fn flat_asks_for_neither_fill_nor_edge() {
1152        assert!(Depth::Flat.fill().is_none());
1153        assert!(Depth::Flat.bevel().is_none());
1154    }
1155
1156    #[test]
1157    fn a_select_keeps_a_value_none_of_its_options_carries() {
1158        // The save-the-wrong-thing bug, asserted at the second renderer so it
1159        // is not re-found there. goingson's own numbers.
1160        let options = [
1161            Choice::plain("1"),
1162            Choice::plain("3"),
1163            Choice::plain("7"),
1164            Choice::plain("14"),
1165        ];
1166        assert_eq!(shown_label(&options, "10"), "10");
1167        // And a value that does match reads as its label, not as itself.
1168        let spelled = [Choice::new("7", "One week")];
1169        assert_eq!(shown_label(&spelled, "7"), "One week");
1170    }
1171
1172    #[test]
1173    fn an_unanswered_chooser_reads_its_ghost_text_and_reads_it_muted() {
1174        let p = palette(Color32::from_rgb(9, 9, 9));
1175        let options = [Choice::new("sp404", "SP-404")];
1176        let field = Field {
1177            placeholder: Some("Select device..."),
1178            ..Field::select("device", "Conform for device", &options)
1179        };
1180
1181        assert_eq!(
1182            chosen_text(&field, "", &p),
1183            ("Select device...", p.content_muted),
1184            "ghost text is not an answer, so it takes the tone the typed kinds' ghost text does"
1185        );
1186
1187        // Answered, and it is the label that reads rather than the value.
1188        assert_eq!(chosen_text(&field, "sp404", &p), ("SP-404", p.content));
1189    }
1190
1191    #[test]
1192    fn a_wrong_answer_is_not_an_absent_one() {
1193        // The retention-10 bug and the ghost text meet here: a value no option
1194        // carries still reads as itself, because the field IS answered and the
1195        // answer is wrong. Only the empty value is unanswered.
1196        let p = palette(Color32::from_rgb(9, 9, 9));
1197        let options = [Choice::plain("1"), Choice::plain("7")];
1198        let field = Field {
1199            placeholder: Some("Pick one"),
1200            ..Field::select("retention", "Keep backups for", &options)
1201        };
1202
1203        assert_eq!(chosen_text(&field, "10", &p), ("10", p.content));
1204    }
1205
1206    #[test]
1207    fn a_chooser_with_no_ghost_text_is_unchanged() {
1208        // The whole change is opt-in from the description. A field that says
1209        // nothing about its empty state still shows an empty box.
1210        let p = palette(Color32::from_rgb(9, 9, 9));
1211        let options = [Choice::plain("1")];
1212        let field = Field::select("retention", "Keep backups for", &options);
1213        assert_eq!(chosen_text(&field, "", &p), ("", p.content));
1214    }
1215
1216    #[test]
1217    fn a_range_is_slid_and_a_number_is_typed_into() {
1218        // The distinction the kind was added for, at the renderer that has to
1219        // act on it. A well with a figure in it is not a quiet slider.
1220        assert_eq!(control_shape(FieldKind::Range), Control::Slid);
1221        assert_eq!(control_shape(FieldKind::Number), Control::Typed);
1222    }
1223
1224    #[test]
1225    fn a_range_missing_an_end_falls_back_to_a_well() {
1226        // egui's `Slider` demands both ends, so inventing one would be this
1227        // renderer picking bounds the app never stated and the user then
1228        // dragging against them. A typed number takes every answer the slider
1229        // would.
1230        let whole = Field::range("review", "Review above", "0", "1");
1231        assert_eq!(shape_of(&whole), Control::Slid);
1232
1233        let half = Field {
1234            max: Some("1"),
1235            ..Field::new(FieldKind::Range, "review", "Review above")
1236        };
1237        assert_eq!(shape_of(&half), Control::Typed);
1238        assert_eq!(extent(&half), None);
1239
1240        // A bound this host cannot read is the same outcome by a different
1241        // route: the description carries bounds as text because the bound of a
1242        // date is a date.
1243        let dated = Field::range("when", "When", "2026-08-01", "2026-08-31");
1244        assert_eq!(extent(&dated), None);
1245    }
1246
1247    #[test]
1248    fn the_step_decides_how_a_dragged_value_is_written_back() {
1249        // Without it a 0-to-1 threshold writes back whatever float the drag
1250        // landed on, which is the host's granularity and is what the
1251        // description says an absent step means.
1252        assert_eq!(decimals(None), None);
1253        assert_eq!(decimals(Some("1")), Some(0));
1254        assert_eq!(decimals(Some("0.01")), Some(2));
1255        // Trailing zeros are not precision: 0.10 is a one-decimal question.
1256        assert_eq!(decimals(Some("0.10")), Some(1));
1257    }
1258
1259    #[test]
1260    fn an_unavailable_option_is_drawn_muted_rather_than_dropped() {
1261        // The tone rule, at the one place it is a claim rather than a
1262        // preference: this option genuinely will not answer, so muted is the
1263        // truth. The available ones beside it keep the secondary intent.
1264        let p = palette(Color32::from_rgb(9, 9, 9));
1265        let options = [
1266            Choice::new("chromatic", "Chromatic"),
1267            Choice::new("multi", "Multi-sample").unless("Drop a second sample."),
1268        ];
1269        assert!(options[0].available());
1270        assert!(!options[1].available());
1271        assert_eq!(
1272            option_color("chromatic", options[0].value, &p),
1273            p.content,
1274            "the chosen option is the emphasised thing"
1275        );
1276        assert_eq!(
1277            option_color("chromatic", options[1].value, &p),
1278            p.content_secondary,
1279            "and `option_color` never mutes: the unavailable path is what does"
1280        );
1281    }
1282
1283    #[test]
1284    fn only_a_required_field_is_marked() {
1285        let style = FieldStyle::default();
1286        let plain = Field::new(FieldKind::Text, "title", "Title");
1287        assert_eq!(label_text(&plain, &style), "Title");
1288
1289        let required = Field {
1290            required: true,
1291            ..plain
1292        };
1293        assert_eq!(label_text(&required, &style), "Title *");
1294
1295        // The marker is copy and the app owns it, which is why it is a knob.
1296        let house = FieldStyle {
1297            required_marker: "(required)",
1298            ..style
1299        };
1300        assert_eq!(label_text(&required, &house), "Title (required)");
1301    }
1302
1303    #[test]
1304    fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
1305        // What decides whether the control gets a well. A well is for what the
1306        // user looks into, and only one of these is.
1307        assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
1308        assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
1309        assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
1310        for k in [
1311            FieldKind::Text,
1312            FieldKind::Secret,
1313            FieldKind::Number,
1314            FieldKind::Email,
1315            FieldKind::Url,
1316            FieldKind::Tel,
1317            FieldKind::Textarea,
1318            FieldKind::Rich,
1319        ] {
1320            assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
1321        }
1322        // And the two multi-line ones get a multi-line edit, which is the half
1323        // `control_shape` alone does not say: both are typed into, and only one
1324        // of the two edit shapes can hold a markdown document.
1325        assert!(FieldKind::Rich.multiline());
1326        assert!(FieldKind::Textarea.multiline());
1327        assert!(!FieldKind::Text.multiline());
1328    }
1329
1330    #[test]
1331    fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
1332        // The description holds Select and Radio apart, and a renderer that
1333        // collapsed them would silently answer a question the app did not ask:
1334        // audiofiles' storage style is irreversible and its alternatives have
1335        // to be readable without opening anything. Asserting the two shapes
1336        // differ is asserting that distinction survives the trip.
1337        assert!(FieldKind::Select.offers_options());
1338        assert!(FieldKind::Radio.offers_options());
1339        assert_ne!(
1340            control_shape(FieldKind::Select),
1341            control_shape(FieldKind::Radio)
1342        );
1343    }
1344
1345    #[test]
1346    fn an_unchosen_option_is_secondary_and_never_muted() {
1347        let p = palette(Color32::from_rgb(4, 4, 4));
1348        assert_eq!(option_color("wav", "wav", &p), p.content);
1349        assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1350        // The whole point of the distinction: muted is what Disabled resolves
1351        // to, so an option wearing it would claim it does not answer a press.
1352        assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1353    }
1354
1355    #[test]
1356    fn a_hidden_field_draws_nothing_and_answers_nothing() {
1357        // Where the two renderers legitimately part: a webview still emits an
1358        // input because the form submits, and there is no form here.
1359        let f = Field::new(FieldKind::Hidden, "id", "Id");
1360        let p = palette(Color32::from_rgb(9, 9, 9));
1361        egui::__run_test_ui(|ui| {
1362            let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1363            assert!(drawn.is_none());
1364        });
1365    }
1366
1367    #[test]
1368    fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1369        let f = Field::new(FieldKind::Text, "title", "Title");
1370        let p = palette(Color32::from_rgb(9, 9, 9));
1371        let style = FieldStyle::default();
1372        egui::__run_test_ui(|ui| {
1373            let mut text = String::from("x");
1374            let disabled = field(
1375                ui,
1376                &f,
1377                Filling::Text(&mut text),
1378                Some(State::Disabled),
1379                &p,
1380                &style,
1381            )
1382            .unwrap();
1383            assert!(!disabled.enabled());
1384
1385            // Stating no state is the ordinary case and answers. Focus used to
1386            // be the counter-example here; it is egui's now and a description
1387            // cannot state it at all.
1388            let mut text = String::from("x");
1389            let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1390            assert!(plain.enabled(), "an unstated field still answers");
1391        });
1392    }
1393
1394    #[test]
1395    fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1396        // No panic and no write-through. A checkbox handed a string cannot be
1397        // filled, so it is drawn off and left alone.
1398        let f = Field::new(FieldKind::Checkbox, "done", "Done");
1399        let p = palette(Color32::from_rgb(9, 9, 9));
1400        let mut text = String::from("untouched");
1401        egui::__run_test_ui(|ui| {
1402            let drawn = field(
1403                ui,
1404                &f,
1405                Filling::Text(&mut text),
1406                None,
1407                &p,
1408                &FieldStyle::default(),
1409            );
1410            assert!(drawn.is_some());
1411        });
1412        assert_eq!(text, "untouched");
1413    }
1414
1415    #[test]
1416    fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
1417        let fields = [
1418            Field::new(FieldKind::Text, "title", "Title"),
1419            Field {
1420                extended: true,
1421                ..Field::new(FieldKind::Text, "notes", "Notes")
1422            },
1423        ];
1424        let style = FieldStyle::default();
1425
1426        let mut closed = Vec::new();
1427        egui::__run_test_ui(|ui| {
1428            group(ui, &fields, false, &style, |_, f| closed.push(f.name));
1429        });
1430        assert_eq!(closed, ["title"]);
1431
1432        let mut open = Vec::new();
1433        egui::__run_test_ui(|ui| {
1434            group(ui, &fields, true, &style, |_, f| open.push(f.name));
1435        });
1436        assert_eq!(open, ["title", "notes"]);
1437    }
1438
1439    #[test]
1440    fn the_default_frame_is_square_and_one_point() {
1441        let d = FrameStyle::default();
1442        assert_eq!(d.radius, CornerRadius::ZERO);
1443        assert_eq!(d.margin, Margin::ZERO);
1444        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1445    }
1446}