Skip to main content

makeover_immediate/
host.rs

1//! The design system, handed to egui as a `Style`.
2//!
3//! <!-- wiki: makeover-immediate -->
4//!
5//! Every other module here draws with the palette. This one hands the
6//! palette to egui itself, so the widgets egui draws on its own account (a
7//! button's fill, a text field's well, a scrollbar, a checkbox, the frame
8//! around a window) wear the same theme as the ones this crate paints.
9//!
10//! # What is here
11//!
12//! [`visuals`] is the colour half: every fill, stroke, shadow and corner egui
13//! draws from, derived from a [`Palette`]. [`spacing`] and [`text_styles`]
14//! are the metric half, derived from `makeover-geometry`'s scale, and
15//! [`style`] composes all three.
16//!
17//! The density, the theme and the three sizes in [`Metrics`] are arguments;
18//! [`Metrics`] defaults them to what `makeover-webview` emits.
19
20use egui::{Color32, CornerRadius, Stroke, Visuals};
21use makeover_geometry::{Density, Gap, Step, Surface, TARGET_LEAST, Text};
22
23use crate::Palette;
24
25/// The sizes egui reads that are the app's to choose rather than the scale's.
26///
27/// Each defaults to what `makeover-webview` emits:
28///
29/// - [`radius`](Self::radius), how round a container is: square.
30/// - [`focus_stroke`](Self::focus_stroke), the focus ring's width: 2 points,
31///   the webview's `2px`.
32/// - [`target`](Self::target), the smallest a control is painted: 24 points,
33///   WCAG 2.5.8's floor.
34#[derive(Debug, Clone, Copy, PartialEq)]
35#[non_exhaustive]
36pub struct Metrics {
37    /// The app's container radius.
38    pub radius: CornerRadius,
39    /// The focus ring's width, in points.
40    pub focus_stroke: f32,
41    /// The smallest height a control is painted at, in points.
42    pub target: f32,
43}
44
45impl Default for Metrics {
46    fn default() -> Self {
47        Self {
48            radius: CornerRadius::ZERO,
49            focus_stroke: f32::from(makeover_geometry::Stroke::Mark.px()),
50            target: f32::from(TARGET_LEAST.px()),
51        }
52    }
53}
54
55impl Metrics {
56    /// Set [`radius`](Self::radius).
57    #[must_use]
58    pub const fn radius(mut self, radius: CornerRadius) -> Self {
59        self.radius = radius;
60        self
61    }
62
63    /// Set [`focus_stroke`](Self::focus_stroke).
64    #[must_use]
65    pub const fn focus_stroke(mut self, points: f32) -> Self {
66        self.focus_stroke = points;
67        self
68    }
69
70    /// Set [`target`](Self::target).
71    #[must_use]
72    pub const fn target(mut self, points: f32) -> Self {
73        self.target = points;
74        self
75    }
76}
77
78/// Whether this palette's page is a light surface.
79///
80/// Decides which of egui's two presets [`visuals`] starts from;
81/// `RichText::strong()` resolves through `dark_mode`.
82///
83/// True when the page's relative luminance is above about 0.179, where black
84/// and white text contrast equally with it.
85#[must_use]
86pub fn is_light(palette: &Palette) -> bool {
87    // Local rather than `makeover::color`: this crate does not link makeover
88    // unless the `theme` feature asks for it.
89    let channel = |c: u8| {
90        let c = f32::from(c) / 255.0;
91        if c <= 0.040_45 {
92            c / 12.92
93        } else {
94            ((c + 0.055) / 1.055).powf(2.4)
95        }
96    };
97    let page = palette.page;
98    let luminance = 0.2126_f32.mul_add(
99        channel(page.r()),
100        0.7152_f32.mul_add(channel(page.g()), 0.0722 * channel(page.b())),
101    );
102    // Where (1.0 + 0.05) / (l + 0.05) == (l + 0.05) / (0.0 + 0.05).
103    luminance > LIGHT_ABOVE
104}
105
106/// The relative luminance at which black and white text contrast equally.
107const LIGHT_ABOVE: f32 = 0.179;
108
109/// Mix two colours, `t` of the way from `a` to `b`.
110fn mix(from: Color32, to: Color32, at: f32) -> Color32 {
111    let channel = |from: u8, to: u8| {
112        let (from, to) = (f32::from(from), f32::from(to));
113        #[expect(
114            clippy::cast_possible_truncation,
115            clippy::cast_sign_loss,
116            reason = "a mix of two channel values is inside 0..=255 by construction"
117        )]
118        let mixed = (to - from).mul_add(at, from).round() as u8;
119        mixed
120    };
121    Color32::from_rgb(
122        channel(from.r(), to.r()),
123        channel(from.g(), to.g()),
124        channel(from.b(), to.b()),
125    )
126}
127
128/// The colours egui draws its own widgets with, from this palette.
129///
130/// The radius and the focus ring's width come from [`Metrics`].
131///
132/// - **State marks stay on the neutral ramp.** The pressed fill and the
133///   selection fill are neutral, since egui derives `strong_text_color()` from
134///   `widgets.active.fg_stroke`; the accent is reserved for the primary action.
135/// - **The selection stroke is content ink**, held to the words' floor. The
136///   same stroke rings a focused text edit.
137/// - **`weak_bg_fill` is set alongside every `bg_fill`**: egui's `Button`
138///   paints a resting button from the weak one.
139/// - **Nothing expands on hover or press.**
140/// - **Window and popup shadows** are [`Palette::cast`](crate::Palette::cast).
141#[must_use]
142pub fn visuals(palette: &Palette, metrics: &Metrics) -> Visuals {
143    let radius = metrics.radius;
144    let mut visuals = if is_light(palette) {
145        Visuals::light()
146    } else {
147        Visuals::dark()
148    };
149
150    visuals.panel_fill = palette.overlay;
151    visuals.window_fill = palette.overlay;
152    // The thing you look *into*, a text edit above all, is the well rather
153    // than the page. `field` fills from the well too, so anything else
154    // here would put a described field and a hand-built one at two colours.
155    visuals.extreme_bg_color = palette.well;
156    visuals.faint_bg_color = mix(palette.page, palette.overlay, 0.3);
157
158    visuals.selection.bg_fill = mix(palette.page, palette.content, 0.3);
159    visuals.selection.stroke = Stroke::new(metrics.focus_stroke, palette.content);
160
161    visuals.widgets.noninteractive.bg_fill = palette.overlay;
162    visuals.widgets.inactive.bg_fill = mix(palette.overlay, palette.sunken, 0.3);
163    visuals.widgets.hovered.bg_fill = palette.sunken;
164    visuals.widgets.active.bg_fill = mix(palette.sunken, palette.content, 0.15);
165
166    visuals.widgets.noninteractive.weak_bg_fill = visuals.widgets.noninteractive.bg_fill;
167    visuals.widgets.inactive.weak_bg_fill = visuals.widgets.inactive.bg_fill;
168    visuals.widgets.hovered.weak_bg_fill = visuals.widgets.hovered.bg_fill;
169    visuals.widgets.active.weak_bg_fill = visuals.widgets.active.bg_fill;
170    visuals.widgets.open.weak_bg_fill = visuals.widgets.inactive.bg_fill;
171
172    let hairline = f32::from(makeover_geometry::Stroke::Hairline.px());
173    visuals.widgets.noninteractive.fg_stroke = Stroke::new(hairline, palette.content_secondary);
174    visuals.widgets.inactive.fg_stroke = Stroke::new(hairline, palette.content);
175    visuals.widgets.hovered.fg_stroke = Stroke::new(hairline, palette.content);
176    visuals.widgets.active.fg_stroke = Stroke::new(hairline, palette.content);
177    visuals.widgets.open.fg_stroke = Stroke::new(hairline, palette.content);
178
179    visuals.window_stroke = Stroke::new(hairline, palette.border);
180    visuals.widgets.inactive.bg_stroke =
181        Stroke::new(0.5, mix(palette.border, palette.overlay, 0.3));
182    visuals.widgets.hovered.bg_stroke = Stroke::new(hairline, palette.border);
183    visuals.widgets.active.bg_stroke = Stroke::new(hairline, palette.action);
184    visuals.widgets.noninteractive.bg_stroke =
185        Stroke::new(0.5, mix(palette.border, palette.overlay, 0.4));
186
187    visuals.widgets.noninteractive.corner_radius = radius;
188    visuals.widgets.inactive.corner_radius = radius;
189    visuals.widgets.hovered.corner_radius = radius;
190    visuals.widgets.active.corner_radius = radius;
191    visuals.widgets.open.corner_radius = radius;
192    visuals.window_corner_radius = radius;
193    visuals.menu_corner_radius = radius;
194
195    // A hard shadow, offset down and right, because that is where the light
196    // the bevel pair assumes is coming from. A blur is a different design
197    // language and reads as a soft web card rather than a physical one.
198    let shadow = palette.cast();
199    visuals.window_shadow = shadow;
200    visuals.popup_shadow = shadow;
201
202    visuals.widgets.hovered.expansion = 0.0;
203    visuals.widgets.active.expansion = 0.0;
204
205    visuals
206}
207
208/// egui's spacing, from the relational scale.
209///
210/// - `item_spacing`: [`Gap::Peer`] across, [`Gap::Bound`] down.
211/// - `button_padding`: Peer across, [`Step::Hair`] down.
212/// - `window_margin`: [`Gap::Group`].
213/// - `indent`: [`Gap::Pane`].
214/// - `interact_size.y`: [`Metrics::target`], raised to the density's floor
215///   (44 points under [`Density::Touch`]), a minimum rather than a size. The
216///   width stays egui's own.
217#[must_use]
218pub fn spacing(surface: &Surface, density: Density, metrics: &Metrics) -> egui::style::Spacing {
219    // The step's size on the surface, snapped to its quantum: not the count of
220    // quanta `Surface::gap` answers, which is points only at a one-point quantum.
221    let gap = |g: Gap| surface.resolve(g.step_at(density).ratio());
222    let default = egui::style::Spacing::default();
223    egui::style::Spacing {
224        item_spacing: egui::vec2(gap(Gap::Peer), gap(Gap::Bound)),
225        button_padding: egui::vec2(gap(Gap::Peer), surface.resolve(Step::Hair.ratio())),
226        window_margin: egui::vec2(gap(Gap::Group), gap(Gap::Group)).into(),
227        indent: gap(Gap::Pane),
228        interact_size: egui::vec2(
229            default.interact_size.x,
230            metrics.target.max(f32::from(density.target_least_px())),
231        ),
232        ..default
233    }
234}
235
236/// egui's text styles, from the type scale.
237///
238/// egui's five roles onto the scale: `Small` is [`Text::Fine`], `Body` and
239/// `Button` are [`Text::Body`], `Monospace` is [`Text::Note`], and `Heading`
240/// is [`Text::Head`].
241#[must_use]
242pub fn text_styles(surface: &Surface) -> std::collections::BTreeMap<egui::TextStyle, egui::FontId> {
243    use egui::{FontFamily, FontId, TextStyle};
244    let size = |role: Text| surface.resolve(role.ratio());
245    [
246        (
247            TextStyle::Small,
248            FontId::new(size(Text::Fine), FontFamily::Proportional),
249        ),
250        (
251            TextStyle::Body,
252            FontId::new(size(Text::Body), FontFamily::Proportional),
253        ),
254        (
255            TextStyle::Button,
256            FontId::new(size(Text::Body), FontFamily::Proportional),
257        ),
258        (
259            TextStyle::Monospace,
260            FontId::new(size(Text::Note), FontFamily::Monospace),
261        ),
262        (
263            TextStyle::Heading,
264            FontId::new(size(Text::Head), FontFamily::Proportional),
265        ),
266    ]
267    .into()
268}
269
270/// The whole design system as one egui `Style`.
271///
272/// [`visuals`], [`spacing`] and [`text_styles`], composed. An app keeping one
273/// of its own calls the pieces.
274#[must_use]
275pub fn style(
276    palette: &Palette,
277    surface: &Surface,
278    density: Density,
279    metrics: &Metrics,
280) -> egui::Style {
281    egui::Style {
282        visuals: visuals(palette, metrics),
283        spacing: spacing(surface, density, metrics),
284        text_styles: text_styles(surface),
285        ..egui::Style::default()
286    }
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    fn palette(page: Color32, content: Color32) -> Palette {
294        Palette {
295            page,
296            content,
297            ..crate::tests::palette()
298        }
299    }
300
301    fn light() -> Palette {
302        palette(Color32::from_rgb(200, 200, 200), Color32::BLACK)
303    }
304
305    fn dark() -> Palette {
306        palette(
307            Color32::from_rgb(26, 27, 38),
308            Color32::from_rgb(192, 202, 245),
309        )
310    }
311
312    #[test]
313    fn a_light_page_starts_from_the_light_preset_and_a_dark_one_does_not() {
314        // Not cosmetic even though every widget colour is overridden below it:
315        // `RichText::strong()` resolves through `dark_mode`, so the wrong
316        // preset paints emphasised text white on a light page.
317        assert!(is_light(&light()));
318        assert!(!is_light(&dark()));
319        assert!(!visuals(&light(), &Metrics::default()).dark_mode);
320        assert!(visuals(&dark(), &Metrics::default()).dark_mode);
321    }
322
323    #[test]
324    fn a_saturated_page_is_judged_by_luminance_and_not_by_an_average() {
325        // A plain channel average calls a saturated blue light. Perceptual
326        // luminance does not, and green is what carries the weight.
327        let blue = palette(Color32::from_rgb(0, 0, 255), Color32::WHITE);
328        assert!(!is_light(&blue));
329    }
330
331    #[test]
332    fn a_mid_grey_page_reads_as_light() {
333        // #A0A0A0 is 0.35 luminance: dark text reads on it and white text does
334        // not, so it takes the light preset. A 0.5 midpoint called it dark.
335        let grey = palette(Color32::from_rgb(0xA0, 0xA0, 0xA0), Color32::BLACK);
336        assert!(is_light(&grey));
337        let charcoal = palette(Color32::from_rgb(0x40, 0x40, 0x40), Color32::WHITE);
338        assert!(!is_light(&charcoal));
339    }
340
341    #[test]
342    fn every_widget_state_carries_a_weak_fill_as_well_as_a_fill() {
343        // egui's `Button` paints from `weak_bg_fill` and only reaches for
344        // `bg_fill` once hovered, so a theme that sets one and not the other
345        // leaves every resting button at the preset default: near-black under
346        // a light theme, near-white under a dark one.
347        let v = visuals(&light(), &Metrics::default());
348        for (name, w) in [
349            ("noninteractive", &v.widgets.noninteractive),
350            ("inactive", &v.widgets.inactive),
351            ("hovered", &v.widgets.hovered),
352            ("active", &v.widgets.active),
353        ] {
354            assert_eq!(w.weak_bg_fill, w.bg_fill, "{name} disagrees with itself");
355        }
356    }
357
358    #[test]
359    fn the_pressed_fill_is_not_the_action_colour() {
360        // egui derives `strong_text_color()` from `widgets.active.fg_stroke`,
361        // so an accent-coloured pressed background forces the foreground to
362        // contrast with the accent, and that colour is then what every
363        // `RichText::strong()` in the app is painted in. Both the pressed fill
364        // and the selection fill stay neutral, and the words stay content.
365        let p = light();
366        let v = visuals(&p, &Metrics::default());
367        assert_ne!(v.widgets.active.bg_fill, p.action);
368        assert_eq!(v.widgets.active.fg_stroke.color, p.content);
369        assert_eq!(v.selection.stroke.color, p.content);
370    }
371
372    #[test]
373    fn nothing_swells_under_the_cursor() {
374        // An expanding widget drags its own bevel outward while the surface
375        // beneath it stays put, which fights the light model the bevel pair
376        // describes.
377        let v = visuals(&light(), &Metrics::default());
378        assert!(v.widgets.hovered.expansion.abs() < f32::EPSILON);
379        assert!(v.widgets.active.expansion.abs() < f32::EPSILON);
380    }
381
382    #[test]
383    fn a_finger_gets_the_touch_floor() {
384        let s = spacing(&Surface::web(), Density::Touch, &Metrics::default());
385        assert!((s.interact_size.y - 44.0).abs() < f32::EPSILON);
386        let p = spacing(&Surface::web(), Density::Pointer, &Metrics::default());
387        assert!((p.interact_size.y - 24.0).abs() < f32::EPSILON);
388    }
389
390    #[test]
391    fn a_control_clears_the_target_floor_and_text_clears_the_readable_one() {
392        // The two defects this module exists to stop a consumer rediscovering.
393        // egui ships 18 and 9; both are under a floor and neither was chosen.
394        let s = spacing(&Surface::web(), Density::Pointer, &Metrics::default());
395        assert!(
396            s.interact_size.y >= 24.0,
397            "interact_size {} is under the target floor",
398            s.interact_size.y
399        );
400
401        let styles = text_styles(&Surface::web());
402        for (role, font) in &styles {
403            assert!(
404                font.size >= 11.0,
405                "{role:?} is {} points, under the readable floor",
406                font.size
407            );
408        }
409    }
410
411    #[test]
412    fn the_scale_orders_the_text_roles() {
413        // Small below body, heading above it. A mapping that inverted one of
414        // these would still clear the floor above and be wrong.
415        let styles = text_styles(&Surface::web());
416        let size = |role: &egui::TextStyle| styles[role].size;
417        assert!(size(&egui::TextStyle::Small) < size(&egui::TextStyle::Body));
418        assert!(size(&egui::TextStyle::Heading) > size(&egui::TextStyle::Body));
419    }
420
421    #[test]
422    fn the_composed_style_is_the_three_pieces() {
423        let p = light();
424        let metrics = Metrics::default().radius(CornerRadius::same(4));
425        let composed = style(&p, &Surface::web(), Density::Pointer, &metrics);
426        assert_eq!(composed.visuals, visuals(&p, &metrics));
427        assert_eq!(
428            composed.spacing,
429            spacing(&Surface::web(), Density::Pointer, &metrics)
430        );
431        assert_eq!(composed.text_styles, text_styles(&Surface::web()));
432    }
433
434    #[test]
435    fn the_focus_ring_and_the_target_match_the_webview_until_the_app_says_otherwise() {
436        let v = visuals(&light(), &Metrics::default());
437        assert!((v.selection.stroke.width - 2.0).abs() < f32::EPSILON);
438        let heavier = visuals(&light(), &Metrics::default().focus_stroke(3.0));
439        assert!((heavier.selection.stroke.width - 3.0).abs() < f32::EPSILON);
440        let roomy = spacing(
441            &Surface::web(),
442            Density::Pointer,
443            &Metrics::default().target(32.0),
444        );
445        assert!((roomy.interact_size.y - 32.0).abs() < f32::EPSILON);
446    }
447
448    #[test]
449    fn repro_spacing_gap_quanta_as_points() {
450        // A surface with a two-point quantum: every gap is a size in points,
451        // snapped to the quantum, and never the count of quanta.
452        let surface = Surface {
453            base: 16.0,
454            quantum: 2.0,
455        };
456        let s = spacing(&surface, Density::Pointer, &Metrics::default());
457        let size = |gap: Gap| surface.resolve(gap.step_at(Density::Pointer).ratio());
458        assert!((s.item_spacing.x - size(Gap::Peer)).abs() < f32::EPSILON);
459        assert!((s.item_spacing.y - size(Gap::Bound)).abs() < f32::EPSILON);
460        assert!((s.indent - size(Gap::Pane)).abs() < f32::EPSILON);
461        assert!((f32::from(s.window_margin.left) - size(Gap::Group)).abs() < f32::EPSILON);
462    }
463}