makeover-immediate 0.70.0

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
//! 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 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.
//!
//! # What is here
//!
//! [`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.
//!
//! The density, the theme and the three sizes in [`Metrics`] are arguments;
//! [`Metrics`] defaults them to what `makeover-webview` emits.

use egui::{Color32, CornerRadius, 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.
///
/// Each defaults to what `makeover-webview` emits:
///
/// - [`radius`](Self::radius), how round a container is: square.
/// - [`focus_stroke`](Self::focus_stroke), the focus ring's width: 2 points,
///   the webview's `2px`.
/// - [`target`](Self::target), the smallest a control is painted: 24 points,
///   WCAG 2.5.8's floor.
#[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 [`visuals`] starts from;
/// `RichText::strong()` resolves through `dark_mode`.
///
/// True when the page's relative luminance is above about 0.179, where black
/// and white text contrast equally with 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_f32.mul_add(
        channel(page.r()),
        0.7152_f32.mul_add(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 = (to - from).mul_add(at, from).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`].
///
/// - **State marks stay on the neutral ramp.** The pressed fill and the
///   selection fill are neutral, since egui derives `strong_text_color()` from
///   `widgets.active.fg_stroke`; the accent is reserved for the primary action.
/// - **The selection stroke is content ink**, held to the words' floor. The
///   same stroke rings a focused text edit.
/// - **`weak_bg_fill` is set alongside every `bg_fill`**: egui's `Button`
///   paints a resting button from the weak one.
/// - **Nothing expands on hover or press.**
/// - **Window and popup shadows** are [`Palette::cast`](crate::Palette::cast).
#[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 = palette.cast();
    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.
///
/// - `item_spacing`: [`Gap::Peer`] across, [`Gap::Bound`] down.
/// - `button_padding`: Peer across, [`Step::Hair`] down.
/// - `window_margin`: [`Gap::Group`].
/// - `indent`: [`Gap::Pane`].
/// - `interact_size.y`: [`Metrics::target`], raised to the density's floor
///   (44 points under [`Density::Touch`]), a minimum rather than a size. The
///   width stays egui's own.
#[must_use]
pub fn spacing(surface: &Surface, density: Density, metrics: &Metrics) -> egui::style::Spacing {
    // The step's size on the surface, snapped to its quantum: not the count of
    // quanta `Surface::gap` answers, which is points only at a one-point quantum.
    let gap = |g: Gap| surface.resolve(g.step_at(density).ratio());
    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.max(f32::from(density.target_least_px())),
        ),
        ..default
    }
}

/// egui's text styles, from the type scale.
///
/// egui's five roles onto the scale: `Small` is [`Text::Fine`], `Body` and
/// `Button` are [`Text::Body`], `Monospace` is [`Text::Note`], and `Heading`
/// is [`Text::Head`].
#[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`.
///
/// [`visuals`], [`spacing`] and [`text_styles`], composed. An app keeping 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_finger_gets_the_touch_floor() {
        let s = spacing(&Surface::web(), Density::Touch, &Metrics::default());
        assert!((s.interact_size.y - 44.0).abs() < f32::EPSILON);
        let p = spacing(&Surface::web(), Density::Pointer, &Metrics::default());
        assert!((p.interact_size.y - 24.0).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);
    }

    #[test]
    fn repro_spacing_gap_quanta_as_points() {
        // A surface with a two-point quantum: every gap is a size in points,
        // snapped to the quantum, and never the count of quanta.
        let surface = Surface {
            base: 16.0,
            quantum: 2.0,
        };
        let s = spacing(&surface, Density::Pointer, &Metrics::default());
        let size = |gap: Gap| surface.resolve(gap.step_at(Density::Pointer).ratio());
        assert!((s.item_spacing.x - size(Gap::Peer)).abs() < f32::EPSILON);
        assert!((s.item_spacing.y - size(Gap::Bound)).abs() < f32::EPSILON);
        assert!((s.indent - size(Gap::Pane)).abs() < f32::EPSILON);
        assert!((f32::from(s.window_margin.left) - size(Gap::Group)).abs() < f32::EPSILON);
    }
}