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