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#![forbid(unsafe_code)]
158
159use egui::{
160    Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke,
161    TextEdit, Ui,
162};
163use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State, Tone};
164
165/// Columns, narrowing, cell parts and the sort caret, over `egui_extras`.
166pub mod table;
167pub mod widget;
168
169/// The resolved colours this renderer needs, as flat values.
170///
171/// Built by the app from whatever it already uses to resolve a theme, then
172/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
173/// painted per widget per frame, and a map lookup per edge is a cost with
174/// nothing to show for it.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct Palette {
177    /// `surface-page`.
178    pub page: Color32,
179    /// `surface-raised`.
180    pub raised: Color32,
181    /// `surface-overlay`.
182    pub overlay: Color32,
183    /// `surface-well`.
184    ///
185    /// Required, not optional. makeover derives it for every theme from 2.3.0,
186    /// so a resolved palette without a well is not a thing that exists here.
187    /// It was an `Option` while that was untrue, and this renderer substituted
188    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
189    /// since a terminal can have the colour and still be unable to show it.
190    pub well: Color32,
191    /// `surface-sunken`.
192    ///
193    /// A surface set back from the one it sits on, by colour and nothing else.
194    /// Not a well: a well is a hole with an edge, and this has no edge. An
195    /// immediate-mode renderer paints an arbitrary rect, so unlike
196    /// `makeover-tui` it has no excuse for declining this one.
197    ///
198    /// Required rather than optional, on the same footing as `well`: all 31
199    /// themes makeover embeds author it.
200    pub sunken: Color32,
201    /// `bevel-light`.
202    pub bevel_light: Color32,
203    /// `bevel-dark`.
204    pub bevel_dark: Color32,
205    /// `elevation`.
206    ///
207    /// What a surface that floats OVER the page is cast onto it with. The one
208    /// intent here that is about a surface's relationship to the page rather
209    /// than about the surface, which is why it is a translucent near-black on
210    /// every theme rather than something read off the palette's own ramp.
211    ///
212    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
213    /// surface *in* the layout takes a bevel, and reaching for this on a panel
214    /// or a card is how a pre-Platinum look survives a conversion under a new
215    /// name.
216    ///
217    /// egui has a real answer for this where a terminal does not: see
218    /// [`Palette::cast`], which is the shadow to hand an
219    /// [`egui::Frame`](egui::Frame).
220    pub elevation: Color32,
221    /// `content`.
222    ///
223    /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
224    /// thing here that draws any: until then this crate painted surfaces and
225    /// edges and let the caller's own egui visuals answer for text.
226    pub content: Color32,
227    /// `content-secondary`.
228    ///
229    /// Inactive but usable: it still answers a press. The middle tone of the
230    /// three (wiki `three-tone-convention`), and the one an unchosen option in
231    /// a choice field takes. Added 0.26.0 for that widget, which drew every
232    /// option at full `content` and so said nothing about which one was
233    /// chosen beyond the dot egui paints.
234    ///
235    /// Not [`content_muted`](Self::content_muted), which carries a claim:
236    /// `State::Disabled` resolves to it, so a live control wearing it tells the
237    /// user it will not answer. `makeover-tui` draws the same widget the same
238    /// way from `makeover-tui@230bf63`.
239    ///
240    /// A step of `content` toward the page, derived at load by `makeover`
241    /// rather than authored, so it is read off the resolved theme here like
242    /// any other token and never re-derived.
243    pub content_secondary: Color32,
244    /// `content-muted`.
245    ///
246    /// A field's hint, and what
247    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
248    /// resolves to. Both readings come from the description rather than from
249    /// here: `State::Disabled` names this intent by token.
250    pub content_muted: Color32,
251    /// `action-primary`.
252    ///
253    /// What a control is drawn in. Added 0.12.0 with the table renderer, for the
254    /// reason `content` was added 0.5.0 with the field renderer: a link in a
255    /// cell is the first thing here that needs the action intent, and a palette
256    /// should carry what is used.
257    ///
258    /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
259    /// separate. A cell holding a control took the cell's text colour until the
260    /// description could say otherwise, which is the drift `makeover-layout`
261    /// 0.14.0 named and `makeover-webview` 0.25.0 fixed on its own side.
262    pub action: Color32,
263    /// `danger`.
264    ///
265    /// A field's error message, a destructive control, a bar that has run over.
266    pub danger: Color32,
267    /// `success`.
268    ///
269    /// Added 0.18.0 with [`widget`], which is the first thing here that draws a
270    /// [`Tone`]. The three status intents arrive together and not one at a
271    /// time: [`Tone`] is five members wide and a resolver missing one has to
272    /// invent a colour for it, which is the substitution this crate spent
273    /// 0.2.0 removing from [`Palette::fill`].
274    pub success: Color32,
275    /// `warning`.
276    pub warning: Color32,
277    /// `info`.
278    pub info: Color32,
279}
280
281impl Palette {
282    /// Resolve a surface intent, or `None` for one this renderer does not know.
283    ///
284    /// A plain lookup. There is still no substitution: the old one existed only
285    /// while `surface-well` was underived, and every consumer reads the real
286    /// token now.
287    ///
288    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
289    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
290    /// stay total by inventing a colour for a member it has never heard of.
291    /// That is the substitution this crate spent 0.2.0 removing, so the return
292    /// type moved instead. Every member the description has today is answered
293    /// with `Some`.
294    #[must_use]
295    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
296        match fill {
297            Fill::Page => Some(self.page),
298            Fill::Raised => Some(self.raised),
299            Fill::Overlay => Some(self.overlay),
300            Fill::Well => Some(self.well),
301            Fill::Sunken => Some(self.sunken),
302            _ => None,
303        }
304    }
305
306    /// The colour a [`Tone`] reads as.
307    ///
308    /// Total, unlike [`fill`](Self::fill), and the difference is not an
309    /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
310    /// description layer settled tone at five members and grows surfaces, so a
311    /// total function here cannot be made to invent a colour by an upstream
312    /// release the way a total `fill` could.
313    ///
314    /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
315    /// its own, which is what "an ordinary fact" means: a neutral badge is text
316    /// in a box, not a fifth status.
317    #[must_use]
318    pub const fn tone(&self, tone: Tone) -> Color32 {
319        match tone {
320            Tone::Neutral => self.content,
321            Tone::Info => self.info,
322            Tone::Success => self.success,
323            Tone::Warning => self.warning,
324            Tone::Danger => self.danger,
325        }
326    }
327
328    /// The cast shadow for a surface that overlays the page.
329    ///
330    /// What "overlaying" means in immediate mode, answered rather than skipped.
331    /// egui already paints shadows for its menus and windows through
332    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
333    /// theme's tone instead of egui's own default, not to invent a painter here
334    /// the way [`paint_bevel`] had to.
335    ///
336    /// The geometry matches what `makeover-webview` composes, in points rather
337    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
338    /// menu sits just off the page rather than hovering above it.
339    ///
340    /// ```no_run
341    /// # let palette: makeover_immediate::Palette = unimplemented!();
342    /// # let ui: &mut egui::Ui = unimplemented!();
343    /// egui::Frame::popup(ui.style())
344    ///     .shadow(palette.cast())
345    ///     .show(ui, |ui| { ui.label("over the page"); });
346    /// ```
347    #[must_use]
348    pub const fn cast(&self) -> egui::Shadow {
349        egui::Shadow {
350            offset: [0, 2],
351            blur: 24,
352            spread: 0,
353            color: self.elevation,
354        }
355    }
356
357    /// Resolve a bevel edge intent.
358    #[must_use]
359    pub const fn edge(&self, edge: Edge) -> Color32 {
360        match edge {
361            Edge::Light => self.bevel_light,
362            Edge::Dark => self.bevel_dark,
363        }
364    }
365}
366
367/// The geometry a framed region is drawn with.
368///
369/// Every field is a value, which is why they all arrive from the caller:
370/// radius and border width belong to `makeover-geometry`, and margins come
371/// from its relational gaps.
372#[derive(Debug, Clone, Copy, PartialEq)]
373pub struct FrameStyle {
374    /// Corner radius. Square under the Platinum default.
375    pub radius: CornerRadius,
376    /// Inner margin between the frame and its contents.
377    pub margin: Margin,
378    /// Bevel stroke width, in points.
379    pub stroke: f32,
380}
381
382impl Default for FrameStyle {
383    /// A one-point square frame with no inner margin.
384    fn default() -> Self {
385        Self {
386            radius: CornerRadius::ZERO,
387            margin: Margin::ZERO,
388            stroke: 1.0,
389        }
390    }
391}
392
393/// Paint a two-tone edge just inside `rect`.
394///
395/// Fill first, bevel after: this adds two polylines and nothing else, so it
396/// composes over whatever is already there. That is what lets it go over an
397/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
398///
399/// Two three-point polylines meeting at opposite corners, rather than four
400/// segments, so egui mitres the corner joins instead of leaving a notch.
401///
402/// The dark polyline is drawn second, so the two corners where the runs meet
403/// take its tone. That is the right answer here rather than a concession.
404/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
405/// a renderer with room to divide one should; at the default one-point stroke
406/// the corner is a one-point square, so the division is sub-pixel and
407/// antialiasing resolves it to the same blend the mitre already gives. Splitting
408/// it would add a seam and no information. `makeover-tui` does split, because a
409/// terminal cell is large enough that not splitting costs a visible cell of edge
410/// weight — the same rule, at a resolution where it has something to say.
411pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
412    let (top_left, bottom_right) = bevel.edges();
413
414    // Inset by half a stroke so the line lands inside `rect` rather than
415    // straddling its edge, which on a fractional-scale display is the
416    // difference between one crisp pixel and two dim ones.
417    let r = rect.shrink(stroke / 2.0);
418
419    painter.add(Shape::line(
420        vec![r.left_bottom(), r.left_top(), r.right_top()],
421        Stroke::new(stroke, palette.edge(top_left)),
422    ));
423    painter.add(Shape::line(
424        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
425        Stroke::new(stroke, palette.edge(bottom_right)),
426    ));
427}
428
429/// Draw a region at a given [`Depth`]: its fill and its edge, together.
430///
431/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
432/// difference between level-with and painted-the-same-colour, and it is the
433/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
434/// page.
435pub fn frame<R>(
436    ui: &mut Ui,
437    depth: Depth,
438    palette: &Palette,
439    style: FrameStyle,
440    add_contents: impl FnOnce(&mut Ui) -> R,
441) -> R {
442    let mut f = egui::Frame::new()
443        .corner_radius(style.radius)
444        .inner_margin(style.margin);
445    // Two ways there is no fill to paint, and they collapse to the same
446    // outcome: the depth names none (Depth::Flat), or it names one this
447    // renderer cannot resolve. Either way the frame goes unfilled and the
448    // bevel below carries the depth on its own, which is the rule this
449    // module already documents for Flat.
450    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
451        f = f.fill(fill);
452    }
453    // A surface that overlays the page is cast onto it. [`Palette::cast`] has
454    // answered what that means here since 0.10.0 and nothing could reach it: a
455    // description had no way to say Overlay until makeover-layout 0.14.0, so
456    // the answer sat beside the question. Keyed off the fill rather than the
457    // variant, so it stays right for whatever else the description calls an
458    // overlay later.
459    if depth.fill() == Some(Fill::Overlay) {
460        f = f.shadow(palette.cast());
461    }
462    let framed = f.show(ui, add_contents);
463    if let Some(bevel) = depth.bevel() {
464        paint_bevel(
465            ui.painter(),
466            framed.response.rect,
467            bevel,
468            palette,
469            style.stroke,
470        );
471    }
472    framed.inner
473}
474
475/// The geometry a field group is drawn with.
476///
477/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
478/// `makeover-geometry` and arrives already resolved.
479#[derive(Debug, Clone, Copy, PartialEq)]
480pub struct FieldStyle {
481    /// The well a text control sits in.
482    pub frame: FrameStyle,
483    /// Between a field's own parts: its label, its control, its hint and its
484    /// error.
485    pub gap: f32,
486    /// Between one field and the next.
487    pub group_gap: f32,
488    /// What marks a required field, appended to its label.
489    ///
490    /// A knob rather than a constant, because it is the one piece of *copy* in
491    /// this crate and copy is not a renderer's call. A webview does not need it
492    /// at all — it emits the `required` attribute and the browser answers — so
493    /// this renderer is the first place where a compulsory field either shows
494    /// that it is or silently does not.
495    pub required_marker: &'static str,
496}
497
498impl Default for FieldStyle {
499    /// The default frame, no gaps, and an asterisk.
500    fn default() -> Self {
501        Self {
502            frame: FrameStyle::default(),
503            gap: 0.0,
504            group_gap: 0.0,
505            required_marker: "*",
506        }
507    }
508}
509
510/// What the field currently holds, borrowed from wherever the app keeps it.
511///
512/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
513/// place the two renderers are forced apart: there the value is read back out
514/// of the DOM after the fact, and here the widget writes through this borrow as
515/// it is edited. Same reason the description carries neither.
516///
517/// An enum rather than a bag of options, on the reasoning
518/// `makeover_webview::form::Value` records: a checkbox holding a string is
519/// unsayable here, where a struct would let it be said and then have to cope.
520#[derive(Debug, Default)]
521pub enum Filling<'a> {
522    /// Nothing to edit. The control is drawn and does not answer.
523    #[default]
524    Absent,
525    /// The buffer behind anything that takes typed text, a select included:
526    /// what a select holds is the `value` of one of its [`Choice`]s.
527    ///
528    /// [`Choice`]: makeover_layout::Choice
529    Text(&'a mut String),
530    /// A checkbox, on or off.
531    On(&'a mut bool),
532}
533
534/// The label, marked if the field is compulsory.
535fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
536    if field.required {
537        format!("{} {}", field.label, style.required_marker)
538    } else {
539        field.label.to_owned()
540    }
541}
542
543/// The four shapes a control comes in here, which is fewer than there are
544/// kinds.
545///
546/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
547/// ways egui has of asking for a value do not. Reducing the open set to this
548/// closed one in one total function is what keeps a new kind from needing a new
549/// arm at every match below.
550#[derive(Debug, Clone, Copy, PartialEq, Eq)]
551enum Control {
552    /// Typed into, so it is drawn as a well: the user looks into it.
553    Typed,
554    /// Picked from a control that shows one option at a time. Pressed rather
555    /// than looked into, so egui's own control painting stands.
556    Chosen,
557    /// Picked from options that are all on screen at once.
558    ///
559    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
560    /// apart, and holding them apart is the whole content of
561    /// [`FieldKind::Radio`]: same question, and an answer the user can read
562    /// without opening anything.
563    Listed,
564    /// Held on or off.
565    Toggled,
566}
567
568/// Which shape a kind takes.
569///
570/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
571/// description since this renderer was built degrades to a text box, which
572/// accepts any value the others would, rather than to nothing drawn at all.
573///
574/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
575/// there rather than grown a shape of its own. egui's honest answer is a button
576/// that opens a native picker, which is a fifth control and a file-dialog
577/// dependency; no consumer of this crate asks for a file field yet. Same
578/// position this crate took on `Meter` at 0.10.0: the membership test is that
579/// every renderer *could* answer honestly, not that each one does on the day.
580/// A path in a text box is not nothing, and it is what an app that needs this
581/// tomorrow gets today.
582///
583/// `FieldKind::Date` and `FieldKind::DateTime` land there too, as of
584/// makeover-layout 0.15.0, on the same footing and with one thing owed. A
585/// calendar is a sixth control and bare `egui` has none, so a typed value is
586/// the honest answer here; what the app gets is the format the description
587/// names, `makeover_layout::DATE_FORMAT` and `DATETIME_FORMAT`, which is why
588/// those are constants rather than a sentence. audiofiles is the only consumer
589/// of this crate and asks for neither today. A calendar popup is the upgrade
590/// whenever one does.
591const fn control_shape(kind: FieldKind) -> Control {
592    match kind {
593        FieldKind::Select => Control::Chosen,
594        FieldKind::Radio => Control::Listed,
595        FieldKind::Checkbox => Control::Toggled,
596        _ => Control::Typed,
597    }
598}
599
600/// What a select shows for the value it currently holds.
601///
602/// A value no option carries stays on screen as itself rather than reading as
603/// whichever option happens to be first. goingson saved a backup retention of
604/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
605/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
606/// stray `<option>` and this is the same fix in the shape egui allows.
607fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
608    options
609        .iter()
610        .find(|opt| opt.value == value)
611        .map_or(value, |opt| opt.label)
612}
613
614/// What one option in a choice field is drawn in.
615///
616/// The chosen one is the emphasised thing and takes `content`; the rest take
617/// [`content_secondary`](Palette::content_secondary), because an option that is
618/// not chosen is still an option and pressing it chooses it. Muted would be the
619/// lie: [`State::Disabled`] resolves to it, so a five-option field read as one
620/// live row and four dead ones. `makeover-tui` draws it the same way
621/// (`makeover-tui@230bf63`); wiki `three-tone-convention` is the table.
622fn option_color(value: &str, option: &str, palette: &Palette) -> Color32 {
623    if value == option {
624        palette.content
625    } else {
626        palette.content_secondary
627    }
628}
629
630/// The control alone, without its label, hint or error.
631fn control(
632    ui: &mut Ui,
633    field: &Field<'_>,
634    filling: Filling<'_>,
635    palette: &Palette,
636    style: &FieldStyle,
637) -> Response {
638    // The mismatch path: described as one thing and filled as another. Nothing
639    // here can fix it, so it is drawn as the empty, inert version of what was
640    // described — visible on screen, in the way an empty select is at the
641    // webview renderer, rather than reported in a log nobody reads.
642    let mut discard = String::new();
643    let mut off = false;
644
645    match control_shape(field.kind) {
646        Control::Typed => {
647            let text = match filling {
648                Filling::Text(text) => text,
649                _ => &mut discard,
650            };
651            // An empty frame and no margin: the well is this crate's, and egui's
652            // own control background and padding would sit underneath it saying
653            // something different about both.
654            let mut edit = if matches!(field.kind, FieldKind::Textarea) {
655                TextEdit::multiline(text)
656            } else {
657                TextEdit::singleline(text)
658            }
659            .frame(egui::Frame::NONE)
660            .margin(Margin::ZERO)
661            .text_color(palette.content)
662            .password(field.kind.confidential());
663            if let Some(ghost) = field.placeholder {
664                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
665            }
666            frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
667        }
668        Control::Toggled => {
669            let on = match filling {
670                Filling::On(on) => on,
671                _ => &mut off,
672            };
673            ui.checkbox(on, RichText::new(field.label).color(palette.content))
674        }
675        Control::Listed => {
676            let value = match filling {
677                Filling::Text(text) => text,
678                _ => &mut discard,
679            };
680            // No `shown_label` counterpart, and none is needed: a value no
681            // option carries leaves every button unfilled, which is already
682            // the honest report on screen. The select needs the fix because it
683            // has one slot and must put *something* in it.
684            let group = ui.vertical(|ui| {
685                let mut answered: Option<Response> = None;
686                for opt in field.options {
687                    let picked = ui.radio_value(
688                        value,
689                        opt.value.to_owned(),
690                        RichText::new(opt.label).color(option_color(value, opt.value, palette)),
691                    );
692                    answered = Some(match answered {
693                        Some(prev) => prev.union(picked),
694                        None => picked,
695                    });
696                }
697                answered
698            });
699            // A group described with no options answers as its own empty area
700            // rather than as no response at all, which keeps the caller's
701            // `.changed()` chain working on a field whose option list has not
702            // loaded yet.
703            group.inner.unwrap_or(group.response)
704        }
705        Control::Chosen => {
706            let value = match filling {
707                Filling::Text(text) => text,
708                _ => &mut discard,
709            };
710            let shown = shown_label(field.options, value);
711            ComboBox::from_id_salt(field.name)
712                .selected_text(RichText::new(shown).color(palette.content))
713                .show_ui(ui, |ui| {
714                    for opt in field.options {
715                        ui.selectable_value(
716                            value,
717                            opt.value.to_owned(),
718                            RichText::new(opt.label).color(option_color(value, opt.value, palette)),
719                        );
720                    }
721                })
722                .response
723        }
724    }
725}
726
727/// One field, as the column the app drops into its form.
728///
729/// The anatomy is `makeover-webview`'s, so the two renderers put a form
730/// together the same way: label, control, hint, error, top to bottom, with a
731/// checkbox labelling itself instead of taking a label above.
732///
733/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
734/// [`FieldKind::visible`] means and is the honest answer here: a webview still
735/// emits an input for it because the form submits, and an immediate-mode
736/// renderer has no form and no submission, so a hidden field is a value the app
737/// already holds and there is nothing to draw or to respond to.
738///
739/// `state` is the description's interaction axis.
740/// [`State::Disabled`] greys the field and stops it answering, through
741/// [`State::suppresses_interaction`] rather than through a second reading of
742/// what disabled means. Focus is not on that axis and never reaches here: egui
743/// owns reach, focus and the ring for this renderer, and one ring means not a
744/// second one per renderer that happens to have opinions.
745pub fn field(
746    ui: &mut Ui,
747    field: &Field<'_>,
748    filling: Filling<'_>,
749    state: Option<State>,
750    palette: &Palette,
751    style: &FieldStyle,
752) -> Option<Response> {
753    if !field.kind.visible() {
754        return None;
755    }
756    let enabled = !state.is_some_and(State::suppresses_interaction);
757    let text = if enabled {
758        palette.content
759    } else {
760        palette.content_muted
761    };
762
763    let response = ui
764        .vertical(|ui| {
765            ui.spacing_mut().item_spacing.y = style.gap;
766
767            // A checkbox labels itself, on the right of the box.
768            // `FieldKind::labels_itself` is the description saying so, and both
769            // webview apps special-cased it inline before it did.
770            if !field.kind.labels_itself() {
771                ui.label(RichText::new(label_text(field, style)).color(text));
772            }
773
774            let response = ui
775                .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
776                .inner;
777
778            // Standing help first, then what is wrong now. Both, in that order,
779            // for the reason the webview renderer names both in
780            // `aria-describedby`: an error appearing must not take the hint
781            // away with it.
782            if let Some(hint) = field.hint {
783                ui.label(RichText::new(hint).color(palette.content_muted));
784            }
785            if let Some(error) = field.error {
786                ui.label(RichText::new(error).color(palette.danger));
787            }
788            response
789        })
790        .inner;
791
792    Some(response)
793}
794
795/// A set of fields, laid down a column.
796///
797/// `show_extended` is the disclosure, and it is a parameter rather than state
798/// held here because the disclosure belongs to the *form* and not to any field:
799/// [`Field::extended`] marks which fields are behind one, and the app owns
800/// whether it is open. That is the same division `makeover-webview` draws when
801/// it marks the group `data-extended` and emits no control to toggle it.
802///
803/// `draw` is called once per field that should be visible, in order. Taking a
804/// callback rather than a slice of [`Filling`]s is what keeps the app's own
805/// values borrowed one at a time: a form's fields usually live in different
806/// structs, and a parallel array would have to be built each frame and kept in
807/// step with the description by hand.
808pub fn group<'a>(
809    ui: &mut Ui,
810    fields: &'a [Field<'a>],
811    show_extended: bool,
812    style: &FieldStyle,
813    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
814) {
815    ui.vertical(|ui| {
816        ui.spacing_mut().item_spacing.y = style.group_gap;
817        for f in fields {
818            if f.extended && !show_extended {
819                continue;
820            }
821            draw(ui, f);
822        }
823    });
824}
825
826#[cfg(test)]
827mod tests {
828    use super::*;
829
830    fn palette(well: Color32) -> Palette {
831        Palette {
832            page: Color32::from_rgb(1, 1, 1),
833            raised: Color32::from_rgb(2, 2, 2),
834            overlay: Color32::from_rgb(3, 3, 3),
835            well,
836            sunken: Color32::from_rgb(4, 4, 4),
837            bevel_light: Color32::WHITE,
838            bevel_dark: Color32::BLACK,
839            elevation: Color32::from_black_alpha(46),
840            content: Color32::from_rgb(5, 5, 5),
841            content_secondary: Color32::from_rgb(55, 55, 55),
842            content_muted: Color32::from_rgb(6, 6, 6),
843            action: Color32::from_rgb(7, 7, 7),
844            danger: Color32::from_rgb(8, 8, 8),
845            success: Color32::from_rgb(9, 9, 9),
846            warning: Color32::from_rgb(10, 10, 10),
847            info: Color32::from_rgb(11, 11, 11),
848        }
849    }
850
851    /// The cast is egui's own shadow type carrying the theme's tone, which is
852    /// the whole of what this crate had to decide for it: unlike a bevel, egui
853    /// already knows how to paint one.
854    #[test]
855    fn the_cast_hands_egui_the_themes_tone() {
856        let p = palette(Color32::from_rgb(9, 9, 9));
857        let cast = p.cast();
858        assert_eq!(cast.color, p.elevation);
859        assert!(cast.blur > 0, "a cast shadow is soft");
860        assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
861    }
862
863    #[test]
864    fn a_well_resolves_to_its_own_token() {
865        // No substitution left. The page-filled well was a stand-in for a
866        // token that did not exist yet; it exists now.
867        let w = Color32::from_rgb(9, 9, 9);
868        let p = palette(w);
869        assert_eq!(p.fill(Fill::Well), Some(w));
870        assert_ne!(p.fill(Fill::Well), Some(p.page));
871    }
872
873    #[test]
874    fn every_intent_is_a_plain_lookup() {
875        let p = palette(Color32::from_rgb(9, 9, 9));
876        assert_eq!(p.fill(Fill::Page), Some(p.page));
877        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
878        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
879    }
880
881    /// Sunken is its own colour, not the well's and not the page's. The two
882    /// are authored in opposite directions and an earlier cut of the
883    /// description conflated them.
884    #[test]
885    fn sunken_is_neither_the_well_nor_the_page() {
886        let p = palette(Color32::from_rgb(9, 9, 9));
887        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
888        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
889        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
890    }
891
892    #[test]
893    fn a_raised_region_never_resolves_to_the_well_fill() {
894        // The cross-app bug, asserted at the renderer boundary this time.
895        let p = palette(Color32::from_rgb(9, 9, 9));
896        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
897        let well = Depth::Well.fill().and_then(|f| p.fill(f));
898        assert_eq!(raised, Some(p.raised));
899        assert_ne!(raised, well);
900    }
901
902    #[test]
903    fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
904        // makeover-layout 0.14.0 is what made this reachable. The answer was
905        // already here at 0.10.0 and the question could not be asked.
906        let p = palette(Color32::from_rgb(9, 9, 9));
907        assert_eq!(
908            Depth::Overlay.fill().and_then(|f| p.fill(f)),
909            Some(p.overlay)
910        );
911        assert_eq!(Depth::Overlay.bevel(), None);
912        // The shadow `frame` reaches for is the theme's tone rather than
913        // egui's default, which is the whole reason `cast` exists.
914        assert_eq!(p.cast().color, p.elevation);
915    }
916
917    #[test]
918    fn the_lit_edge_swaps_when_a_card_is_pressed() {
919        let p = palette(Color32::from_rgb(9, 9, 9));
920        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
921        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
922        assert_eq!(p.edge(tl), p.bevel_light);
923        assert_eq!(p.edge(ptl), p.bevel_dark);
924    }
925
926    #[test]
927    fn flat_asks_for_neither_fill_nor_edge() {
928        assert!(Depth::Flat.fill().is_none());
929        assert!(Depth::Flat.bevel().is_none());
930    }
931
932    #[test]
933    fn a_select_keeps_a_value_none_of_its_options_carries() {
934        // The save-the-wrong-thing bug, asserted at the second renderer so it
935        // is not re-found there. goingson's own numbers.
936        let options = [
937            Choice::plain("1"),
938            Choice::plain("3"),
939            Choice::plain("7"),
940            Choice::plain("14"),
941        ];
942        assert_eq!(shown_label(&options, "10"), "10");
943        // And a value that does match reads as its label, not as itself.
944        let spelled = [Choice {
945            value: "7",
946            label: "One week",
947        }];
948        assert_eq!(shown_label(&spelled, "7"), "One week");
949    }
950
951    #[test]
952    fn only_a_required_field_is_marked() {
953        let style = FieldStyle::default();
954        let plain = Field::new(FieldKind::Text, "title", "Title");
955        assert_eq!(label_text(&plain, &style), "Title");
956
957        let required = Field {
958            required: true,
959            ..plain
960        };
961        assert_eq!(label_text(&required, &style), "Title *");
962
963        // The marker is copy and the app owns it, which is why it is a knob.
964        let house = FieldStyle {
965            required_marker: "(required)",
966            ..style
967        };
968        assert_eq!(label_text(&required, &house), "Title (required)");
969    }
970
971    #[test]
972    fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
973        // What decides whether the control gets a well. A well is for what the
974        // user looks into, and only one of these is.
975        assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
976        assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
977        assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
978        for k in [
979            FieldKind::Text,
980            FieldKind::Secret,
981            FieldKind::Number,
982            FieldKind::Email,
983            FieldKind::Url,
984            FieldKind::Tel,
985            FieldKind::Textarea,
986        ] {
987            assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
988        }
989    }
990
991    #[test]
992    fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
993        // The description holds Select and Radio apart, and a renderer that
994        // collapsed them would silently answer a question the app did not ask:
995        // audiofiles' storage style is irreversible and its alternatives have
996        // to be readable without opening anything. Asserting the two shapes
997        // differ is asserting that distinction survives the trip.
998        assert!(FieldKind::Select.offers_options());
999        assert!(FieldKind::Radio.offers_options());
1000        assert_ne!(
1001            control_shape(FieldKind::Select),
1002            control_shape(FieldKind::Radio)
1003        );
1004    }
1005
1006    #[test]
1007    fn an_unchosen_option_is_secondary_and_never_muted() {
1008        let p = palette(Color32::from_rgb(4, 4, 4));
1009        assert_eq!(option_color("wav", "wav", &p), p.content);
1010        assert_eq!(option_color("wav", "aiff", &p), p.content_secondary);
1011        // The whole point of the distinction: muted is what Disabled resolves
1012        // to, so an option wearing it would claim it does not answer a press.
1013        assert_ne!(option_color("wav", "aiff", &p), p.content_muted);
1014    }
1015
1016    #[test]
1017    fn a_hidden_field_draws_nothing_and_answers_nothing() {
1018        // Where the two renderers legitimately part: a webview still emits an
1019        // input because the form submits, and there is no form here.
1020        let f = Field::new(FieldKind::Hidden, "id", "Id");
1021        let p = palette(Color32::from_rgb(9, 9, 9));
1022        egui::__run_test_ui(|ui| {
1023            let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
1024            assert!(drawn.is_none());
1025        });
1026    }
1027
1028    #[test]
1029    fn a_disabled_field_stops_answering_and_an_unstated_one_does_not() {
1030        let f = Field::new(FieldKind::Text, "title", "Title");
1031        let p = palette(Color32::from_rgb(9, 9, 9));
1032        let style = FieldStyle::default();
1033        egui::__run_test_ui(|ui| {
1034            let mut text = String::from("x");
1035            let disabled = field(
1036                ui,
1037                &f,
1038                Filling::Text(&mut text),
1039                Some(State::Disabled),
1040                &p,
1041                &style,
1042            )
1043            .unwrap();
1044            assert!(!disabled.enabled());
1045
1046            // Stating no state is the ordinary case and answers. Focus used to
1047            // be the counter-example here; it is egui's now and a description
1048            // cannot state it at all.
1049            let mut text = String::from("x");
1050            let plain = field(ui, &f, Filling::Text(&mut text), None, &p, &style).unwrap();
1051            assert!(plain.enabled(), "an unstated field still answers");
1052        });
1053    }
1054
1055    #[test]
1056    fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
1057        // No panic and no write-through. A checkbox handed a string cannot be
1058        // filled, so it is drawn off and left alone.
1059        let f = Field::new(FieldKind::Checkbox, "done", "Done");
1060        let p = palette(Color32::from_rgb(9, 9, 9));
1061        let mut text = String::from("untouched");
1062        egui::__run_test_ui(|ui| {
1063            let drawn = field(
1064                ui,
1065                &f,
1066                Filling::Text(&mut text),
1067                None,
1068                &p,
1069                &FieldStyle::default(),
1070            );
1071            assert!(drawn.is_some());
1072        });
1073        assert_eq!(text, "untouched");
1074    }
1075
1076    #[test]
1077    fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
1078        let fields = [
1079            Field::new(FieldKind::Text, "title", "Title"),
1080            Field {
1081                extended: true,
1082                ..Field::new(FieldKind::Text, "notes", "Notes")
1083            },
1084        ];
1085        let style = FieldStyle::default();
1086
1087        let mut closed = Vec::new();
1088        egui::__run_test_ui(|ui| {
1089            group(ui, &fields, false, &style, |_, f| closed.push(f.name));
1090        });
1091        assert_eq!(closed, ["title"]);
1092
1093        let mut open = Vec::new();
1094        egui::__run_test_ui(|ui| {
1095            group(ui, &fields, true, &style, |_, f| open.push(f.name));
1096        });
1097        assert_eq!(open, ["title", "notes"]);
1098    }
1099
1100    #[test]
1101    fn the_default_frame_is_square_and_one_point() {
1102        let d = FrameStyle::default();
1103        assert_eq!(d.radius, CornerRadius::ZERO);
1104        assert_eq!(d.margin, Margin::ZERO);
1105        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
1106    }
1107}