makeover-immediate 0.63.2

The immediate-mode renderer for makeover-layout, backed by egui: no cascade, no retained tree, one stroke per widget.
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! 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 draws
//!
//! The parts of the description that carry no vocabulary member: depth
//! ([`frame`], [`paint_bevel`]), the resolved colours ([`Palette`]), a table's
//! per-frame facts and cell tones ([`table`]), the token and the waiting
//! marks ([`piece`]), and the egui visuals and metrics a host starts from
//! ([`host`]).
//!
//! The vocabulary members (fields, columns, meters, controls, facts, figures
//! and charts) are drawn by `quasi-immediate`, which owns those types through
//! `quasi-router` and calls into this crate for everything above. The style
//! types it draws them with stay here: [`FieldStyle`], [`Editing`],
//! [`piece::PieceStyle`] and [`table::TableStyle`].
//!
//! # 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 substitutions: makeover
//! derives `surface-well` and every consumer reads the real token. [`Palette`]
//! is supplied by the caller already resolved.
//!
//! It picks no sizes either. Every radius, margin, stroke width and floor
//! arrives in a style type ([`FrameStyle`], [`FieldStyle`], [`piece::PieceStyle`],
//! [`table::TableStyle`], [`host::Metrics`]), and where one has a default it is
//! the suite's number rather than this crate's: the focus ring and the target
//! floor in [`host::Metrics`] default to what `makeover-webview` emits.
//!
//! `makeover` itself is linked only by the `theme` feature, for
//! `Palette::from_theme`: it embeds every shipped theme file, and an app that
//! resolves its own colours should not carry them.
//!
//! # 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.
//!
//! # Overlays
//!
//! [`Palette::cast`] is what overlaying means in immediate mode. [`frame`] hands
//! the cast shadow to the `egui::Frame` for any depth whose fill is
//! [`Fill::Overlay`], keyed off the fill rather than the variant.
//!
//! # Tones
//!
//! [`Palette`] carries the three status intents together rather than one per
//! widget, for the reason [`Palette::fill`] is an `Option`: `Tone` is five
//! members wide, and a resolver missing one has to invent a colour, which is a
//! substitution this crate does not make.
//!
//! # Focus and chrome
//!
//! **Focus is not describable, and egui owns all of it here.** Reach, focus
//! and the focus ring are this renderer's three answers and egui already has
//! all three: its own id stack decides what is reachable, its own state decides
//! what holds the keyboard, and it paints exactly one ring. Drawing a second
//! ring on top of egui's would break the one-ring rule. The terms are defined
//! once in `makeover_layout`'s crate header, "Reach, focus and the focus ring".
//!
//! **App-level chrome is not drawn here.** `quasi-router` names the affordances
//! that outlive one screen, and `quasi-immediate` answers them: this crate
//! depends on `makeover-layout` and not on `quasi-router`, one layer below the
//! renderers that consume a `Screen`.

#![forbid(unsafe_code)]

use egui::{Color32, CornerRadius, Margin, Painter, Rect, Shape, Stroke, Ui};
use makeover_layout::{Bevel, Depth, Edge, Fill, HEAT_BANDS, Heat, Tone};

pub mod host;
pub mod piece;
pub mod table;

/// 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.
///
/// `#[non_exhaustive]`, so a colour added here is not a breaking change: build
/// one with `Palette::from_theme` (the `theme` feature), or start from
/// [`Palette::two_tone`] and set every colour the app resolves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
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, so a
    /// resolved palette without a well is not a thing that exists here.
    /// `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,
    /// `elevation`.
    ///
    /// What a surface that floats OVER the page is cast onto it with. The one
    /// intent here that is about a surface's relationship to the page rather
    /// than about the surface, which is why it is a translucent near-black on
    /// every theme rather than something read off the palette's own ramp.
    ///
    /// **Only for a surface that overlays.** A menu, a tooltip, a modal. A
    /// surface *in* the layout takes a bevel, and reaching for this on a panel
    /// or a card is how a pre-Platinum look survives a conversion under a new
    /// name.
    ///
    /// egui has a real answer for this where a terminal does not: see
    /// [`Palette::cast`], which is the shadow to hand an
    /// [`egui::Frame`].
    pub elevation: Color32,
    /// `content`.
    ///
    /// Ordinary text.
    pub content: Color32,
    /// `content-secondary`.
    ///
    /// Inactive but usable: it still answers a press. The middle tone of the
    /// three (wiki `three-tone-convention`), and the one an unchosen option in
    /// a choice field takes.
    ///
    /// Not [`content_muted`](Self::content_muted), which carries a claim:
    /// `State::Disabled` resolves to it, so a live control wearing it tells the
    /// user it will not answer. `makeover-tui` draws the same widget the same
    /// way from `makeover-tui@230bf63`.
    ///
    /// A step of `content` toward the page, derived at load by `makeover`
    /// rather than authored, so it is read off the resolved theme here like
    /// any other token and never re-derived.
    pub content_secondary: Color32,
    /// `content-muted`.
    ///
    /// A field's hint, and what
    /// [`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,
    /// `action-primary`.
    ///
    /// What a control is drawn in.
    ///
    /// This is the intent [`CellPart`](makeover_layout::CellPart) exists to
    /// separate. A cell holding a control that takes the cell's text colour is
    /// the drift `CellPart` names.
    pub action: Color32,
    /// `content-on-action`: ink that stays readable on [`action`](Self::action).
    ///
    /// Derived by the theme with `readable_on(action)` rather than picked here,
    /// so a theme whose action hue is pale gets dark ink without this renderer
    /// knowing which themes those are.
    ///
    /// The one thing that fills with `action` is the act a screen is for, the
    /// leading control, which is why this colour exists.
    /// A renderer that fills with the accent and leaves the label on the
    /// ordinary content colour is one theme change away from unreadable.
    pub content_on_action: Color32,
    /// `danger`.
    ///
    /// A field's error message, a destructive control, a bar that has run over.
    pub danger: Color32,
    /// `success`.
    ///
    /// The three status intents arrive together and not one at a time:
    /// [`Tone`] is five members wide and a resolver missing one has to invent
    /// a colour for it, which is the substitution [`Palette::fill`] refuses.
    pub success: Color32,
    /// `warning`.
    pub warning: Color32,
    /// `info`.
    pub info: Color32,
    /// `border`, the authored line colour.
    ///
    /// A neutral badge's edge: a badge on the raised ground is raised too, so
    /// the edge is what draws it.
    pub border: Color32,
    /// `info-surface`: raised with 12 percent of `info`. A badge's fill.
    ///
    /// The four tone surfaces arrive together for the status intents' reason.
    pub info_surface: Color32,
    /// `success-surface`.
    pub success_surface: Color32,
    /// `warning-surface`.
    pub warning_surface: Color32,
    /// `danger-surface`.
    pub danger_surface: Color32,
    /// `row-hover`: the row under the pointer, at 9 percent.
    pub row_hover: Color32,
    /// `row-rule`: the hairline between rows and around a table, at 26
    /// percent.
    pub row_rule: Color32,
    /// `row-selected`: a selected row, raised with 18 percent of the accent.
    ///
    /// A fill and never a foreground, so a row that is red for a failure stays
    /// red while it is selected.
    pub row_selected: Color32,
    /// `heat-0` to `heat-4`: the measure ramp, quietest first, from the
    /// raised ground to the cursor row's mix. Read through
    /// [`heat`](Self::heat).
    pub heats: [Color32; HEAT_BANDS as usize],
}

impl Palette {
    /// Every surface `page` and every ink `ink`, with no cast shadow.
    ///
    /// A starting point for the setters, legible on its own and wrong in every
    /// detail a theme decides: an app that resolves its own colours starts here
    /// and sets each one, and a colour added to this type later arrives at one
    /// of these two rather than as a compile error in every consumer.
    #[must_use]
    pub const fn two_tone(page: Color32, ink: Color32) -> Self {
        Self {
            page,
            raised: page,
            overlay: page,
            well: page,
            sunken: page,
            bevel_light: page,
            bevel_dark: ink,
            elevation: Color32::TRANSPARENT,
            content: ink,
            content_secondary: ink,
            content_muted: ink,
            action: ink,
            content_on_action: page,
            danger: ink,
            success: ink,
            warning: ink,
            info: ink,
            border: ink,
            info_surface: page,
            success_surface: page,
            warning_surface: page,
            danger_surface: page,
            row_hover: page,
            row_rule: ink,
            row_selected: page,
            heats: [page; HEAT_BANDS as usize],
        }
    }

    /// Set [`page`](Self::page).
    #[must_use]
    pub const fn page(mut self, colour: Color32) -> Self {
        self.page = colour;
        self
    }

    /// Set [`raised`](Self::raised).
    #[must_use]
    pub const fn raised(mut self, colour: Color32) -> Self {
        self.raised = colour;
        self
    }

    /// Set [`overlay`](Self::overlay).
    #[must_use]
    pub const fn overlay(mut self, colour: Color32) -> Self {
        self.overlay = colour;
        self
    }

    /// Set [`well`](Self::well).
    #[must_use]
    pub const fn well(mut self, colour: Color32) -> Self {
        self.well = colour;
        self
    }

    /// Set [`sunken`](Self::sunken).
    #[must_use]
    pub const fn sunken(mut self, colour: Color32) -> Self {
        self.sunken = colour;
        self
    }

    /// Set [`bevel_light`](Self::bevel_light).
    #[must_use]
    pub const fn bevel_light(mut self, colour: Color32) -> Self {
        self.bevel_light = colour;
        self
    }

    /// Set [`bevel_dark`](Self::bevel_dark).
    #[must_use]
    pub const fn bevel_dark(mut self, colour: Color32) -> Self {
        self.bevel_dark = colour;
        self
    }

    /// Set [`elevation`](Self::elevation).
    #[must_use]
    pub const fn elevation(mut self, colour: Color32) -> Self {
        self.elevation = colour;
        self
    }

    /// Set [`content`](Self::content).
    #[must_use]
    pub const fn content(mut self, colour: Color32) -> Self {
        self.content = colour;
        self
    }

    /// Set [`content_secondary`](Self::content_secondary).
    #[must_use]
    pub const fn content_secondary(mut self, colour: Color32) -> Self {
        self.content_secondary = colour;
        self
    }

    /// Set [`content_muted`](Self::content_muted).
    #[must_use]
    pub const fn content_muted(mut self, colour: Color32) -> Self {
        self.content_muted = colour;
        self
    }

    /// Set [`action`](Self::action).
    #[must_use]
    pub const fn action(mut self, colour: Color32) -> Self {
        self.action = colour;
        self
    }

    /// Set [`content_on_action`](Self::content_on_action).
    #[must_use]
    pub const fn content_on_action(mut self, colour: Color32) -> Self {
        self.content_on_action = colour;
        self
    }

    /// Set [`danger`](Self::danger).
    #[must_use]
    pub const fn danger(mut self, colour: Color32) -> Self {
        self.danger = colour;
        self
    }

    /// Set [`success`](Self::success).
    #[must_use]
    pub const fn success(mut self, colour: Color32) -> Self {
        self.success = colour;
        self
    }

    /// Set [`warning`](Self::warning).
    #[must_use]
    pub const fn warning(mut self, colour: Color32) -> Self {
        self.warning = colour;
        self
    }

    /// Set [`info`](Self::info).
    #[must_use]
    pub const fn info(mut self, colour: Color32) -> Self {
        self.info = colour;
        self
    }

    /// Set [`border`](Self::border).
    #[must_use]
    pub const fn border(mut self, colour: Color32) -> Self {
        self.border = colour;
        self
    }

    /// Set [`info_surface`](Self::info_surface).
    #[must_use]
    pub const fn info_surface(mut self, colour: Color32) -> Self {
        self.info_surface = colour;
        self
    }

    /// Set [`success_surface`](Self::success_surface).
    #[must_use]
    pub const fn success_surface(mut self, colour: Color32) -> Self {
        self.success_surface = colour;
        self
    }

    /// Set [`warning_surface`](Self::warning_surface).
    #[must_use]
    pub const fn warning_surface(mut self, colour: Color32) -> Self {
        self.warning_surface = colour;
        self
    }

    /// Set [`danger_surface`](Self::danger_surface).
    #[must_use]
    pub const fn danger_surface(mut self, colour: Color32) -> Self {
        self.danger_surface = colour;
        self
    }

    /// Set [`row_hover`](Self::row_hover).
    #[must_use]
    pub const fn row_hover(mut self, colour: Color32) -> Self {
        self.row_hover = colour;
        self
    }

    /// Set [`row_rule`](Self::row_rule).
    #[must_use]
    pub const fn row_rule(mut self, colour: Color32) -> Self {
        self.row_rule = colour;
        self
    }

    /// Set [`row_selected`](Self::row_selected).
    #[must_use]
    pub const fn row_selected(mut self, colour: Color32) -> Self {
        self.row_selected = colour;
        self
    }

    /// Set [`heats`](Self::heats).
    #[must_use]
    pub const fn heats(mut self, ramp: [Color32; HEAT_BANDS as usize]) -> Self {
        self.heats = ramp;
        self
    }

    /// Every colour, read from a resolved makeover theme.
    ///
    /// # Errors
    ///
    /// [`MissingToken`] naming the first token the theme does not resolve.
    /// makeover derives every one of these for every shipped theme, so this
    /// fails only on a theme file missing a base intent.
    #[cfg(feature = "theme")]
    pub fn from_theme(tokens: &makeover::SemanticTokens) -> Result<Self, MissingToken> {
        use makeover::Token;
        let colour = |token: Token| {
            tokens
                .rgba(token)
                .map(|(r, g, b, a)| Color32::from_rgba_unmultiplied(r, g, b, a))
                .ok_or(MissingToken(token))
        };
        Ok(Self {
            page: colour(Token::SurfacePage)?,
            raised: colour(Token::SurfaceRaised)?,
            overlay: colour(Token::SurfaceOverlay)?,
            well: colour(Token::SurfaceWell)?,
            sunken: colour(Token::SurfaceSunken)?,
            bevel_light: colour(Token::BevelLight)?,
            bevel_dark: colour(Token::BevelDark)?,
            elevation: colour(Token::Elevation)?,
            content: colour(Token::Content)?,
            content_secondary: colour(Token::ContentSecondary)?,
            content_muted: colour(Token::ContentMuted)?,
            action: colour(Token::Action)?,
            content_on_action: colour(Token::ContentOnAction)?,
            danger: colour(Token::Danger)?,
            success: colour(Token::Success)?,
            warning: colour(Token::Warning)?,
            info: colour(Token::Info)?,
            border: colour(Token::Border)?,
            info_surface: colour(Token::InfoSurface)?,
            success_surface: colour(Token::SuccessSurface)?,
            warning_surface: colour(Token::WarningSurface)?,
            danger_surface: colour(Token::DangerSurface)?,
            row_hover: colour(Token::RowHover)?,
            row_rule: colour(Token::RowRule)?,
            row_selected: colour(Token::RowSelected)?,
            heats: [
                colour(Token::Heat0)?,
                colour(Token::Heat1)?,
                colour(Token::Heat2)?,
                colour(Token::Heat3)?,
                colour(Token::Heat4)?,
            ],
        })
    }
}

/// A token `Palette::from_theme` needed and the theme did not resolve.
#[cfg(feature = "theme")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MissingToken(pub makeover::Token);

#[cfg(feature = "theme")]
impl std::fmt::Display for MissingToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "the theme resolves no `{}`", self.0.as_str())
    }
}

#[cfg(feature = "theme")]
impl std::error::Error for MissingToken {}

impl Palette {
    /// Resolve a surface intent, or `None` for one this renderer does not know.
    ///
    /// A plain lookup, and no substitution.
    ///
    /// `Option`, because [`Fill`] is `#[non_exhaustive]` and a total function
    /// over an open enum can only stay total by inventing a colour for a member
    /// it has never heard of. 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,
        }
    }

    /// The colour a [`Tone`] reads as.
    ///
    /// Total, unlike [`fill`](Self::fill), and the difference is not an
    /// inconsistency. `Fill` is `#[non_exhaustive]` and `Tone` is not: the
    /// description layer settled tone at five members and grows surfaces, so a
    /// total function here cannot be made to invent a colour by an upstream
    /// release the way a total `fill` could.
    ///
    /// [`Tone::Neutral`] is [`content`](Self::content) rather than a colour of
    /// its own, which is what "an ordinary fact" means: a neutral badge is text
    /// in a box, not a fifth status.
    #[must_use]
    pub const fn tone(&self, tone: Tone) -> Color32 {
        match tone {
            Tone::Neutral => self.content,
            Tone::Info => self.info,
            Tone::Success => self.success,
            Tone::Warning => self.warning,
            Tone::Danger => self.danger,
            // A tone this renderer has not learnt yet reads as an ordinary
            // fact rather than as a status it might misstate.
            _ => self.content,
        }
    }

    /// The fill a measure band sits on, or `None` at band 0, which is the
    /// ground and draws nothing. A band past the last reads as the last.
    #[must_use]
    pub const fn heat(&self, heat: Heat) -> Option<Color32> {
        let last = HEAT_BANDS - 1;
        match if heat.0 > last { last } else { heat.0 } {
            0 => None,
            band => Some(self.heats[band as usize]),
        }
    }

    /// What a badge of this tone is filled with: its tone surface, or the
    /// raised surface for [`Tone::Neutral`], as `makeover-webview` fills one.
    #[must_use]
    pub const fn tone_surface(&self, tone: Tone) -> Color32 {
        match tone {
            Tone::Neutral => self.raised,
            Tone::Info => self.info_surface,
            Tone::Success => self.success_surface,
            Tone::Warning => self.warning_surface,
            Tone::Danger => self.danger_surface,
            _ => self.raised,
        }
    }

    /// What a badge of this tone is edged with: its tone, or
    /// [`border`](Self::border) for [`Tone::Neutral`], whose tone is the ink.
    #[must_use]
    pub const fn tone_edge(&self, tone: Tone) -> Color32 {
        match tone {
            Tone::Neutral => self.border,
            other => self.tone(other),
        }
    }

    /// The cast shadow for a surface that overlays the page.
    ///
    /// What "overlaying" means in immediate mode, answered rather than skipped.
    /// egui already paints shadows for its menus and windows through
    /// [`egui::Frame::shadow`], so the honest port is to hand that machinery the
    /// theme's tone instead of egui's own default, not to invent a painter here
    /// the way [`paint_bevel`] had to.
    ///
    /// The geometry matches what `makeover-webview` composes, in points rather
    /// than pixels: a small downward offset and a wide soft blur. A Platinum-era
    /// menu sits just off the page rather than hovering above it.
    ///
    /// ```no_run
    /// # let palette: makeover_immediate::Palette = unimplemented!();
    /// # let ui: &mut egui::Ui = unimplemented!();
    /// egui::Frame::popup(ui.style())
    ///     .shadow(palette.cast())
    ///     .show(ui, |ui| { ui.label("over the page"); });
    /// ```
    #[must_use]
    pub const fn cast(&self) -> egui::Shadow {
        egui::Shadow {
            offset: [0, 2],
            blur: 24,
            spread: 0,
            color: self.elevation,
        }
    }

    /// 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,
            // An edge this renderer has not learnt is drawn as the border, the
            // one line every surface already has.
            _ => self.border,
        }
    }
}

/// 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: f32::from(makeover_geometry::Stroke::Hairline.px()),
        }
    }
}

/// 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)),
    ));
    // Three points close the box, two leave the bottom open: the shaded run
    // comes down the right side and stops. That is the folder tab, and it is
    // the same edge the browser draws by dropping the shadow's vertical
    // offset. The lit polyline is untouched either way, so the join is the
    // only thing that changes.
    let shaded = if bevel.draws_bottom() {
        vec![r.right_top(), r.right_bottom(), r.left_bottom()]
    } else {
        vec![r.right_top(), r.right_bottom()]
    };
    painter.add(Shape::line(
        shaded,
        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);
    }
    // A surface that overlays the page is cast onto it, with
    // [`Palette::cast`]. Keyed off the fill rather than the variant, so it stays right for whatever else the description calls an
    // overlay later.
    if depth.fill() == Some(Fill::Overlay) {
        f = f.shadow(palette.cast());
    }
    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.
///
/// The fields themselves are drawn by `quasi-immediate`; the style lives here
/// beside [`FrameStyle`], which it embeds, so an app sets both in one place.
/// 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.
///
/// Handed to `quasi-immediate`'s field, which writes through it as the user
/// edits.
///
/// The editable counterpart of [`makeover_layout::Value`], which is what the
/// other renderers read: there the value is read back after the fact, and here
/// the widget writes through this borrow as it is edited. The description
/// carries neither, for the same reason.
///
/// An enum rather than a bag of options, on the reasoning
/// [`makeover_layout::Value`] records: a checkbox holding a string is
/// unsayable here, where a struct would let it be said and then have to cope.
///
/// `#[non_exhaustive]`: a host builds these and never matches on them, so the
/// next shape of held value costs nobody a match arm.
#[derive(Debug, Default)]
#[non_exhaustive]
pub enum Editing<'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 options.
    Text(&'a mut String),
    /// A checkbox, on or off.
    On(&'a mut bool),
    /// The values of a [`FieldKind::Checklist`](makeover_layout::FieldKind::Checklist)'s ticked options.
    ///
    /// The values rather than a bool per option, because the options are the
    /// description's and the set is the app's: a host keeps what was ticked
    /// under the option values it submits, and a parallel list of bools would
    /// have to be re-aligned with the options every time the list changed.
    /// Ticking pushes the option's value and unticking removes it, so the order
    /// is the order things were ticked in, which is no order a handler should
    /// read anything into.
    Ticked(&'a mut Vec<String>),
    /// The two buffers behind a [`FieldKind::Interval`](makeover_layout::FieldKind::Interval), lower first.
    ///
    /// Two buffers rather than one string with a separator: an
    /// interval is submitted under two names, so it is edited as two values,
    /// and a delimiter this crate owned could appear inside either of them.
    ///
    /// Either end may be empty while the other stands. An open end is an
    /// answer ("over 120 BPM") rather than a half-filled box.
    Between {
        /// The lower end's buffer.
        lower: &'a mut String,
        /// The upper end's buffer.
        upper: &'a mut String,
    },
}

#[cfg(test)]
mod tests;