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