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 this renderer
47//! carries and does not draw. No table is drawn here yet, and the vocabulary is
48//! what makes drawing one possible without inventing a private name for what a
49//! cell holds -- which is the whole reason it lives in the description rather
50//! than in `quasi`.
51//!
52//! # Forms
53//!
54//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
55//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
56//! of them laid down a column in [`group`]. Before it, a description saying
57//! "text field, labelled, required, with this hint" had no way to become a
58//! widget here, and audiofiles' forms stayed hand-rolled.
59//!
60//! `makeover-webview` got there first and its form emitter is the precedent
61//! followed rather than re-derived, including the parts that are bug fixes: a
62//! select handed a value none of its options carries keeps that value visible
63//! instead of silently reading as the first option, which is a save-the-wrong-
64//! thing bug goingson hit for real.
65//!
66//! What differs is forced by the mode and not chosen:
67//!
68//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
69//!   and the widget writes through it. There is no DOM to read back out of,
70//!   which is also why the description deliberately does not carry the value.
71//! - **A text control is drawn as a well and a select is not.** The description
72//!   holds that a well is for anything the user looks *into*, and a text field
73//!   is its own example; a select and a checkbox are pressed rather than looked
74//!   into, so they keep egui's own control painting.
75//! - **[`makeover_layout::State::Focus`] is not drawn here.** egui already
76//!   paints exactly one focus stroke, and the description's rule is one ring
77//!   rather than a ring per primitive, so adding a second would break the rule
78//!   it came from. [`makeover_layout::State::Disabled`] *is* drawn, because egui
79//!   has no opinion about it until told.
80
81#![forbid(unsafe_code)]
82
83use egui::{
84    Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke,
85    TextEdit, Ui,
86};
87use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State};
88
89/// The resolved colours this renderer needs, as flat values.
90///
91/// Built by the app from whatever it already uses to resolve a theme, then
92/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
93/// painted per widget per frame, and a map lookup per edge is a cost with
94/// nothing to show for it.
95#[derive(Debug, Clone, Copy, PartialEq, Eq)]
96pub struct Palette {
97    /// `surface-page`.
98    pub page: Color32,
99    /// `surface-raised`.
100    pub raised: Color32,
101    /// `surface-overlay`.
102    pub overlay: Color32,
103    /// `surface-well`.
104    ///
105    /// Required, not optional. makeover derives it for every theme from 2.3.0,
106    /// so a resolved palette without a well is not a thing that exists here.
107    /// It was an `Option` while that was untrue, and this renderer substituted
108    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
109    /// since a terminal can have the colour and still be unable to show it.
110    pub well: Color32,
111    /// `surface-sunken`.
112    ///
113    /// A surface set back from the one it sits on, by colour and nothing else.
114    /// Not a well: a well is a hole with an edge, and this has no edge. An
115    /// immediate-mode renderer paints an arbitrary rect, so unlike
116    /// `makeover-tui` it has no excuse for declining this one.
117    ///
118    /// Required rather than optional, on the same footing as `well`: all 31
119    /// themes makeover embeds author it.
120    pub sunken: Color32,
121    /// `bevel-light`.
122    pub bevel_light: Color32,
123    /// `bevel-dark`.
124    pub bevel_dark: Color32,
125    /// `elevation`.
126    ///
127    /// What a surface that floats OVER the page is cast onto it with. The one
128    /// intent here that is about a surface's relationship to the page rather
129    /// than about the surface, which is why it is a translucent near-black on
130    /// every theme rather than something read off the palette's own ramp.
131    ///
132    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
133    /// surface *in* the layout takes a bevel, and reaching for this on a panel
134    /// or a card is how a pre-Platinum look survives a conversion under a new
135    /// name.
136    ///
137    /// egui has a real answer for this where a terminal does not: see
138    /// [`Palette::cast`], which is the shadow to hand an
139    /// [`egui::Frame`](egui::Frame).
140    pub elevation: Color32,
141    /// `content`.
142    ///
143    /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
144    /// thing here that draws any: until then this crate painted surfaces and
145    /// edges and let the caller's own egui visuals answer for text.
146    pub content: Color32,
147    /// `content-muted`.
148    ///
149    /// A field's hint, and what
150    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
151    /// resolves to. Both readings come from the description rather than from
152    /// here: `State::Disabled` names this intent by token.
153    pub content_muted: Color32,
154    /// `danger`.
155    ///
156    /// A field's error message. The one [`makeover_layout::Tone`] this renderer
157    /// needs so far, and it is here rather than as a whole resolved tone set
158    /// because notices are not drawn here yet and a palette should carry what
159    /// is used.
160    pub danger: Color32,
161}
162
163impl Palette {
164    /// Resolve a surface intent, or `None` for one this renderer does not know.
165    ///
166    /// A plain lookup. There is still no substitution: the old one existed only
167    /// while `surface-well` was underived, and every consumer reads the real
168    /// token now.
169    ///
170    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
171    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
172    /// stay total by inventing a colour for a member it has never heard of.
173    /// That is the substitution this crate spent 0.2.0 removing, so the return
174    /// type moved instead. Every member the description has today is answered
175    /// with `Some`.
176    #[must_use]
177    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
178        match fill {
179            Fill::Page => Some(self.page),
180            Fill::Raised => Some(self.raised),
181            Fill::Overlay => Some(self.overlay),
182            Fill::Well => Some(self.well),
183            Fill::Sunken => Some(self.sunken),
184            _ => None,
185        }
186    }
187
188    /// The cast shadow for a surface that overlays the page.
189    ///
190    /// What "overlaying" means in immediate mode, answered rather than skipped.
191    /// egui already paints shadows for its menus and windows through
192    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
193    /// theme's tone instead of egui's own default, not to invent a painter here
194    /// the way [`paint_bevel`] had to.
195    ///
196    /// The geometry matches what `makeover-webview` composes, in points rather
197    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
198    /// menu sits just off the page rather than hovering above it.
199    ///
200    /// ```no_run
201    /// # let palette: makeover_immediate::Palette = unimplemented!();
202    /// # let ui: &mut egui::Ui = unimplemented!();
203    /// egui::Frame::popup(ui.style())
204    ///     .shadow(palette.cast())
205    ///     .show(ui, |ui| { ui.label("over the page"); });
206    /// ```
207    #[must_use]
208    pub const fn cast(&self) -> egui::Shadow {
209        egui::Shadow {
210            offset: [0, 2],
211            blur: 24,
212            spread: 0,
213            color: self.elevation,
214        }
215    }
216
217    /// Resolve a bevel edge intent.
218    #[must_use]
219    pub const fn edge(&self, edge: Edge) -> Color32 {
220        match edge {
221            Edge::Light => self.bevel_light,
222            Edge::Dark => self.bevel_dark,
223        }
224    }
225}
226
227/// The geometry a framed region is drawn with.
228///
229/// Every field is a value, which is why they all arrive from the caller:
230/// radius and border width belong to `makeover-geometry`, and margins come
231/// from its relational gaps.
232#[derive(Debug, Clone, Copy, PartialEq)]
233pub struct FrameStyle {
234    /// Corner radius. Square under the Platinum default.
235    pub radius: CornerRadius,
236    /// Inner margin between the frame and its contents.
237    pub margin: Margin,
238    /// Bevel stroke width, in points.
239    pub stroke: f32,
240}
241
242impl Default for FrameStyle {
243    /// A one-point square frame with no inner margin.
244    fn default() -> Self {
245        Self {
246            radius: CornerRadius::ZERO,
247            margin: Margin::ZERO,
248            stroke: 1.0,
249        }
250    }
251}
252
253/// Paint a two-tone edge just inside `rect`.
254///
255/// Fill first, bevel after: this adds two polylines and nothing else, so it
256/// composes over whatever is already there. That is what lets it go over an
257/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
258///
259/// Two three-point polylines meeting at opposite corners, rather than four
260/// segments, so egui mitres the corner joins instead of leaving a notch.
261///
262/// The dark polyline is drawn second, so the two corners where the runs meet
263/// take its tone. That is the right answer here rather than a concession.
264/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
265/// a renderer with room to divide one should; at the default one-point stroke
266/// the corner is a one-point square, so the division is sub-pixel and
267/// antialiasing resolves it to the same blend the mitre already gives. Splitting
268/// it would add a seam and no information. `makeover-tui` does split, because a
269/// terminal cell is large enough that not splitting costs a visible cell of edge
270/// weight — the same rule, at a resolution where it has something to say.
271pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
272    let (top_left, bottom_right) = bevel.edges();
273
274    // Inset by half a stroke so the line lands inside `rect` rather than
275    // straddling its edge, which on a fractional-scale display is the
276    // difference between one crisp pixel and two dim ones.
277    let r = rect.shrink(stroke / 2.0);
278
279    painter.add(Shape::line(
280        vec![r.left_bottom(), r.left_top(), r.right_top()],
281        Stroke::new(stroke, palette.edge(top_left)),
282    ));
283    painter.add(Shape::line(
284        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
285        Stroke::new(stroke, palette.edge(bottom_right)),
286    ));
287}
288
289/// Draw a region at a given [`Depth`]: its fill and its edge, together.
290///
291/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
292/// difference between level-with and painted-the-same-colour, and it is the
293/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
294/// page.
295pub fn frame<R>(
296    ui: &mut Ui,
297    depth: Depth,
298    palette: &Palette,
299    style: FrameStyle,
300    add_contents: impl FnOnce(&mut Ui) -> R,
301) -> R {
302    let mut f = egui::Frame::new()
303        .corner_radius(style.radius)
304        .inner_margin(style.margin);
305    // Two ways there is no fill to paint, and they collapse to the same
306    // outcome: the depth names none (Depth::Flat), or it names one this
307    // renderer cannot resolve. Either way the frame goes unfilled and the
308    // bevel below carries the depth on its own, which is the rule this
309    // module already documents for Flat.
310    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
311        f = f.fill(fill);
312    }
313    // A surface that overlays the page is cast onto it. [`Palette::cast`] has
314    // answered what that means here since 0.10.0 and nothing could reach it: a
315    // description had no way to say Overlay until makeover-layout 0.14.0, so
316    // the answer sat beside the question. Keyed off the fill rather than the
317    // variant, so it stays right for whatever else the description calls an
318    // overlay later.
319    if depth.fill() == Some(Fill::Overlay) {
320        f = f.shadow(palette.cast());
321    }
322    let framed = f.show(ui, add_contents);
323    if let Some(bevel) = depth.bevel() {
324        paint_bevel(
325            ui.painter(),
326            framed.response.rect,
327            bevel,
328            palette,
329            style.stroke,
330        );
331    }
332    framed.inner
333}
334
335/// The geometry a field group is drawn with.
336///
337/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
338/// `makeover-geometry` and arrives already resolved.
339#[derive(Debug, Clone, Copy, PartialEq)]
340pub struct FieldStyle {
341    /// The well a text control sits in.
342    pub frame: FrameStyle,
343    /// Between a field's own parts: its label, its control, its hint and its
344    /// error.
345    pub gap: f32,
346    /// Between one field and the next.
347    pub group_gap: f32,
348    /// What marks a required field, appended to its label.
349    ///
350    /// A knob rather than a constant, because it is the one piece of *copy* in
351    /// this crate and copy is not a renderer's call. A webview does not need it
352    /// at all — it emits the `required` attribute and the browser answers — so
353    /// this renderer is the first place where a compulsory field either shows
354    /// that it is or silently does not.
355    pub required_marker: &'static str,
356}
357
358impl Default for FieldStyle {
359    /// The default frame, no gaps, and an asterisk.
360    fn default() -> Self {
361        Self {
362            frame: FrameStyle::default(),
363            gap: 0.0,
364            group_gap: 0.0,
365            required_marker: "*",
366        }
367    }
368}
369
370/// What the field currently holds, borrowed from wherever the app keeps it.
371///
372/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
373/// place the two renderers are forced apart: there the value is read back out
374/// of the DOM after the fact, and here the widget writes through this borrow as
375/// it is edited. Same reason the description carries neither.
376///
377/// An enum rather than a bag of options, on the reasoning
378/// `makeover_webview::form::Value` records: a checkbox holding a string is
379/// unsayable here, where a struct would let it be said and then have to cope.
380#[derive(Debug, Default)]
381pub enum Filling<'a> {
382    /// Nothing to edit. The control is drawn and does not answer.
383    #[default]
384    Absent,
385    /// The buffer behind anything that takes typed text, a select included:
386    /// what a select holds is the `value` of one of its [`Choice`]s.
387    ///
388    /// [`Choice`]: makeover_layout::Choice
389    Text(&'a mut String),
390    /// A checkbox, on or off.
391    On(&'a mut bool),
392}
393
394/// The label, marked if the field is compulsory.
395fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
396    if field.required {
397        format!("{} {}", field.label, style.required_marker)
398    } else {
399        field.label.to_owned()
400    }
401}
402
403/// The four shapes a control comes in here, which is fewer than there are
404/// kinds.
405///
406/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
407/// ways egui has of asking for a value do not. Reducing the open set to this
408/// closed one in one total function is what keeps a new kind from needing a new
409/// arm at every match below.
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411enum Control {
412    /// Typed into, so it is drawn as a well: the user looks into it.
413    Typed,
414    /// Picked from a control that shows one option at a time. Pressed rather
415    /// than looked into, so egui's own control painting stands.
416    Chosen,
417    /// Picked from options that are all on screen at once.
418    ///
419    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
420    /// apart, and holding them apart is the whole content of
421    /// [`FieldKind::Radio`]: same question, and an answer the user can read
422    /// without opening anything.
423    Listed,
424    /// Held on or off.
425    Toggled,
426}
427
428/// Which shape a kind takes.
429///
430/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
431/// description since this renderer was built degrades to a text box, which
432/// accepts any value the others would, rather than to nothing drawn at all.
433///
434/// `FieldKind::File` lands there as of makeover-layout 0.11.0, and it is left
435/// there rather than grown a shape of its own. egui's honest answer is a button
436/// that opens a native picker, which is a fifth control and a file-dialog
437/// dependency; no consumer of this crate asks for a file field yet. Same
438/// position this crate took on `Meter` at 0.10.0: the membership test is that
439/// every renderer *could* answer honestly, not that each one does on the day.
440/// A path in a text box is not nothing, and it is what an app that needs this
441/// tomorrow gets today.
442const fn control_shape(kind: FieldKind) -> Control {
443    match kind {
444        FieldKind::Select => Control::Chosen,
445        FieldKind::Radio => Control::Listed,
446        FieldKind::Checkbox => Control::Toggled,
447        _ => Control::Typed,
448    }
449}
450
451/// What a select shows for the value it currently holds.
452///
453/// A value no option carries stays on screen as itself rather than reading as
454/// whichever option happens to be first. goingson saved a backup retention of
455/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
456/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
457/// stray `<option>` and this is the same fix in the shape egui allows.
458fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
459    options
460        .iter()
461        .find(|opt| opt.value == value)
462        .map_or(value, |opt| opt.label)
463}
464
465/// The control alone, without its label, hint or error.
466fn control(
467    ui: &mut Ui,
468    field: &Field<'_>,
469    filling: Filling<'_>,
470    palette: &Palette,
471    style: &FieldStyle,
472) -> Response {
473    // The mismatch path: described as one thing and filled as another. Nothing
474    // here can fix it, so it is drawn as the empty, inert version of what was
475    // described — visible on screen, in the way an empty select is at the
476    // webview renderer, rather than reported in a log nobody reads.
477    let mut discard = String::new();
478    let mut off = false;
479
480    match control_shape(field.kind) {
481        Control::Typed => {
482            let text = match filling {
483                Filling::Text(text) => text,
484                _ => &mut discard,
485            };
486            // An empty frame and no margin: the well is this crate's, and egui's
487            // own control background and padding would sit underneath it saying
488            // something different about both.
489            let mut edit = if matches!(field.kind, FieldKind::Textarea) {
490                TextEdit::multiline(text)
491            } else {
492                TextEdit::singleline(text)
493            }
494            .frame(egui::Frame::NONE)
495            .margin(Margin::ZERO)
496            .text_color(palette.content)
497            .password(field.kind.confidential());
498            if let Some(ghost) = field.placeholder {
499                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
500            }
501            frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
502        }
503        Control::Toggled => {
504            let on = match filling {
505                Filling::On(on) => on,
506                _ => &mut off,
507            };
508            ui.checkbox(on, RichText::new(field.label).color(palette.content))
509        }
510        Control::Listed => {
511            let value = match filling {
512                Filling::Text(text) => text,
513                _ => &mut discard,
514            };
515            // No `shown_label` counterpart, and none is needed: a value no
516            // option carries leaves every button unfilled, which is already
517            // the honest report on screen. The select needs the fix because it
518            // has one slot and must put *something* in it.
519            let group = ui.vertical(|ui| {
520                let mut answered: Option<Response> = None;
521                for opt in field.options {
522                    let picked = ui.radio_value(
523                        value,
524                        opt.value.to_owned(),
525                        RichText::new(opt.label).color(palette.content),
526                    );
527                    answered = Some(match answered {
528                        Some(prev) => prev.union(picked),
529                        None => picked,
530                    });
531                }
532                answered
533            });
534            // A group described with no options answers as its own empty area
535            // rather than as no response at all, which keeps the caller's
536            // `.changed()` chain working on a field whose option list has not
537            // loaded yet.
538            group.inner.unwrap_or(group.response)
539        }
540        Control::Chosen => {
541            let value = match filling {
542                Filling::Text(text) => text,
543                _ => &mut discard,
544            };
545            let shown = shown_label(field.options, value);
546            ComboBox::from_id_salt(field.name)
547                .selected_text(RichText::new(shown).color(palette.content))
548                .show_ui(ui, |ui| {
549                    for opt in field.options {
550                        ui.selectable_value(
551                            value,
552                            opt.value.to_owned(),
553                            RichText::new(opt.label).color(palette.content),
554                        );
555                    }
556                })
557                .response
558        }
559    }
560}
561
562/// One field, as the column the app drops into its form.
563///
564/// The anatomy is `makeover-webview`'s, so the two renderers put a form
565/// together the same way: label, control, hint, error, top to bottom, with a
566/// checkbox labelling itself instead of taking a label above.
567///
568/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
569/// [`FieldKind::visible`] means and is the honest answer here: a webview still
570/// emits an input for it because the form submits, and an immediate-mode
571/// renderer has no form and no submission, so a hidden field is a value the app
572/// already holds and there is nothing to draw or to respond to.
573///
574/// `state` is the description's interaction axis.
575/// [`State::Disabled`] greys the field and stops it answering, through
576/// [`State::suppresses_interaction`] rather than through a second reading of
577/// what disabled means. [`State::Focus`] is deliberately not acted on: egui
578/// paints its own focus stroke and the description asks for one ring, not one
579/// per renderer that happens to have opinions.
580pub fn field(
581    ui: &mut Ui,
582    field: &Field<'_>,
583    filling: Filling<'_>,
584    state: Option<State>,
585    palette: &Palette,
586    style: &FieldStyle,
587) -> Option<Response> {
588    if !field.kind.visible() {
589        return None;
590    }
591    let enabled = !state.is_some_and(State::suppresses_interaction);
592    let text = if enabled {
593        palette.content
594    } else {
595        palette.content_muted
596    };
597
598    let response = ui
599        .vertical(|ui| {
600            ui.spacing_mut().item_spacing.y = style.gap;
601
602            // A checkbox labels itself, on the right of the box.
603            // `FieldKind::labels_itself` is the description saying so, and both
604            // webview apps special-cased it inline before it did.
605            if !field.kind.labels_itself() {
606                ui.label(RichText::new(label_text(field, style)).color(text));
607            }
608
609            let response = ui
610                .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
611                .inner;
612
613            // Standing help first, then what is wrong now. Both, in that order,
614            // for the reason the webview renderer names both in
615            // `aria-describedby`: an error appearing must not take the hint
616            // away with it.
617            if let Some(hint) = field.hint {
618                ui.label(RichText::new(hint).color(palette.content_muted));
619            }
620            if let Some(error) = field.error {
621                ui.label(RichText::new(error).color(palette.danger));
622            }
623            response
624        })
625        .inner;
626
627    Some(response)
628}
629
630/// A set of fields, laid down a column.
631///
632/// `show_extended` is the disclosure, and it is a parameter rather than state
633/// held here because the disclosure belongs to the *form* and not to any field:
634/// [`Field::extended`] marks which fields are behind one, and the app owns
635/// whether it is open. That is the same division `makeover-webview` draws when
636/// it marks the group `data-extended` and emits no control to toggle it.
637///
638/// `draw` is called once per field that should be visible, in order. Taking a
639/// callback rather than a slice of [`Filling`]s is what keeps the app's own
640/// values borrowed one at a time: a form's fields usually live in different
641/// structs, and a parallel array would have to be built each frame and kept in
642/// step with the description by hand.
643pub fn group<'a>(
644    ui: &mut Ui,
645    fields: &'a [Field<'a>],
646    show_extended: bool,
647    style: &FieldStyle,
648    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
649) {
650    ui.vertical(|ui| {
651        ui.spacing_mut().item_spacing.y = style.group_gap;
652        for f in fields {
653            if f.extended && !show_extended {
654                continue;
655            }
656            draw(ui, f);
657        }
658    });
659}
660
661#[cfg(test)]
662mod tests {
663    use super::*;
664
665    fn palette(well: Color32) -> Palette {
666        Palette {
667            page: Color32::from_rgb(1, 1, 1),
668            raised: Color32::from_rgb(2, 2, 2),
669            overlay: Color32::from_rgb(3, 3, 3),
670            well,
671            sunken: Color32::from_rgb(4, 4, 4),
672            bevel_light: Color32::WHITE,
673            bevel_dark: Color32::BLACK,
674            elevation: Color32::from_black_alpha(46),
675            content: Color32::from_rgb(5, 5, 5),
676            content_muted: Color32::from_rgb(6, 6, 6),
677            danger: Color32::from_rgb(7, 7, 7),
678        }
679    }
680
681    /// The cast is egui's own shadow type carrying the theme's tone, which is
682    /// the whole of what this crate had to decide for it: unlike a bevel, egui
683    /// already knows how to paint one.
684    #[test]
685    fn the_cast_hands_egui_the_themes_tone() {
686        let p = palette(Color32::from_rgb(9, 9, 9));
687        let cast = p.cast();
688        assert_eq!(cast.color, p.elevation);
689        assert!(cast.blur > 0, "a cast shadow is soft");
690        assert_eq!(cast.offset, [0, 2], "it falls downward and only a little");
691    }
692
693    #[test]
694    fn a_well_resolves_to_its_own_token() {
695        // No substitution left. The page-filled well was a stand-in for a
696        // token that did not exist yet; it exists now.
697        let w = Color32::from_rgb(9, 9, 9);
698        let p = palette(w);
699        assert_eq!(p.fill(Fill::Well), Some(w));
700        assert_ne!(p.fill(Fill::Well), Some(p.page));
701    }
702
703    #[test]
704    fn every_intent_is_a_plain_lookup() {
705        let p = palette(Color32::from_rgb(9, 9, 9));
706        assert_eq!(p.fill(Fill::Page), Some(p.page));
707        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
708        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
709    }
710
711    /// Sunken is its own colour, not the well's and not the page's. The two
712    /// are authored in opposite directions and an earlier cut of the
713    /// description conflated them.
714    #[test]
715    fn sunken_is_neither_the_well_nor_the_page() {
716        let p = palette(Color32::from_rgb(9, 9, 9));
717        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
718        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
719        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
720    }
721
722    #[test]
723    fn a_raised_region_never_resolves_to_the_well_fill() {
724        // The cross-app bug, asserted at the renderer boundary this time.
725        let p = palette(Color32::from_rgb(9, 9, 9));
726        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
727        let well = Depth::Well.fill().and_then(|f| p.fill(f));
728        assert_eq!(raised, Some(p.raised));
729        assert_ne!(raised, well);
730    }
731
732    #[test]
733    fn an_overlay_is_cast_onto_the_page_and_takes_no_edge() {
734        // makeover-layout 0.14.0 is what made this reachable. The answer was
735        // already here at 0.10.0 and the question could not be asked.
736        let p = palette(Color32::from_rgb(9, 9, 9));
737        assert_eq!(
738            Depth::Overlay.fill().and_then(|f| p.fill(f)),
739            Some(p.overlay)
740        );
741        assert_eq!(Depth::Overlay.bevel(), None);
742        // The shadow `frame` reaches for is the theme's tone rather than
743        // egui's default, which is the whole reason `cast` exists.
744        assert_eq!(p.cast().color, p.elevation);
745    }
746
747    #[test]
748    fn the_lit_edge_swaps_when_a_card_is_pressed() {
749        let p = palette(Color32::from_rgb(9, 9, 9));
750        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
751        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
752        assert_eq!(p.edge(tl), p.bevel_light);
753        assert_eq!(p.edge(ptl), p.bevel_dark);
754    }
755
756    #[test]
757    fn flat_asks_for_neither_fill_nor_edge() {
758        assert!(Depth::Flat.fill().is_none());
759        assert!(Depth::Flat.bevel().is_none());
760    }
761
762    #[test]
763    fn a_select_keeps_a_value_none_of_its_options_carries() {
764        // The save-the-wrong-thing bug, asserted at the second renderer so it
765        // is not re-found there. goingson's own numbers.
766        let options = [
767            Choice::plain("1"),
768            Choice::plain("3"),
769            Choice::plain("7"),
770            Choice::plain("14"),
771        ];
772        assert_eq!(shown_label(&options, "10"), "10");
773        // And a value that does match reads as its label, not as itself.
774        let spelled = [Choice {
775            value: "7",
776            label: "One week",
777        }];
778        assert_eq!(shown_label(&spelled, "7"), "One week");
779    }
780
781    #[test]
782    fn only_a_required_field_is_marked() {
783        let style = FieldStyle::default();
784        let plain = Field::new(FieldKind::Text, "title", "Title");
785        assert_eq!(label_text(&plain, &style), "Title");
786
787        let required = Field {
788            required: true,
789            ..plain
790        };
791        assert_eq!(label_text(&required, &style), "Title *");
792
793        // The marker is copy and the app owns it, which is why it is a knob.
794        let house = FieldStyle {
795            required_marker: "(required)",
796            ..style
797        };
798        assert_eq!(label_text(&required, &house), "Title (required)");
799    }
800
801    #[test]
802    fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
803        // What decides whether the control gets a well. A well is for what the
804        // user looks into, and only one of these is.
805        assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
806        assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
807        assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
808        for k in [
809            FieldKind::Text,
810            FieldKind::Secret,
811            FieldKind::Number,
812            FieldKind::Email,
813            FieldKind::Url,
814            FieldKind::Tel,
815            FieldKind::Textarea,
816        ] {
817            assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
818        }
819    }
820
821    #[test]
822    fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
823        // The description holds Select and Radio apart, and a renderer that
824        // collapsed them would silently answer a question the app did not ask:
825        // audiofiles' storage style is irreversible and its alternatives have
826        // to be readable without opening anything. Asserting the two shapes
827        // differ is asserting that distinction survives the trip.
828        assert!(FieldKind::Select.offers_options());
829        assert!(FieldKind::Radio.offers_options());
830        assert_ne!(
831            control_shape(FieldKind::Select),
832            control_shape(FieldKind::Radio)
833        );
834    }
835
836    #[test]
837    fn a_hidden_field_draws_nothing_and_answers_nothing() {
838        // Where the two renderers legitimately part: a webview still emits an
839        // input because the form submits, and there is no form here.
840        let f = Field::new(FieldKind::Hidden, "id", "Id");
841        let p = palette(Color32::from_rgb(9, 9, 9));
842        egui::__run_test_ui(|ui| {
843            let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
844            assert!(drawn.is_none());
845        });
846    }
847
848    #[test]
849    fn a_disabled_field_stops_answering_and_a_focused_one_does_not() {
850        let f = Field::new(FieldKind::Text, "title", "Title");
851        let p = palette(Color32::from_rgb(9, 9, 9));
852        let style = FieldStyle::default();
853        egui::__run_test_ui(|ui| {
854            let mut text = String::from("x");
855            let disabled = field(
856                ui,
857                &f,
858                Filling::Text(&mut text),
859                Some(State::Disabled),
860                &p,
861                &style,
862            )
863            .unwrap();
864            assert!(!disabled.enabled());
865
866            let mut text = String::from("x");
867            let focused = field(
868                ui,
869                &f,
870                Filling::Text(&mut text),
871                Some(State::Focus),
872                &p,
873                &style,
874            )
875            .unwrap();
876            assert!(focused.enabled(), "focus is a thing you can still click");
877        });
878    }
879
880    #[test]
881    fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
882        // No panic and no write-through. A checkbox handed a string cannot be
883        // filled, so it is drawn off and left alone.
884        let f = Field::new(FieldKind::Checkbox, "done", "Done");
885        let p = palette(Color32::from_rgb(9, 9, 9));
886        let mut text = String::from("untouched");
887        egui::__run_test_ui(|ui| {
888            let drawn = field(
889                ui,
890                &f,
891                Filling::Text(&mut text),
892                None,
893                &p,
894                &FieldStyle::default(),
895            );
896            assert!(drawn.is_some());
897        });
898        assert_eq!(text, "untouched");
899    }
900
901    #[test]
902    fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
903        let fields = [
904            Field::new(FieldKind::Text, "title", "Title"),
905            Field {
906                extended: true,
907                ..Field::new(FieldKind::Text, "notes", "Notes")
908            },
909        ];
910        let style = FieldStyle::default();
911
912        let mut closed = Vec::new();
913        egui::__run_test_ui(|ui| {
914            group(ui, &fields, false, &style, |_, f| closed.push(f.name));
915        });
916        assert_eq!(closed, ["title"]);
917
918        let mut open = Vec::new();
919        egui::__run_test_ui(|ui| {
920            group(ui, &fields, true, &style, |_, f| open.push(f.name));
921        });
922        assert_eq!(open, ["title", "notes"]);
923    }
924
925    #[test]
926    fn the_default_frame_is_square_and_one_point() {
927        let d = FrameStyle::default();
928        assert_eq!(d.radius, CornerRadius::ZERO);
929        assert_eq!(d.margin, Margin::ZERO);
930        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
931    }
932}