makeover-immediate 0.55.1

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
//! 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 not the app's job, though it has been
//!
//! [`Palette`] is twenty-five colours and nothing else, so before this module
//! an app got the colours for *described* content and inherited egui's own
//! defaults for everything else. That is not a small residue. audiofiles
//! discovered it three separate times in one afternoon, each time as a
//! defect found by measurement rather than by reading:
//!
//! - every control was 18 points high, egui's `interact_size`, against a
//!   24-point floor;
//! - every table column heading was 9 points, egui's `TextStyle::Small`,
//!   under the 11 points at which text stops being readable;
//! - every window offered a collapse triangle, egui's default, on screens
//!   with no collapsed state to show.
//!
//! None of those were choices. They were what egui ships with, surviving
//! because nothing had said otherwise, and the app that found them then
//! wrote about a hundred and seventy lines of mapping by hand. The next
//! consumer would have written them again, differently, and a fourth defect
//! would have waited for a fourth 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, the corner radius its buttons take, which theme is loaded: those
//! are arguments. This module maps a resolved design system onto egui and
//! holds no opinion of its own.

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

use crate::Palette;

/// The focus ring's width, in points.
///
/// egui's default is a one-point contrast hairline that is very hard to see
/// against a themed surface. A ring is the only thing telling a keyboard user
/// where they are, so it is drawn at a width that survives being looked at.
const FOCUS_STROKE: f32 = 1.5;

/// 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.
#[must_use]
pub fn is_light(palette: &Palette) -> bool {
    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());
    luminance > 0.5
}

/// 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.
///
/// `radius` is the app's own container radius, because how round a thing is
/// is a house style rather than a fact about the palette. Square is a
/// defensible default and so is not: this crate does not pick.
///
/// Three choices here are worth their reasoning, because each was arrived at
/// by getting it wrong first.
///
/// **The pressed fill stays neutral rather than taking 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
/// application is painted in. The accent shows up in the focus ring instead,
/// where it belongs.
///
/// **`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, radius: CornerRadius) -> Visuals {
    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. `widget::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.action, 0.3);
    visuals.selection.stroke = Stroke::new(FOCUS_STROKE, palette.action);

    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;

    visuals.widgets.noninteractive.fg_stroke = Stroke::new(1.0, palette.content_secondary);
    visuals.widgets.inactive.fg_stroke = Stroke::new(1.0, palette.content);
    visuals.widgets.hovered.fg_stroke = Stroke::new(1.0, palette.content);
    visuals.widgets.active.fg_stroke = Stroke::new(1.0, palette.content);
    visuals.widgets.open.fg_stroke = Stroke::new(1.0, palette.content);

    visuals.window_stroke = Stroke::new(1.0, 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(1.0, palette.border);
    visuals.widgets.active.bg_stroke = Stroke::new(1.0, 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
}

/// The smallest a control may be painted, in points.
///
/// WCAG 2.5.8 and the Mac HIG's floor. egui's own `interact_size` is 18,
/// which pads out to about 22 on a button, and no one chose either number.
const TARGET: f32 = 24.0;

/// 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
/// the target floor, 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) -> 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, 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
/// [`table`](crate::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,
    radius: CornerRadius,
) -> egui::Style {
    egui::Style {
        visuals: visuals(palette, radius),
        spacing: spacing(surface, density),
        text_styles: text_styles(surface),
        ..egui::Style::default()
    }
}

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

    /// A palette with every field distinct, so a mapping that reads the
    /// wrong token shows up as the wrong colour rather than as a coincidence.
    fn palette(page: Color32, content: Color32) -> Palette {
        Palette {
            page,
            raised: Color32::from_rgb(2, 2, 2),
            overlay: Color32::from_rgb(3, 3, 3),
            well: Color32::from_rgb(4, 4, 4),
            sunken: Color32::from_rgb(5, 5, 5),
            bevel_light: Color32::from_rgb(6, 6, 6),
            bevel_dark: Color32::from_rgb(7, 7, 7),
            elevation: Color32::from_rgb(8, 8, 8),
            content,
            content_secondary: Color32::from_rgb(10, 10, 10),
            content_muted: Color32::from_rgb(11, 11, 11),
            action: Color32::from_rgb(12, 12, 12),
            content_on_action: Color32::from_rgb(250, 250, 250),
            danger: Color32::from_rgb(13, 13, 13),
            success: Color32::from_rgb(14, 14, 14),
            warning: Color32::from_rgb(15, 15, 15),
            info: Color32::from_rgb(16, 16, 16),
            border: Color32::from_rgb(17, 17, 17),
            info_surface: Color32::from_rgb(18, 18, 18),
            success_surface: Color32::from_rgb(19, 19, 19),
            warning_surface: Color32::from_rgb(20, 20, 20),
            danger_surface: Color32::from_rgb(21, 21, 21),
            row_stripe: Color32::from_rgb(22, 22, 22),
            row_hover: Color32::from_rgb(23, 23, 23),
            row_rule: Color32::from_rgb(24, 24, 24),
            row_selected: Color32::from_rgb(25, 25, 25),
        }
    }

    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),
        )
    }

    fn surface() -> Surface {
        Surface {
            base: f32::from(makeover_geometry::DEFAULT_BASE_PX),
            quantum: 1.0,
        }
    }

    #[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(), CornerRadius::ZERO).dark_mode);
        assert!(visuals(&dark(), CornerRadius::ZERO).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 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(), CornerRadius::ZERO);
        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. The accent belongs
        // in the focus ring, which is where this puts it.
        let p = light();
        let v = visuals(&p, CornerRadius::ZERO);
        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.action);
    }

    #[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(), CornerRadius::ZERO);
        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(), Density::Pointer);
        assert!(
            s.interact_size.y >= 24.0,
            "interact_size {} is under the target floor",
            s.interact_size.y
        );

        let styles = text_styles(&surface());
        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());
        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 radius = CornerRadius::same(4);
        let composed = style(&p, &surface(), Density::Pointer, radius);
        assert_eq!(composed.visuals, visuals(&p, radius));
        assert_eq!(composed.spacing, spacing(&surface(), Density::Pointer));
        assert_eq!(composed.text_styles, text_styles(&surface()));
    }
}