makeover-immediate 0.6.0

The immediate-mode renderer for makeover-layout. Immediate mode is the constraint that matters, not the library: no cascade, no retained tree, one stroke per widget. Backed by egui.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
//! The immediate-mode renderer for [`makeover_layout`].
//!
//! <!-- wiki: makeover-immediate -->
//!
//! Named for the mode, not the library, the way `makeover-tui` is named for
//! the target and not for ratatui. Immediate mode is the constraint that
//! actually separates this renderer from the other two, and egui is the
//! backend it is written against.
//!
//! It is the harshest renderer the description has to survive: no
//! `box-shadow`, no `inset`, no cascade, no retained tree to mutate, and
//! `Visuals.widgets.*.bg_stroke` is a single stroke with no per-side control.
//! A two-tone lit edge is not something egui can be configured into producing,
//! so it gets painted by hand here, once, instead of in every consuming app.
//!
//! # What this crate does and does not own
//!
//! It owns the *expression*: two mitred polylines for a bevel and a `Frame`
//! for a filled region. It owns no colours and no sizes, and no longer owns a
//! substitution: it briefly supplied the page for a well, which was a stand-in
//! for `surface-well` before makeover derived it, and every consumer reads the
//! real token now. [`Palette`] is supplied by the caller,
//! already resolved, and every radius, margin and stroke width arrives in
//! [`FrameStyle`].
//!
//! That split is why the crate has no dependency on `makeover` itself: the app
//! already resolves a theme, and coupling a renderer to a colour crate's
//! version would buy nothing.
//!
//! # The cascade is the real difference
//!
//! A stylesheet can say "a pressed button inverts its bevel" once and let the
//! cascade carry it. An immediate-mode renderer has nowhere to put that, so
//! every call site decides. [`makeover_layout::Depth::pressed`] is what keeps
//! the decision from being re-derived per widget.
//!
//! # Forms
//!
//! 0.5.0 adds the field vocabulary on top of the depth vocabulary:
//! [`makeover_layout::Field`] rendered to egui widgets, in [`field`], and a set
//! of them laid down a column in [`group`]. Before it, a description saying
//! "text field, labelled, required, with this hint" had no way to become a
//! widget here, and audiofiles' forms stayed hand-rolled.
//!
//! `makeover-webview` got there first and its form emitter is the precedent
//! followed rather than re-derived, including the parts that are bug fixes: a
//! select handed a value none of its options carries keeps that value visible
//! instead of silently reading as the first option, which is a save-the-wrong-
//! thing bug goingson hit for real.
//!
//! What differs is forced by the mode and not chosen:
//!
//! - **The value arrives as a `&mut`.** [`Filling`] borrows the app's own field
//!   and the widget writes through it. There is no DOM to read back out of,
//!   which is also why the description deliberately does not carry the value.
//! - **A text control is drawn as a well and a select is not.** The description
//!   holds that a well is for anything the user looks *into*, and a text field
//!   is its own example; a select and a checkbox are pressed rather than looked
//!   into, so they keep egui's own control painting.
//! - **[`makeover_layout::State::Focus`] is not drawn here.** egui already
//!   paints exactly one focus stroke, and the description's rule is one ring
//!   rather than a ring per primitive, so adding a second would break the rule
//!   it came from. [`makeover_layout::State::Disabled`] *is* drawn, because egui
//!   has no opinion about it until told.

#![forbid(unsafe_code)]

use egui::{
    Color32, ComboBox, CornerRadius, Margin, Painter, Rect, Response, RichText, Shape, Stroke,
    TextEdit, Ui,
};
use makeover_layout::{Bevel, Choice, Depth, Edge, Field, FieldKind, Fill, State};

/// The resolved colours this renderer needs, as flat values.
///
/// Built by the app from whatever it already uses to resolve a theme, then
/// held and reused. Deliberately not a trait and not string-keyed: a bevel is
/// painted per widget per frame, and a map lookup per edge is a cost with
/// nothing to show for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Palette {
    /// `surface-page`.
    pub page: Color32,
    /// `surface-raised`.
    pub raised: Color32,
    /// `surface-overlay`.
    pub overlay: Color32,
    /// `surface-well`.
    ///
    /// Required, not optional. makeover derives it for every theme from 2.3.0,
    /// so a resolved palette without a well is not a thing that exists here.
    /// It was an `Option` while that was untrue, and this renderer substituted
    /// the page; `makeover-tui` keeps its own `Option` for a different reason,
    /// since a terminal can have the colour and still be unable to show it.
    pub well: Color32,
    /// `surface-sunken`.
    ///
    /// A surface set back from the one it sits on, by colour and nothing else.
    /// Not a well: a well is a hole with an edge, and this has no edge. An
    /// immediate-mode renderer paints an arbitrary rect, so unlike
    /// `makeover-tui` it has no excuse for declining this one.
    ///
    /// Required rather than optional, on the same footing as `well`: all 31
    /// themes makeover embeds author it.
    pub sunken: Color32,
    /// `bevel-light`.
    pub bevel_light: Color32,
    /// `bevel-dark`.
    pub bevel_dark: Color32,
    /// `content`.
    ///
    /// Ordinary text. Added 0.5.0 with the field renderer, which is the first
    /// thing here that draws any: until then this crate painted surfaces and
    /// edges and let the caller's own egui visuals answer for text.
    pub content: Color32,
    /// `content-muted`.
    ///
    /// A field's hint, and what
    /// [`makeover_layout::State::Disabled`](makeover_layout::State::Disabled)
    /// resolves to. Both readings come from the description rather than from
    /// here: `State::Disabled` names this intent by token.
    pub content_muted: Color32,
    /// `danger`.
    ///
    /// A field's error message. The one [`makeover_layout::Tone`] this renderer
    /// needs so far, and it is here rather than as a whole resolved tone set
    /// because notices are not drawn here yet and a palette should carry what
    /// is used.
    pub danger: Color32,
}

impl Palette {
    /// Resolve a surface intent, or `None` for one this renderer does not know.
    ///
    /// A plain lookup. There is still no substitution: the old one existed only
    /// while `surface-well` was underived, and every consumer reads the real
    /// token now.
    ///
    /// `Option` since 0.3.0, because [`Fill`] became `#[non_exhaustive]` in
    /// `makeover-layout` 0.4.0 and a total function over an open enum can only
    /// stay total by inventing a colour for a member it has never heard of.
    /// That is the substitution this crate spent 0.2.0 removing, so the return
    /// type moved instead. Every member the description has today is answered
    /// with `Some`.
    #[must_use]
    pub const fn fill(&self, fill: Fill) -> Option<Color32> {
        match fill {
            Fill::Page => Some(self.page),
            Fill::Raised => Some(self.raised),
            Fill::Overlay => Some(self.overlay),
            Fill::Well => Some(self.well),
            Fill::Sunken => Some(self.sunken),
            _ => None,
        }
    }

    /// Resolve a bevel edge intent.
    #[must_use]
    pub const fn edge(&self, edge: Edge) -> Color32 {
        match edge {
            Edge::Light => self.bevel_light,
            Edge::Dark => self.bevel_dark,
        }
    }
}

/// The geometry a framed region is drawn with.
///
/// Every field is a value, which is why they all arrive from the caller:
/// radius and border width belong to `makeover-geometry`, and margins come
/// from its relational gaps.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FrameStyle {
    /// Corner radius. Square under the Platinum default.
    pub radius: CornerRadius,
    /// Inner margin between the frame and its contents.
    pub margin: Margin,
    /// Bevel stroke width, in points.
    pub stroke: f32,
}

impl Default for FrameStyle {
    /// A one-point square frame with no inner margin.
    fn default() -> Self {
        Self {
            radius: CornerRadius::ZERO,
            margin: Margin::ZERO,
            stroke: 1.0,
        }
    }
}

/// Paint a two-tone edge just inside `rect`.
///
/// Fill first, bevel after: this adds two polylines and nothing else, so it
/// composes over whatever is already there. That is what lets it go over an
/// [`egui::TextEdit`] after `ui.add`, where the widget's own fill has landed.
///
/// Two three-point polylines meeting at opposite corners, rather than four
/// segments, so egui mitres the corner joins instead of leaving a notch.
///
/// The dark polyline is drawn second, so the two corners where the runs meet
/// take its tone. That is the right answer here rather than a concession.
/// [`makeover_layout::Bevel`] holds those corners to belong to both edges, and
/// a renderer with room to divide one should; at the default one-point stroke
/// the corner is a one-point square, so the division is sub-pixel and
/// antialiasing resolves it to the same blend the mitre already gives. Splitting
/// it would add a seam and no information. `makeover-tui` does split, because a
/// terminal cell is large enough that not splitting costs a visible cell of edge
/// weight — the same rule, at a resolution where it has something to say.
pub fn paint_bevel(painter: &Painter, rect: Rect, bevel: Bevel, palette: &Palette, stroke: f32) {
    let (top_left, bottom_right) = bevel.edges();

    // Inset by half a stroke so the line lands inside `rect` rather than
    // straddling its edge, which on a fractional-scale display is the
    // difference between one crisp pixel and two dim ones.
    let r = rect.shrink(stroke / 2.0);

    painter.add(Shape::line(
        vec![r.left_bottom(), r.left_top(), r.right_top()],
        Stroke::new(stroke, palette.edge(top_left)),
    ));
    painter.add(Shape::line(
        vec![r.right_top(), r.right_bottom(), r.left_bottom()],
        Stroke::new(stroke, palette.edge(bottom_right)),
    ));
}

/// Draw a region at a given [`Depth`]: its fill and its edge, together.
///
/// [`Depth::Flat`] gets neither, and inherits whatever it sits on. That is the
/// difference between level-with and painted-the-same-colour, and it is the
/// reason `Depth::fill` returns an [`Option`] rather than defaulting to the
/// page.
pub fn frame<R>(
    ui: &mut Ui,
    depth: Depth,
    palette: &Palette,
    style: FrameStyle,
    add_contents: impl FnOnce(&mut Ui) -> R,
) -> R {
    let mut f = egui::Frame::new()
        .corner_radius(style.radius)
        .inner_margin(style.margin);
    // Two ways there is no fill to paint, and they collapse to the same
    // outcome: the depth names none (Depth::Flat), or it names one this
    // renderer cannot resolve. Either way the frame goes unfilled and the
    // bevel below carries the depth on its own, which is the rule this
    // module already documents for Flat.
    if let Some(fill) = depth.fill().and_then(|f| palette.fill(f)) {
        f = f.fill(fill);
    }
    let framed = f.show(ui, add_contents);
    if let Some(bevel) = depth.bevel() {
        paint_bevel(
            ui.painter(),
            framed.response.rect,
            bevel,
            palette,
            style.stroke,
        );
    }
    framed.inner
}

/// The geometry a field group is drawn with.
///
/// Values again, for the reason [`FrameStyle`] is: every number here belongs to
/// `makeover-geometry` and arrives already resolved.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FieldStyle {
    /// The well a text control sits in.
    pub frame: FrameStyle,
    /// Between a field's own parts: its label, its control, its hint and its
    /// error.
    pub gap: f32,
    /// Between one field and the next.
    pub group_gap: f32,
    /// What marks a required field, appended to its label.
    ///
    /// A knob rather than a constant, because it is the one piece of *copy* in
    /// this crate and copy is not a renderer's call. A webview does not need it
    /// at all — it emits the `required` attribute and the browser answers — so
    /// this renderer is the first place where a compulsory field either shows
    /// that it is or silently does not.
    pub required_marker: &'static str,
}

impl Default for FieldStyle {
    /// The default frame, no gaps, and an asterisk.
    fn default() -> Self {
        Self {
            frame: FrameStyle::default(),
            gap: 0.0,
            group_gap: 0.0,
            required_marker: "*",
        }
    }
}

/// What the field currently holds, borrowed from wherever the app keeps it.
///
/// The immediate-mode counterpart of `makeover_webview::form::Value`, and the
/// place the two renderers are forced apart: there the value is read back out
/// of the DOM after the fact, and here the widget writes through this borrow as
/// it is edited. Same reason the description carries neither.
///
/// An enum rather than a bag of options, on the reasoning
/// `makeover_webview::form::Value` records: a checkbox holding a string is
/// unsayable here, where a struct would let it be said and then have to cope.
#[derive(Debug, Default)]
pub enum Filling<'a> {
    /// Nothing to edit. The control is drawn and does not answer.
    #[default]
    Absent,
    /// The buffer behind anything that takes typed text, a select included:
    /// what a select holds is the `value` of one of its [`Choice`]s.
    ///
    /// [`Choice`]: makeover_layout::Choice
    Text(&'a mut String),
    /// A checkbox, on or off.
    On(&'a mut bool),
}

/// The label, marked if the field is compulsory.
fn label_text(field: &Field<'_>, style: &FieldStyle) -> String {
    if field.required {
        format!("{} {}", field.label, style.required_marker)
    } else {
        field.label.to_owned()
    }
}

/// The four shapes a control comes in here, which is fewer than there are
/// kinds.
///
/// [`FieldKind`] is `#[non_exhaustive]` and grows; this does not, because the
/// ways egui has of asking for a value do not. Reducing the open set to this
/// closed one in one total function is what keeps a new kind from needing a new
/// arm at every match below.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Control {
    /// Typed into, so it is drawn as a well: the user looks into it.
    Typed,
    /// Picked from a control that shows one option at a time. Pressed rather
    /// than looked into, so egui's own control painting stands.
    Chosen,
    /// Picked from options that are all on screen at once.
    ///
    /// Apart from [`Chosen`](Self::Chosen) because the description holds them
    /// apart, and holding them apart is the whole content of
    /// [`FieldKind::Radio`]: same question, and an answer the user can read
    /// without opening anything.
    Listed,
    /// Held on or off.
    Toggled,
}

/// Which shape a kind takes.
///
/// The wildcard falls to [`Control::Typed`] on purpose: a kind added to the
/// description since this renderer was built degrades to a text box, which
/// accepts any value the others would, rather than to nothing drawn at all.
const fn control_shape(kind: FieldKind) -> Control {
    match kind {
        FieldKind::Select => Control::Chosen,
        FieldKind::Radio => Control::Listed,
        FieldKind::Checkbox => Control::Toggled,
        _ => Control::Typed,
    }
}

/// What a select shows for the value it currently holds.
///
/// A value no option carries stays on screen as itself rather than reading as
/// whichever option happens to be first. goingson saved a backup retention of
/// 10 against a 1/3/7/14/0 list and the browser silently showed it as 1, so the
/// next save wrote a value nobody chose; `makeover-webview` grew the fix as a
/// stray `<option>` and this is the same fix in the shape egui allows.
fn shown_label<'a>(options: &'a [Choice<'a>], value: &'a str) -> &'a str {
    options
        .iter()
        .find(|opt| opt.value == value)
        .map_or(value, |opt| opt.label)
}

/// The control alone, without its label, hint or error.
fn control(
    ui: &mut Ui,
    field: &Field<'_>,
    filling: Filling<'_>,
    palette: &Palette,
    style: &FieldStyle,
) -> Response {
    // The mismatch path: described as one thing and filled as another. Nothing
    // here can fix it, so it is drawn as the empty, inert version of what was
    // described — visible on screen, in the way an empty select is at the
    // webview renderer, rather than reported in a log nobody reads.
    let mut discard = String::new();
    let mut off = false;

    match control_shape(field.kind) {
        Control::Typed => {
            let text = match filling {
                Filling::Text(text) => text,
                _ => &mut discard,
            };
            // An empty frame and no margin: the well is this crate's, and egui's
            // own control background and padding would sit underneath it saying
            // something different about both.
            let mut edit = if matches!(field.kind, FieldKind::Textarea) {
                TextEdit::multiline(text)
            } else {
                TextEdit::singleline(text)
            }
            .frame(egui::Frame::NONE)
            .margin(Margin::ZERO)
            .text_color(palette.content)
            .password(field.kind.confidential());
            if let Some(ghost) = field.placeholder {
                edit = edit.hint_text(RichText::new(ghost).color(palette.content_muted));
            }
            frame(ui, Depth::Well, palette, style.frame, |ui| ui.add(edit))
        }
        Control::Toggled => {
            let on = match filling {
                Filling::On(on) => on,
                _ => &mut off,
            };
            ui.checkbox(on, RichText::new(field.label).color(palette.content))
        }
        Control::Listed => {
            let value = match filling {
                Filling::Text(text) => text,
                _ => &mut discard,
            };
            // No `shown_label` counterpart, and none is needed: a value no
            // option carries leaves every button unfilled, which is already
            // the honest report on screen. The select needs the fix because it
            // has one slot and must put *something* in it.
            let group = ui.vertical(|ui| {
                let mut answered: Option<Response> = None;
                for opt in field.options {
                    let picked = ui.radio_value(
                        value,
                        opt.value.to_owned(),
                        RichText::new(opt.label).color(palette.content),
                    );
                    answered = Some(match answered {
                        Some(prev) => prev.union(picked),
                        None => picked,
                    });
                }
                answered
            });
            // A group described with no options answers as its own empty area
            // rather than as no response at all, which keeps the caller's
            // `.changed()` chain working on a field whose option list has not
            // loaded yet.
            group.inner.unwrap_or(group.response)
        }
        Control::Chosen => {
            let value = match filling {
                Filling::Text(text) => text,
                _ => &mut discard,
            };
            let shown = shown_label(field.options, value);
            ComboBox::from_id_salt(field.name)
                .selected_text(RichText::new(shown).color(palette.content))
                .show_ui(ui, |ui| {
                    for opt in field.options {
                        ui.selectable_value(
                            value,
                            opt.value.to_owned(),
                            RichText::new(opt.label).color(palette.content),
                        );
                    }
                })
                .response
        }
    }
}

/// One field, as the column the app drops into its form.
///
/// The anatomy is `makeover-webview`'s, so the two renderers put a form
/// together the same way: label, control, hint, error, top to bottom, with a
/// checkbox labelling itself instead of taking a label above.
///
/// Returns [`None`] for a [`FieldKind::Hidden`] field, which is what
/// [`FieldKind::visible`] means and is the honest answer here: a webview still
/// emits an input for it because the form submits, and an immediate-mode
/// renderer has no form and no submission, so a hidden field is a value the app
/// already holds and there is nothing to draw or to respond to.
///
/// `state` is the description's interaction axis.
/// [`State::Disabled`] greys the field and stops it answering, through
/// [`State::suppresses_interaction`] rather than through a second reading of
/// what disabled means. [`State::Focus`] is deliberately not acted on: egui
/// paints its own focus stroke and the description asks for one ring, not one
/// per renderer that happens to have opinions.
pub fn field(
    ui: &mut Ui,
    field: &Field<'_>,
    filling: Filling<'_>,
    state: Option<State>,
    palette: &Palette,
    style: &FieldStyle,
) -> Option<Response> {
    if !field.kind.visible() {
        return None;
    }
    let enabled = !state.is_some_and(State::suppresses_interaction);
    let text = if enabled {
        palette.content
    } else {
        palette.content_muted
    };

    let response = ui
        .vertical(|ui| {
            ui.spacing_mut().item_spacing.y = style.gap;

            // A checkbox labels itself, on the right of the box.
            // `FieldKind::labels_itself` is the description saying so, and both
            // webview apps special-cased it inline before it did.
            if !field.kind.labels_itself() {
                ui.label(RichText::new(label_text(field, style)).color(text));
            }

            let response = ui
                .add_enabled_ui(enabled, |ui| control(ui, field, filling, palette, style))
                .inner;

            // Standing help first, then what is wrong now. Both, in that order,
            // for the reason the webview renderer names both in
            // `aria-describedby`: an error appearing must not take the hint
            // away with it.
            if let Some(hint) = field.hint {
                ui.label(RichText::new(hint).color(palette.content_muted));
            }
            if let Some(error) = field.error {
                ui.label(RichText::new(error).color(palette.danger));
            }
            response
        })
        .inner;

    Some(response)
}

/// A set of fields, laid down a column.
///
/// `show_extended` is the disclosure, and it is a parameter rather than state
/// held here because the disclosure belongs to the *form* and not to any field:
/// [`Field::extended`] marks which fields are behind one, and the app owns
/// whether it is open. That is the same division `makeover-webview` draws when
/// it marks the group `data-extended` and emits no control to toggle it.
///
/// `draw` is called once per field that should be visible, in order. Taking a
/// callback rather than a slice of [`Filling`]s is what keeps the app's own
/// values borrowed one at a time: a form's fields usually live in different
/// structs, and a parallel array would have to be built each frame and kept in
/// step with the description by hand.
pub fn group<'a>(
    ui: &mut Ui,
    fields: &'a [Field<'a>],
    show_extended: bool,
    style: &FieldStyle,
    mut draw: impl FnMut(&mut Ui, &'a Field<'a>),
) {
    ui.vertical(|ui| {
        ui.spacing_mut().item_spacing.y = style.group_gap;
        for f in fields {
            if f.extended && !show_extended {
                continue;
            }
            draw(ui, f);
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    fn palette(well: Color32) -> Palette {
        Palette {
            page: Color32::from_rgb(1, 1, 1),
            raised: Color32::from_rgb(2, 2, 2),
            overlay: Color32::from_rgb(3, 3, 3),
            well,
            sunken: Color32::from_rgb(4, 4, 4),
            bevel_light: Color32::WHITE,
            bevel_dark: Color32::BLACK,
            content: Color32::from_rgb(5, 5, 5),
            content_muted: Color32::from_rgb(6, 6, 6),
            danger: Color32::from_rgb(7, 7, 7),
        }
    }

    #[test]
    fn a_well_resolves_to_its_own_token() {
        // No substitution left. The page-filled well was a stand-in for a
        // token that did not exist yet; it exists now.
        let w = Color32::from_rgb(9, 9, 9);
        let p = palette(w);
        assert_eq!(p.fill(Fill::Well), Some(w));
        assert_ne!(p.fill(Fill::Well), Some(p.page));
    }

    #[test]
    fn every_intent_is_a_plain_lookup() {
        let p = palette(Color32::from_rgb(9, 9, 9));
        assert_eq!(p.fill(Fill::Page), Some(p.page));
        assert_eq!(p.fill(Fill::Raised), Some(p.raised));
        assert_eq!(p.fill(Fill::Overlay), Some(p.overlay));
    }

    /// Sunken is its own colour, not the well's and not the page's. The two
    /// are authored in opposite directions and an earlier cut of the
    /// description conflated them.
    #[test]
    fn sunken_is_neither_the_well_nor_the_page() {
        let p = palette(Color32::from_rgb(9, 9, 9));
        assert_eq!(p.fill(Fill::Sunken), Some(p.sunken));
        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Well));
        assert_ne!(p.fill(Fill::Sunken), p.fill(Fill::Page));
    }

    #[test]
    fn a_raised_region_never_resolves_to_the_well_fill() {
        // The cross-app bug, asserted at the renderer boundary this time.
        let p = palette(Color32::from_rgb(9, 9, 9));
        let raised = Depth::Raised.fill().and_then(|f| p.fill(f));
        let well = Depth::Well.fill().and_then(|f| p.fill(f));
        assert_eq!(raised, Some(p.raised));
        assert_ne!(raised, well);
    }

    #[test]
    fn the_lit_edge_swaps_when_a_card_is_pressed() {
        let p = palette(Color32::from_rgb(9, 9, 9));
        let (tl, _) = Depth::Raised.bevel().unwrap().edges();
        let (ptl, _) = Depth::Raised.pressed().bevel().unwrap().edges();
        assert_eq!(p.edge(tl), p.bevel_light);
        assert_eq!(p.edge(ptl), p.bevel_dark);
    }

    #[test]
    fn flat_asks_for_neither_fill_nor_edge() {
        assert!(Depth::Flat.fill().is_none());
        assert!(Depth::Flat.bevel().is_none());
    }

    #[test]
    fn a_select_keeps_a_value_none_of_its_options_carries() {
        // The save-the-wrong-thing bug, asserted at the second renderer so it
        // is not re-found there. goingson's own numbers.
        let options = [
            Choice::plain("1"),
            Choice::plain("3"),
            Choice::plain("7"),
            Choice::plain("14"),
        ];
        assert_eq!(shown_label(&options, "10"), "10");
        // And a value that does match reads as its label, not as itself.
        let spelled = [Choice {
            value: "7",
            label: "One week",
        }];
        assert_eq!(shown_label(&spelled, "7"), "One week");
    }

    #[test]
    fn only_a_required_field_is_marked() {
        let style = FieldStyle::default();
        let plain = Field::new(FieldKind::Text, "title", "Title");
        assert_eq!(label_text(&plain, &style), "Title");

        let required = Field {
            required: true,
            ..plain
        };
        assert_eq!(label_text(&required, &style), "Title *");

        // The marker is copy and the app owns it, which is why it is a knob.
        let house = FieldStyle {
            required_marker: "(required)",
            ..style
        };
        assert_eq!(label_text(&required, &house), "Title (required)");
    }

    #[test]
    fn a_select_and_a_checkbox_are_pressed_and_everything_else_is_typed_into() {
        // What decides whether the control gets a well. A well is for what the
        // user looks into, and only one of these is.
        assert_eq!(control_shape(FieldKind::Select), Control::Chosen);
        assert_eq!(control_shape(FieldKind::Radio), Control::Listed);
        assert_eq!(control_shape(FieldKind::Checkbox), Control::Toggled);
        for k in [
            FieldKind::Text,
            FieldKind::Secret,
            FieldKind::Number,
            FieldKind::Email,
            FieldKind::Url,
            FieldKind::Tel,
            FieldKind::Textarea,
        ] {
            assert_eq!(control_shape(k), Control::Typed, "{k:?} is typed into");
        }
    }

    #[test]
    fn the_two_option_taking_kinds_are_drawn_differently_on_purpose() {
        // The description holds Select and Radio apart, and a renderer that
        // collapsed them would silently answer a question the app did not ask:
        // audiofiles' storage style is irreversible and its alternatives have
        // to be readable without opening anything. Asserting the two shapes
        // differ is asserting that distinction survives the trip.
        assert!(FieldKind::Select.offers_options());
        assert!(FieldKind::Radio.offers_options());
        assert_ne!(
            control_shape(FieldKind::Select),
            control_shape(FieldKind::Radio)
        );
    }

    #[test]
    fn a_hidden_field_draws_nothing_and_answers_nothing() {
        // Where the two renderers legitimately part: a webview still emits an
        // input because the form submits, and there is no form here.
        let f = Field::new(FieldKind::Hidden, "id", "Id");
        let p = palette(Color32::from_rgb(9, 9, 9));
        egui::__run_test_ui(|ui| {
            let drawn = field(ui, &f, Filling::Absent, None, &p, &FieldStyle::default());
            assert!(drawn.is_none());
        });
    }

    #[test]
    fn a_disabled_field_stops_answering_and_a_focused_one_does_not() {
        let f = Field::new(FieldKind::Text, "title", "Title");
        let p = palette(Color32::from_rgb(9, 9, 9));
        let style = FieldStyle::default();
        egui::__run_test_ui(|ui| {
            let mut text = String::from("x");
            let disabled = field(
                ui,
                &f,
                Filling::Text(&mut text),
                Some(State::Disabled),
                &p,
                &style,
            )
            .unwrap();
            assert!(!disabled.enabled());

            let mut text = String::from("x");
            let focused = field(
                ui,
                &f,
                Filling::Text(&mut text),
                Some(State::Focus),
                &p,
                &style,
            )
            .unwrap();
            assert!(focused.enabled(), "focus is a thing you can still click");
        });
    }

    #[test]
    fn a_field_described_one_way_and_filled_another_is_drawn_inert() {
        // No panic and no write-through. A checkbox handed a string cannot be
        // filled, so it is drawn off and left alone.
        let f = Field::new(FieldKind::Checkbox, "done", "Done");
        let p = palette(Color32::from_rgb(9, 9, 9));
        let mut text = String::from("untouched");
        egui::__run_test_ui(|ui| {
            let drawn = field(
                ui,
                &f,
                Filling::Text(&mut text),
                None,
                &p,
                &FieldStyle::default(),
            );
            assert!(drawn.is_some());
        });
        assert_eq!(text, "untouched");
    }

    #[test]
    fn the_disclosure_belongs_to_the_form_and_not_to_the_field() {
        let fields = [
            Field::new(FieldKind::Text, "title", "Title"),
            Field {
                extended: true,
                ..Field::new(FieldKind::Text, "notes", "Notes")
            },
        ];
        let style = FieldStyle::default();

        let mut closed = Vec::new();
        egui::__run_test_ui(|ui| {
            group(ui, &fields, false, &style, |_, f| closed.push(f.name));
        });
        assert_eq!(closed, ["title"]);

        let mut open = Vec::new();
        egui::__run_test_ui(|ui| {
            group(ui, &fields, true, &style, |_, f| open.push(f.name));
        });
        assert_eq!(open, ["title", "notes"]);
    }

    #[test]
    fn the_default_frame_is_square_and_one_point() {
        let d = FrameStyle::default();
        assert_eq!(d.radius, CornerRadius::ZERO);
        assert_eq!(d.margin, Margin::ZERO);
        assert!((d.stroke - 1.0).abs() < f32::EPSILON);
    }
}