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