makeover-immediate 0.63.1

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
//! The design system, handed to egui as a `Style`.
//!
//! <!-- wiki: makeover-immediate -->
//!
//! Every other module here draws *with* the palette. This one hands the
//! palette to egui itself, so that the widgets egui draws on its own account
//! (a button's fill, a text field's well, a scrollbar, a checkbox, the frame
//! around a window) wear the same theme as the ones this crate paints.
//!
//! # Why this is the renderer's job
//!
//! [`Palette`] is colours and nothing else, so without this module an app
//! gets the theme for *described* content and egui's own defaults for
//! everything else: controls 18 points high against a 24-point floor, table
//! headings in a 9-point `TextStyle::Small` under the 11 points at which text
//! stays readable, and a collapse triangle on windows with nothing to
//! collapse. None of those are choices; they are what egui ships. Mapping the
//! design system onto egui once, here, is what keeps each consumer from
//! finding them again by measurement.
//!
//! # What is here and what is deliberately not
//!
//! [`visuals`] is the colour half: every fill, stroke, shadow and corner egui
//! draws from, derived from a [`Palette`]. [`spacing`] and [`text_styles`]
//! are the metric half, derived from `makeover-geometry`'s scale, and
//! [`style`] composes all three.
//!
//! What is *not* here is anything an app should still decide. The density it
//! draws at, which theme is loaded, and the three sizes in [`Metrics`] are
//! arguments; [`Metrics`] defaults them to what `makeover-webview` emits.

use egui::{Color32, CornerRadius, Shadow, Stroke, Visuals};
use makeover_geometry::{Density, Gap, Step, Surface, TARGET_LEAST, Text};

use crate::Palette;

/// The sizes egui reads that are the app's to choose rather than the scale's.
///
/// Not on [`Palette`], which is colours. Three numbers, each a house decision
/// with a floor under it, defaulting to what `makeover-webview` emits so the
/// three renderers agree until an app says otherwise:
///
/// - [`radius`](Self::radius), how round a container is: square by default.
/// - [`focus_stroke`](Self::focus_stroke), the focus ring's width: 2 points,
///   the webview's `2px`. egui's own is a one-point hairline that disappears
///   against a themed surface, and the ring is the only thing telling a
///   keyboard user where they are.
/// - [`target`](Self::target), the smallest a control is painted: 24 points,
///   WCAG 2.5.8 and the Mac HIG's floor. egui's `interact_size` is 18.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Metrics {
    /// The app's container radius.
    pub radius: CornerRadius,
    /// The focus ring's width, in points.
    pub focus_stroke: f32,
    /// The smallest height a control is painted at, in points.
    pub target: f32,
}

impl Default for Metrics {
    fn default() -> Self {
        Self {
            radius: CornerRadius::ZERO,
            focus_stroke: f32::from(makeover_geometry::Stroke::Mark.px()),
            target: f32::from(TARGET_LEAST.px()),
        }
    }
}

impl Metrics {
    /// Set [`radius`](Self::radius).
    #[must_use]
    pub const fn radius(mut self, radius: CornerRadius) -> Self {
        self.radius = radius;
        self
    }

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

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

/// Whether this palette's page is a light surface.
///
/// Decides which of egui's two presets the visuals start from, and that is
/// not cosmetic even though every widget colour below is overridden:
/// `RichText::strong()` resolves through `dark_mode`, so starting from the
/// wrong one paints emphasised text white on a light page.
///
/// Perceptual luminance rather than a plain average, so a saturated blue page
/// is not mistaken for a light one. The threshold is where black text and
/// white text contrast equally with the page (relative luminance about 0.179),
/// not the midpoint of the scale: a mid grey like `#A0A0A0` sits at 0.35 and
/// reads with dark text, which is the light preset. Measured on a midpoint,
/// it took the dark preset and painted strong text white on it.
#[must_use]
pub fn is_light(palette: &Palette) -> bool {
    // Local rather than `makeover::color`: this crate does not link makeover
    // unless the `theme` feature asks for it.
    let channel = |c: u8| {
        let c = f32::from(c) / 255.0;
        if c <= 0.040_45 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    let page = palette.page;
    let luminance =
        0.2126 * channel(page.r()) + 0.7152 * channel(page.g()) + 0.0722 * channel(page.b());
    // Where (1.0 + 0.05) / (l + 0.05) == (l + 0.05) / (0.0 + 0.05).
    luminance > LIGHT_ABOVE
}

/// The relative luminance at which black and white text contrast equally.
const LIGHT_ABOVE: f32 = 0.179;

/// Mix two colours, `t` of the way from `a` to `b`.
fn mix(from: Color32, to: Color32, at: f32) -> Color32 {
    let channel = |from: u8, to: u8| {
        let (from, to) = (f32::from(from), f32::from(to));
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "a mix of two channel values is inside 0..=255 by construction"
        )]
        let mixed = (from + (to - from) * at).round() as u8;
        mixed
    };
    Color32::from_rgb(
        channel(from.r(), to.r()),
        channel(from.g(), to.g()),
        channel(from.b(), to.b()),
    )
}

/// The colours egui draws its own widgets with, from this palette.
///
/// The radius and the focus ring's width come from [`Metrics`]: how round a
/// thing is and how heavy its ring are house decisions rather than facts about
/// the palette.
///
/// These choices are worth their reasoning, because each was arrived at
/// by getting it wrong first.
///
/// **State marks stay on the neutral ramp.** egui derives
/// `strong_text_color()` from `widgets.active.fg_stroke`, so an accent-coloured
/// pressed background forces the foreground to contrast with the accent, and
/// that colour is then what every `RichText::strong()` in the application is
/// painted in. The pressed fill and the selection fill both stay neutral, and
/// the accent is reserved for the primary action (accent-as-state ruling).
///
/// **The selection stroke is content ink.** egui paints a selected control's
/// words and selected text in it, so it is held to the words' floor. The same
/// stroke rings a focused text edit, which then rings in content: a higher
/// contrast than the accent, which misses the page's floor on several ported
/// themes.
///
/// **`weak_bg_fill` is set alongside every `bg_fill`.** egui's `Button` paints
/// from the weak one and only reaches for `bg_fill` once hovered, so a theme
/// that sets only `bg_fill` leaves every resting button at the preset default:
/// near-black under a light theme, near-white under a dark one.
///
/// **Nothing expands on hover.** A widget that swells a point under the cursor
/// drags its own bevel outward while the surface beneath it stays put, which
/// fights the light model the bevel pair describes. State change is carried by
/// the bevel inverting, which is a stronger signal and costs no layout.
#[must_use]
pub fn visuals(palette: &Palette, metrics: &Metrics) -> Visuals {
    let radius = metrics.radius;
    let mut visuals = if is_light(palette) {
        Visuals::light()
    } else {
        Visuals::dark()
    };

    visuals.panel_fill = palette.overlay;
    visuals.window_fill = palette.overlay;
    // The thing you look *into*, a text edit above all, is the well rather
    // than the page. `field` fills from the well too, so anything else
    // here would put a described field and a hand-built one at two colours.
    visuals.extreme_bg_color = palette.well;
    visuals.faint_bg_color = mix(palette.page, palette.overlay, 0.3);

    visuals.selection.bg_fill = mix(palette.page, palette.content, 0.3);
    visuals.selection.stroke = Stroke::new(metrics.focus_stroke, palette.content);

    visuals.widgets.noninteractive.bg_fill = palette.overlay;
    visuals.widgets.inactive.bg_fill = mix(palette.overlay, palette.sunken, 0.3);
    visuals.widgets.hovered.bg_fill = palette.sunken;
    visuals.widgets.active.bg_fill = mix(palette.sunken, palette.content, 0.15);

    visuals.widgets.noninteractive.weak_bg_fill = visuals.widgets.noninteractive.bg_fill;
    visuals.widgets.inactive.weak_bg_fill = visuals.widgets.inactive.bg_fill;
    visuals.widgets.hovered.weak_bg_fill = visuals.widgets.hovered.bg_fill;
    visuals.widgets.active.weak_bg_fill = visuals.widgets.active.bg_fill;
    visuals.widgets.open.weak_bg_fill = visuals.widgets.inactive.bg_fill;

    let hairline = f32::from(makeover_geometry::Stroke::Hairline.px());
    visuals.widgets.noninteractive.fg_stroke = Stroke::new(hairline, palette.content_secondary);
    visuals.widgets.inactive.fg_stroke = Stroke::new(hairline, palette.content);
    visuals.widgets.hovered.fg_stroke = Stroke::new(hairline, palette.content);
    visuals.widgets.active.fg_stroke = Stroke::new(hairline, palette.content);
    visuals.widgets.open.fg_stroke = Stroke::new(hairline, palette.content);

    visuals.window_stroke = Stroke::new(hairline, palette.border);
    visuals.widgets.inactive.bg_stroke =
        Stroke::new(0.5, mix(palette.border, palette.overlay, 0.3));
    visuals.widgets.hovered.bg_stroke = Stroke::new(hairline, palette.border);
    visuals.widgets.active.bg_stroke = Stroke::new(hairline, palette.action);
    visuals.widgets.noninteractive.bg_stroke =
        Stroke::new(0.5, mix(palette.border, palette.overlay, 0.4));

    visuals.widgets.noninteractive.corner_radius = radius;
    visuals.widgets.inactive.corner_radius = radius;
    visuals.widgets.hovered.corner_radius = radius;
    visuals.widgets.active.corner_radius = radius;
    visuals.widgets.open.corner_radius = radius;
    visuals.window_corner_radius = radius;
    visuals.menu_corner_radius = radius;

    // A hard shadow, offset down and right, because that is where the light
    // the bevel pair assumes is coming from. A blur is a different design
    // language and reads as a soft web card rather than a physical one.
    let shadow = Shadow {
        offset: [2, 2],
        blur: 0,
        spread: 0,
        color: palette.elevation,
    };
    visuals.window_shadow = shadow;
    visuals.popup_shadow = shadow;

    visuals.widgets.hovered.expansion = 0.0;
    visuals.widgets.active.expansion = 0.0;

    visuals
}

/// egui's spacing, from the relational scale.
///
/// The mapping is nearly one for one. `item_spacing` separates controls of a
/// kind, so [`Gap::Peer`] across and [`Gap::Bound`] down, because a stacked
/// row sits closer to its neighbour than a side-by-side one does.
/// `button_padding` is the distance from a button's edge to its label, Peer
/// across and a hair down because a button is wider than it is tall.
/// `window_margin` is a panel's inner margin, which is a group. `indent`
/// offsets a child from its parent, a hierarchy rather than a separation, so
/// it is the width that reads as one pane at this type size.
///
/// `interact_size.y` is the one number here that is not a relationship: it is
/// [`Metrics::target`], and it is a minimum rather than a size. The width is
/// left at egui's own, which is about `DragValue` and friends; forcing it on
/// every control would stretch a one-word button for nothing a reader gains.
#[must_use]
pub fn spacing(surface: &Surface, density: Density, metrics: &Metrics) -> egui::style::Spacing {
    #[expect(
        clippy::cast_precision_loss,
        reason = "a gap is a small whole number of points; the scale tops out at 32"
    )]
    let gap = |g: Gap| surface.gap(g, density) as f32;
    let default = egui::style::Spacing::default();
    egui::style::Spacing {
        item_spacing: egui::vec2(gap(Gap::Peer), gap(Gap::Bound)),
        button_padding: egui::vec2(gap(Gap::Peer), surface.resolve(Step::Hair.ratio())),
        window_margin: egui::vec2(gap(Gap::Group), gap(Gap::Group)).into(),
        indent: gap(Gap::Pane),
        interact_size: egui::vec2(default.interact_size.x, metrics.target),
        ..default
    }
}

/// egui's text styles, from the type scale.
///
/// egui ships five roles and the scale has nine, so this maps the five onto
/// the nearest role rather than inventing names: `Small` is [`Text::Fine`],
/// `Body` and `Button` are [`Text::Body`], `Monospace` is [`Text::Note`]
/// because a monospaced face reads larger at the same size, and `Heading` is
/// [`Text::Head`].
///
/// `Small` is the one that has bitten. egui defaults it to 9 points, which is
/// under the 11 at which text stops being readable, and the egui table sets
/// every column heading in it. The scale has
/// nothing below `Fine` on purpose: if a thing is worth painting it is worth
/// three quarters of the base.
#[must_use]
pub fn text_styles(surface: &Surface) -> std::collections::BTreeMap<egui::TextStyle, egui::FontId> {
    use egui::{FontFamily, FontId, TextStyle};
    let size = |role: Text| surface.resolve(role.ratio());
    [
        (
            TextStyle::Small,
            FontId::new(size(Text::Fine), FontFamily::Proportional),
        ),
        (
            TextStyle::Body,
            FontId::new(size(Text::Body), FontFamily::Proportional),
        ),
        (
            TextStyle::Button,
            FontId::new(size(Text::Body), FontFamily::Proportional),
        ),
        (
            TextStyle::Monospace,
            FontId::new(size(Text::Note), FontFamily::Monospace),
        ),
        (
            TextStyle::Heading,
            FontId::new(size(Text::Head), FontFamily::Proportional),
        ),
    ]
    .into()
}

/// The whole design system as one egui `Style`.
///
/// The three above, composed. An app that wants all of it calls this and sets
/// the result; an app that wants to keep one of its own calls the pieces.
#[must_use]
pub fn style(
    palette: &Palette,
    surface: &Surface,
    density: Density,
    metrics: &Metrics,
) -> egui::Style {
    egui::Style {
        visuals: visuals(palette, metrics),
        spacing: spacing(surface, density, metrics),
        text_styles: text_styles(surface),
        ..egui::Style::default()
    }
}

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

    fn palette(page: Color32, content: Color32) -> Palette {
        Palette {
            page,
            content,
            ..crate::tests::palette()
        }
    }

    fn light() -> Palette {
        palette(Color32::from_rgb(200, 200, 200), Color32::BLACK)
    }

    fn dark() -> Palette {
        palette(
            Color32::from_rgb(26, 27, 38),
            Color32::from_rgb(192, 202, 245),
        )
    }

    #[test]
    fn a_light_page_starts_from_the_light_preset_and_a_dark_one_does_not() {
        // Not cosmetic even though every widget colour is overridden below it:
        // `RichText::strong()` resolves through `dark_mode`, so the wrong
        // preset paints emphasised text white on a light page.
        assert!(is_light(&light()));
        assert!(!is_light(&dark()));
        assert!(!visuals(&light(), &Metrics::default()).dark_mode);
        assert!(visuals(&dark(), &Metrics::default()).dark_mode);
    }

    #[test]
    fn a_saturated_page_is_judged_by_luminance_and_not_by_an_average() {
        // A plain channel average calls a saturated blue light. Perceptual
        // luminance does not, and green is what carries the weight.
        let blue = palette(Color32::from_rgb(0, 0, 255), Color32::WHITE);
        assert!(!is_light(&blue));
    }

    #[test]
    fn a_mid_grey_page_reads_as_light() {
        // #A0A0A0 is 0.35 luminance: dark text reads on it and white text does
        // not, so it takes the light preset. A 0.5 midpoint called it dark.
        let grey = palette(Color32::from_rgb(0xA0, 0xA0, 0xA0), Color32::BLACK);
        assert!(is_light(&grey));
        let charcoal = palette(Color32::from_rgb(0x40, 0x40, 0x40), Color32::WHITE);
        assert!(!is_light(&charcoal));
    }

    #[test]
    fn every_widget_state_carries_a_weak_fill_as_well_as_a_fill() {
        // egui's `Button` paints from `weak_bg_fill` and only reaches for
        // `bg_fill` once hovered, so a theme that sets one and not the other
        // leaves every resting button at the preset default: near-black under
        // a light theme, near-white under a dark one.
        let v = visuals(&light(), &Metrics::default());
        for (name, w) in [
            ("noninteractive", &v.widgets.noninteractive),
            ("inactive", &v.widgets.inactive),
            ("hovered", &v.widgets.hovered),
            ("active", &v.widgets.active),
        ] {
            assert_eq!(w.weak_bg_fill, w.bg_fill, "{name} disagrees with itself");
        }
    }

    #[test]
    fn the_pressed_fill_is_not_the_action_colour() {
        // egui derives `strong_text_color()` from `widgets.active.fg_stroke`,
        // so an accent-coloured pressed background forces the foreground to
        // contrast with the accent, and that colour is then what every
        // `RichText::strong()` in the app is painted in. Both the pressed fill
        // and the selection fill stay neutral, and the words stay content.
        let p = light();
        let v = visuals(&p, &Metrics::default());
        assert_ne!(v.widgets.active.bg_fill, p.action);
        assert_eq!(v.widgets.active.fg_stroke.color, p.content);
        assert_eq!(v.selection.stroke.color, p.content);
    }

    #[test]
    fn nothing_swells_under_the_cursor() {
        // An expanding widget drags its own bevel outward while the surface
        // beneath it stays put, which fights the light model the bevel pair
        // describes.
        let v = visuals(&light(), &Metrics::default());
        assert!(v.widgets.hovered.expansion.abs() < f32::EPSILON);
        assert!(v.widgets.active.expansion.abs() < f32::EPSILON);
    }

    #[test]
    fn a_control_clears_the_target_floor_and_text_clears_the_readable_one() {
        // The two defects this module exists to stop a consumer rediscovering.
        // egui ships 18 and 9; both are under a floor and neither was chosen.
        let s = spacing(&Surface::web(), Density::Pointer, &Metrics::default());
        assert!(
            s.interact_size.y >= 24.0,
            "interact_size {} is under the target floor",
            s.interact_size.y
        );

        let styles = text_styles(&Surface::web());
        for (role, font) in &styles {
            assert!(
                font.size >= 11.0,
                "{role:?} is {} points, under the readable floor",
                font.size
            );
        }
    }

    #[test]
    fn the_scale_orders_the_text_roles() {
        // Small below body, heading above it. A mapping that inverted one of
        // these would still clear the floor above and be wrong.
        let styles = text_styles(&Surface::web());
        let size = |role: &egui::TextStyle| styles[role].size;
        assert!(size(&egui::TextStyle::Small) < size(&egui::TextStyle::Body));
        assert!(size(&egui::TextStyle::Heading) > size(&egui::TextStyle::Body));
    }

    #[test]
    fn the_composed_style_is_the_three_pieces() {
        let p = light();
        let metrics = Metrics::default().radius(CornerRadius::same(4));
        let composed = style(&p, &Surface::web(), Density::Pointer, &metrics);
        assert_eq!(composed.visuals, visuals(&p, &metrics));
        assert_eq!(
            composed.spacing,
            spacing(&Surface::web(), Density::Pointer, &metrics)
        );
        assert_eq!(composed.text_styles, text_styles(&Surface::web()));
    }

    #[test]
    fn the_focus_ring_and_the_target_match_the_webview_until_the_app_says_otherwise() {
        let v = visuals(&light(), &Metrics::default());
        assert!((v.selection.stroke.width - 2.0).abs() < f32::EPSILON);
        let heavier = visuals(&light(), &Metrics::default().focus_stroke(3.0));
        assert!((heavier.selection.stroke.width - 3.0).abs() < f32::EPSILON);
        let roomy = spacing(
            &Surface::web(),
            Density::Pointer,
            &Metrics::default().target(32.0),
        );
        assert!((roomy.interact_size.y - 32.0).abs() < f32::EPSILON);
    }
}