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