Skip to main content

brep_app/
theme.rs

1//! Theme tokens: the one place a colour, size, radius, shadow or duration of
2//! the refreshed UI is written (section 3).
3//!
4//! STATUS: rollout step 1. Nothing in the app reads these tokens except the
5//! developer gallery ([`crate::ui_kit::gallery`]) and its whole-app PREVIEW,
6//! which is off unless the gallery turns it on. With the gallery closed and the
7//! preview off the app makes no call into this module.
8//!
9//! A [`Theme`](crate::theme::Theme) is built per mode (dark, light), density (compact, comfortable)
10//! and accent. [`Theme::apply`](crate::theme::Theme::apply) writes it into an `egui::Style`, which restyles
11//! every default egui widget; the [`crate::ui_kit`] components read the tokens
12//! directly through [`Theme::of`](crate::theme::Theme::of).
13use eframe::egui::{self, Color32};
14use std::sync::Arc;
15
16/// Dark or light chrome. The 3D viewport's colours are render settings and are
17/// not part of the theme.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum Mode {
20    Dark,
21    Light,
22}
23
24impl Mode {
25    pub fn of(dark: bool) -> Self {
26        if dark { Mode::Dark } else { Mode::Light }
27    }
28    pub fn label(self) -> &'static str {
29        match self {
30            Mode::Dark => "Dark",
31            Mode::Light => "Light",
32        }
33    }
34}
35
36/// Control heights and spacing. Compact is the proposed default (spec section 2).
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Density {
39    Compact,
40    Comfortable,
41}
42
43impl Density {
44    pub fn label(self) -> &'static str {
45        match self {
46            Density::Compact => "Compact",
47            Density::Comfortable => "Comfortable",
48        }
49    }
50}
51
52/// One accent the owner can choose between (spec section 9, decision 2).
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub struct Accent {
55    /// The key a command names it by.
56    pub key: &'static str,
57    pub label: &'static str,
58    pub color: Color32,
59}
60
61/// The accent candidates. The first is the spec's proposal.
62pub const ACCENTS: &[Accent] = &[
63    Accent { key: "blue", label: "Blue #3d8bfd (proposed)", color: Color32::from_rgb(0x3d, 0x8b, 0xfd) },
64    Accent { key: "brand", label: "Help-site blue #0b6bcb", color: Color32::from_rgb(0x0b, 0x6b, 0xcb) },
65    Accent { key: "teal", label: "Teal #14b8a6", color: Color32::from_rgb(0x14, 0xb8, 0xa6) },
66    Accent { key: "violet", label: "Violet #8b5cf6", color: Color32::from_rgb(0x8b, 0x5c, 0xf6) },
67    Accent { key: "orange", label: "Orange #f08c2e", color: Color32::from_rgb(0xf0, 0x8c, 0x2e) },
68    Accent { key: "green", label: "Green #2fb170", color: Color32::from_rgb(0x2f, 0xb1, 0x70) },
69];
70
71/// The accent with this key.
72pub fn accent(key: &str) -> Option<Accent> {
73    ACCENTS.iter().copied().find(|a| a.key == key)
74}
75
76/// The colour roles (spec section 3). Every colour is opaque except the three
77/// overlays, which are laid over whatever surface the control sits on.
78#[derive(Debug, Clone, Copy, PartialEq)]
79pub struct Palette {
80    /// The window background behind panels.
81    pub bg_app: Color32,
82    /// Panel surfaces.
83    pub bg_panel: Color32,
84    /// Cards, popups, menus.
85    pub bg_raised: Color32,
86    /// Text and number field fill.
87    pub bg_input: Color32,
88    /// Hover overlay (translucent).
89    pub hover: Color32,
90    /// Pressed overlay (translucent).
91    pub pressed: Color32,
92    /// Card and panel borders.
93    pub border_subtle: Color32,
94    /// Input borders.
95    pub border_strong: Color32,
96    /// The accent as chosen: focus rings, underlines, check marks, sliders.
97    pub accent: Color32,
98    /// The accent as a FILL under [`Palette::on_accent`] text: the accent
99    /// itself when white text reads on it at 4.5:1, else darkened until it does.
100    pub accent_fill: Color32,
101    /// The accent as TEXT on this mode's surfaces (4.5:1 on every one of them
102    /// and on [`Palette::accent_muted`] over them).
103    pub accent_text: Color32,
104    /// The accent as a focus RING or 2 px bar: 3:1 on every surface.
105    pub accent_ring: Color32,
106    /// Selected rows, active tab background (translucent: accent at 18 %).
107    /// Text on it is `text.primary` or `accent.text`, never `text.secondary`.
108    pub accent_muted: Color32,
109    /// Text on [`Palette::accent_fill`] and on the filled danger button.
110    pub on_accent: Color32,
111    pub text_primary: Color32,
112    pub text_secondary: Color32,
113    /// Disabled text. Exempt from the contrast rule (WCAG 1.4.3).
114    pub text_disabled: Color32,
115    pub danger: Color32,
116    /// The danger colour as a fill under [`Palette::on_accent`] text.
117    pub danger_fill: Color32,
118    pub warning: Color32,
119    pub success: Color32,
120    /// Popup and window shadow colour (translucent).
121    pub shadow: Color32,
122}
123
124const fn rgb(hex: u32) -> Color32 {
125    Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
126}
127
128/// WCAG relative luminance of an opaque colour.
129pub fn luminance(c: Color32) -> f32 {
130    let f = |v: u8| {
131        let v = f32::from(v) / 255.0;
132        if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
133    };
134    0.2126 * f(c.r()) + 0.7152 * f(c.g()) + 0.0722 * f(c.b())
135}
136
137/// WCAG contrast ratio of two opaque colours (1 to 21).
138pub fn contrast(a: Color32, b: Color32) -> f32 {
139    let (la, lb) = (luminance(a), luminance(b));
140    (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
141}
142
143/// `top` laid over the opaque `base` at `top`'s own alpha.
144pub fn over(base: Color32, top: Color32) -> Color32 {
145    let [r, g, b, a] = top.to_srgba_unmultiplied();
146    mix(base, Color32::from_rgb(r, g, b), f32::from(a) / 255.0)
147}
148
149/// `a` moved `t` of the way to `b` (both opaque).
150pub fn mix(a: Color32, b: Color32, t: f32) -> Color32 {
151    let ch = |x: u8, y: u8| (f32::from(x) * (1.0 - t) + f32::from(y) * t).round() as u8;
152    Color32::from_rgb(ch(a.r(), b.r()), ch(a.g(), b.g()), ch(a.b(), b.b()))
153}
154
155fn alpha(c: Color32, a: f32) -> Color32 {
156    Color32::from_rgba_unmultiplied(c.r(), c.g(), c.b(), (a * 255.0).round() as u8)
157}
158
159/// `color` moved towards `toward` in 2 % steps until `ok` accepts it.
160/// Returns `toward` if nothing less does.
161fn moved_until(color: Color32, toward: Color32, ok: impl Fn(Color32) -> bool) -> Color32 {
162    (0..=50).map(|step| mix(color, toward, step as f32 * 0.02)).find(|c| ok(*c)).unwrap_or(toward)
163}
164
165impl Palette {
166    pub fn new(mode: Mode, accent: Color32) -> Self {
167        let white = Color32::WHITE;
168        let black = Color32::BLACK;
169        let mut p = match mode {
170            Mode::Dark => Palette {
171                bg_app: rgb(0x0f151c),
172                bg_panel: rgb(0x151d26),
173                bg_raised: rgb(0x1b2531),
174                bg_input: rgb(0x0f151c),
175                hover: alpha(white, 0.06),
176                pressed: alpha(white, 0.10),
177                border_subtle: rgb(0x263241),
178                border_strong: rgb(0x334255),
179                accent,
180                accent_fill: accent,
181                accent_text: accent,
182                accent_ring: accent,
183                accent_muted: alpha(accent, 0.18),
184                on_accent: white,
185                text_primary: rgb(0xe6edf3),
186                text_secondary: rgb(0x9fb0c0),
187                text_disabled: rgb(0x5c6b7a),
188                // The spec's #f05252 reads 4.45:1 on bg.raised; one step lighter passes.
189                danger: rgb(0xf26464),
190                danger_fill: rgb(0xf05252),
191                warning: rgb(0xf5a524),
192                success: rgb(0x3fb950),
193                shadow: alpha(black, 0.45),
194            },
195            Mode::Light => Palette {
196                bg_app: rgb(0xe9edf2),
197                bg_panel: rgb(0xf4f6f9),
198                bg_raised: rgb(0xffffff),
199                bg_input: rgb(0xffffff),
200                hover: alpha(black, 0.05),
201                pressed: alpha(black, 0.09),
202                border_subtle: rgb(0xd3dae3),
203                border_strong: rgb(0xaeb9c6),
204                accent,
205                accent_fill: accent,
206                accent_text: accent,
207                accent_ring: accent,
208                accent_muted: alpha(accent, 0.18),
209                on_accent: white,
210                text_primary: rgb(0x17212b),
211                text_secondary: rgb(0x4a5868),
212                text_disabled: rgb(0x8d99a6),
213                danger: rgb(0xc62828),
214                danger_fill: rgb(0xc62828),
215                warning: rgb(0x8f5d00),
216                success: rgb(0x177332),
217                shadow: alpha(black, 0.18),
218            },
219        };
220        // The accent's derived forms. The accent the owner picks stays the hue;
221        // each use moves it only as far as its contrast rule needs.
222        let surfaces = [p.bg_app, p.bg_panel, p.bg_raised, p.bg_input];
223        let away = if mode == Mode::Dark { white } else { black };
224        let (hover, pressed, muted) = (p.hover, p.pressed, p.accent_muted);
225        // A fill carries white text; hovered and pressed it only gets darker
226        // ([`Palette::fill_hover`], [`Palette::fill_pressed`]).
227        let carries_white = |fill: Color32| contrast(white, fill) >= 4.5;
228        p.accent_fill = moved_until(accent, black, carries_white);
229        p.danger_fill = moved_until(p.danger_fill, black, carries_white);
230        p.accent_ring = moved_until(accent, away, |c| surfaces.iter().all(|bg| contrast(c, *bg) >= 3.0));
231        // Accent text reads on every surface at rest, hovered, pressed and selected.
232        let states: Vec<Color32> = surfaces
233            .iter()
234            .flat_map(|s| [*s, over(*s, hover), over(*s, pressed), over(*s, muted), over(over(*s, muted), hover)])
235            .collect();
236        p.accent_text = moved_until(accent, away, |c| states.iter().all(|bg| contrast(c, *bg) >= 4.5));
237        p
238    }
239
240    /// A filled button's fill while hovered: 8 % towards black, in both
241    /// modes, so its white text never loses contrast.
242    pub fn fill_hover(fill: Color32) -> Color32 {
243        mix(fill, Color32::BLACK, 0.08)
244    }
245
246    /// A filled button's fill while pressed: 16 % towards black.
247    pub fn fill_pressed(fill: Color32) -> Color32 {
248        mix(fill, Color32::BLACK, 0.16)
249    }
250}
251
252/// The 4 px spacing scale (spec section 3).
253pub mod space {
254    pub const XXS: f32 = 2.0;
255    pub const XS: f32 = 4.0;
256    pub const SM: f32 = 6.0;
257    pub const MD: f32 = 8.0;
258    pub const LG: f32 = 12.0;
259    pub const XL: f32 = 16.0;
260    pub const XXL: f32 = 24.0;
261    pub const XXXL: f32 = 32.0;
262}
263
264/// Corner radii (spec section 3).
265pub mod radius {
266    /// Inputs and small buttons.
267    pub const INPUT: f32 = 4.0;
268    /// Buttons and tabs.
269    pub const BUTTON: f32 = 6.0;
270    /// Cards and popups.
271    pub const CARD: f32 = 8.0;
272}
273
274/// Every border is 1 px; a focus ring or an active bar is 2 px.
275pub const BORDER: f32 = 1.0;
276pub const RING: f32 = 2.0;
277
278/// The type scale (spec section 4).
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280pub enum Text {
281    /// 11: captions, group labels, error messages.
282    Caption,
283    /// 13: body text and control text.
284    Body,
285    /// 12 semibold: field labels.
286    Label,
287    /// 14 semibold: section headers.
288    Section,
289    /// 16 semibold: panel and dialog titles.
290    Title,
291    /// 12 monospace: code, the console.
292    Code,
293}
294
295/// The font families the theme draws with. Until a UI font is chosen and bound
296/// (spec section 9, decision 1) all three are egui's own families, so a theme
297/// can always be drawn.
298#[derive(Debug, Clone, PartialEq, Eq)]
299pub struct Families {
300    pub text: egui::FontFamily,
301    /// The semibold face; the regular one where there is no semibold.
302    pub strong: egui::FontFamily,
303    pub mono: egui::FontFamily,
304}
305
306impl Default for Families {
307    fn default() -> Self {
308        Self {
309            text: egui::FontFamily::Proportional,
310            strong: egui::FontFamily::Proportional,
311            mono: egui::FontFamily::Monospace,
312        }
313    }
314}
315
316/// One theme: every token a component or the base egui style needs.
317#[derive(Debug, Clone, PartialEq)]
318pub struct Theme {
319    pub mode: Mode,
320    pub density: Density,
321    pub colors: Palette,
322    pub families: Families,
323    /// Turns every transition off.
324    pub reduce_motion: bool,
325}
326
327impl Default for Theme {
328    fn default() -> Self {
329        Theme::new(Mode::Dark, Density::Compact, ACCENTS[0].color)
330    }
331}
332
333impl Theme {
334    pub fn new(mode: Mode, density: Density, accent: Color32) -> Self {
335        Theme { mode, density, colors: Palette::new(mode, accent), families: Families::default(), reduce_motion: false }
336    }
337
338    pub fn with_families(mut self, families: Families) -> Self {
339        self.families = families;
340        self
341    }
342
343    pub fn with_reduce_motion(mut self, reduce: bool) -> Self {
344        self.reduce_motion = reduce;
345        self
346    }
347
348    /// The height of inputs, buttons and dropdowns: 24 compact, 28 comfortable.
349    pub fn control_height(&self) -> f32 {
350        match self.density {
351            Density::Compact => 24.0,
352            Density::Comfortable => 28.0,
353        }
354    }
355
356    /// The height of a small (`sm`) button; never under the 24 px hit target.
357    pub fn control_height_sm(&self) -> f32 {
358        24.0
359    }
360
361    /// The height of a list, menu or tree row.
362    pub fn row_height(&self) -> f32 {
363        match self.density {
364            Density::Compact => 24.0,
365            Density::Comfortable => 28.0,
366        }
367    }
368
369    /// Horizontal padding inside a control.
370    pub fn control_padding(&self) -> f32 {
371        match self.density {
372            Density::Compact => space::MD,
373            Density::Comfortable => space::LG,
374        }
375    }
376
377    pub fn font(&self, role: Text) -> egui::FontId {
378        let (size, family) = match role {
379            Text::Caption => (11.0, &self.families.text),
380            Text::Body => (13.0, &self.families.text),
381            Text::Label => (12.0, &self.families.strong),
382            Text::Section => (14.0, &self.families.strong),
383            Text::Title => (16.0, &self.families.strong),
384            Text::Code => (12.0, &self.families.mono),
385        };
386        egui::FontId::new(size, family.clone())
387    }
388
389    fn seconds(&self, s: f32) -> f32 {
390        if self.reduce_motion { 0.0 } else { s }
391    }
392    /// 80 ms: hover.
393    pub fn motion_fast(&self) -> f32 {
394        self.seconds(0.08)
395    }
396    /// 120 ms: press, focus, toggles.
397    pub fn motion_base(&self) -> f32 {
398        self.seconds(0.12)
399    }
400    /// 160 ms: the tab indicator, popups opening.
401    pub fn motion_slow(&self) -> f32 {
402        self.seconds(0.16)
403    }
404
405    /// The small shadow: popups and menus.
406    pub fn shadow_small(&self) -> egui::Shadow {
407        egui::Shadow { offset: [0, 2], blur: 8, spread: 0, color: self.colors.shadow }
408    }
409    /// The medium shadow: windows and dialogs.
410    pub fn shadow_medium(&self) -> egui::Shadow {
411        egui::Shadow { offset: [0, 6], blur: 20, spread: 0, color: self.colors.shadow }
412    }
413
414    /// The frame of a popup, menu or card on `bg.raised`.
415    pub fn raised_frame(&self) -> egui::Frame {
416        egui::Frame::new()
417            .fill(self.colors.bg_raised)
418            .stroke(egui::Stroke::new(BORDER, self.colors.border_subtle))
419            .corner_radius(radius::CARD)
420    }
421
422    /// Write the tokens into `style`: this alone restyles every default egui
423    /// widget (rollout step 2's foundation). Fields the theme has no token for
424    /// keep the value `style` came with.
425    pub fn apply(&self, style: &mut egui::Style) {
426        let c = &self.colors;
427        style.text_styles = [
428            (egui::TextStyle::Small, self.font(Text::Caption)),
429            (egui::TextStyle::Body, self.font(Text::Body)),
430            (egui::TextStyle::Button, self.font(Text::Body)),
431            (egui::TextStyle::Heading, self.font(Text::Title)),
432            (egui::TextStyle::Monospace, self.font(Text::Code)),
433        ]
434        .into();
435        style.animation_time = self.motion_base();
436
437        let s = &mut style.spacing;
438        let compact = self.density == Density::Compact;
439        s.item_spacing = if compact { egui::vec2(space::SM, space::XS) } else { egui::vec2(space::MD, space::SM) };
440        s.button_padding = egui::vec2(self.control_padding(), if compact { 3.0 } else { 5.0 });
441        s.interact_size = egui::vec2(40.0, self.control_height());
442        s.window_margin = egui::Margin::same(space::LG as i8);
443        s.menu_margin = egui::Margin::same(space::SM as i8);
444        s.indent = space::XL;
445        s.icon_width = 16.0;
446        s.icon_width_inner = 10.0;
447        s.icon_spacing = space::SM;
448        s.slider_rail_height = 4.0;
449        s.combo_height = 28.0 * 12.0;
450        // Solid bars stay (the app's own rule: overflow is visible without
451        // hovering); they only get thinner.
452        s.scroll.bar_width = 6.0;
453        s.scroll.handle_min_length = 24.0;
454
455        let v = &mut style.visuals;
456        *v = if self.mode == Mode::Dark { egui::Visuals::dark() } else { egui::Visuals::light() };
457        v.panel_fill = c.bg_panel;
458        v.window_fill = c.bg_raised;
459        v.extreme_bg_color = c.bg_input;
460        v.text_edit_bg_color = Some(c.bg_input);
461        v.faint_bg_color = over(c.bg_panel, c.hover);
462        v.code_bg_color = c.bg_input;
463        v.hyperlink_color = c.accent_text;
464        v.warn_fg_color = c.warning;
465        v.error_fg_color = c.danger;
466        v.weak_text_color = Some(c.text_secondary);
467        v.window_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
468        v.menu_corner_radius = egui::CornerRadius::same(radius::CARD as u8);
469        v.window_stroke = egui::Stroke::new(BORDER, c.border_subtle);
470        v.window_shadow = self.shadow_medium();
471        v.popup_shadow = self.shadow_small();
472        v.selection.bg_fill = over(c.bg_panel, alpha(c.accent, 0.35));
473        v.selection.stroke = egui::Stroke::new(BORDER, c.accent_ring);
474        v.text_cursor.stroke = egui::Stroke::new(RING, c.accent_ring);
475        v.slider_trailing_fill = true;
476        v.handle_shape = egui::style::HandleShape::Circle;
477        v.striped = false;
478
479        let button = egui::CornerRadius::same(radius::BUTTON as u8);
480        let w = &mut v.widgets;
481        // Labels, separators, frames.
482        w.noninteractive.bg_fill = c.bg_panel;
483        w.noninteractive.weak_bg_fill = c.bg_panel;
484        w.noninteractive.bg_stroke = egui::Stroke::new(BORDER, c.border_subtle);
485        w.noninteractive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
486        w.noninteractive.corner_radius = button;
487        // A control at rest: the secondary button. `bg_fill` is what egui
488        // fills a checkbox's box and a slider's rail and handle with: the
489        // input fill, so an unticked box reads as empty.
490        w.inactive.bg_fill = c.bg_input;
491        w.inactive.weak_bg_fill = c.bg_raised;
492        w.inactive.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
493        w.inactive.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
494        w.inactive.corner_radius = button;
495        w.inactive.expansion = 0.0;
496        w.hovered.bg_fill = over(c.bg_input, c.hover);
497        w.hovered.weak_bg_fill = over(c.bg_raised, c.hover);
498        w.hovered.bg_stroke = egui::Stroke::new(BORDER, c.border_strong);
499        w.hovered.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
500        w.hovered.corner_radius = button;
501        w.hovered.expansion = 0.0;
502        w.active.bg_fill = over(c.bg_input, c.pressed);
503        w.active.weak_bg_fill = over(c.bg_raised, c.pressed);
504        w.active.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
505        w.active.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
506        w.active.corner_radius = button;
507        w.active.expansion = 0.0;
508        w.open.bg_fill = over(c.bg_raised, c.pressed);
509        w.open.weak_bg_fill = over(c.bg_raised, c.pressed);
510        w.open.bg_stroke = egui::Stroke::new(BORDER, c.accent_ring);
511        w.open.fg_stroke = egui::Stroke::new(BORDER, c.text_primary);
512        w.open.corner_radius = button;
513        w.open.expansion = 0.0;
514    }
515
516    /// `base` with this theme applied.
517    pub fn style(&self, base: &egui::Style) -> egui::Style {
518        let mut style = base.clone();
519        self.apply(&mut style);
520        style
521    }
522
523    /// The theme the components under `ui` draw with: the one [`set`] stored,
524    /// or the default (dark, compact, the proposed accent).
525    pub fn of(ui: &egui::Ui) -> Arc<Theme> {
526        current(ui.ctx())
527    }
528}
529
530fn slot() -> egui::Id {
531    egui::Id::new("brep-theme")
532}
533
534/// Make `theme` the one [`Theme::of`] answers for this context.
535pub fn set(ctx: &egui::Context, theme: Arc<Theme>) {
536    ctx.data_mut(|d| d.insert_temp(slot(), theme));
537}
538
539/// Forget the stored theme.
540pub fn clear(ctx: &egui::Context) {
541    ctx.data_mut(|d| d.remove::<Arc<Theme>>(slot()));
542}
543
544/// The stored theme, if one is stored.
545pub fn stored(ctx: &egui::Context) -> Option<Arc<Theme>> {
546    ctx.data(|d| d.get_temp::<Arc<Theme>>(slot()))
547}
548
549/// The stored theme, or the default.
550pub fn current(ctx: &egui::Context) -> Arc<Theme> {
551    stored(ctx).unwrap_or_default()
552}
553