Skip to main content

crisol_ui_kit/foundation/
style.rs

1//! Application-wide shape, density, and type scale: control heights, row heights,
2//! corner radii, border width, and text size.
3//!
4//! Colors come from the [`crate::theme`]; this module holds everything else that makes
5//! the workbench look compact, roomy, sharp, or round. Install a [`WorkbenchStyle`]
6//! once with [`set`] (it survives theme changes) and every component reads it with
7//! [`get`]. The default reproduces the shell exactly, pixel for pixel.
8//!
9//! ```
10//! use crisol_ui_kit::style::{self, Density, WorkbenchStyle};
11//! # let ctx = crisol_ui_kit::egui::Context::default();
12//! style::set(&ctx, WorkbenchStyle {
13//!     density: Density::Compact,
14//!     control_radius: 3,
15//!     ..WorkbenchStyle::default()
16//! });
17//! assert_eq!(style::get(&ctx).control_height(), 26.0);
18//! ```
19//!
20//! The window chrome (title bar, tab strip, status bar) keeps its fixed heights from
21//! [`crate::metrics`]: it matches the platform's window decorations and the hit areas
22//! of the window controls. Its radii, borders, and text still follow the style.
23//!
24//! Components never hard-code a radius, border width, or font size: they ask the
25//! style ([`WorkbenchStyle::item`], [`WorkbenchStyle::border`],
26//! [`WorkbenchStyle::font`], …). `cargo xtask check` rejects literal radii and font
27//! sizes outside this module, so a custom style reaches every pixel.
28
29use egui::{Color32, Context, CornerRadius, FontId, Id, Stroke, TextStyle, Vec2};
30
31use crate::components::Size;
32use crate::foundation::metrics;
33
34/// How much vertical room controls and rows take.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum Density {
37    /// About 15 % tighter: data-heavy tools.
38    Compact,
39    /// The reference sizes in [`crate::metrics`].
40    #[default]
41    Default,
42    /// About 15 % roomier: touch screens and presentation.
43    Comfortable,
44}
45
46impl Density {
47    /// The factor applied to heights and vertical padding.
48    pub const fn factor(self) -> f32 {
49        match self {
50            Self::Compact => 0.86,
51            Self::Default => 1.0,
52            Self::Comfortable => 1.16,
53        }
54    }
55
56    /// Every density, from tight to roomy.
57    pub const ALL: [Self; 3] = [Self::Compact, Self::Default, Self::Comfortable];
58
59    /// A stable value for settings files.
60    pub const fn as_setting(self) -> &'static str {
61        match self {
62            Self::Compact => "compact",
63            Self::Default => "default",
64            Self::Comfortable => "comfortable",
65        }
66    }
67
68    /// Parse [`Self::as_setting`]; unknown values give [`Density::Default`].
69    pub fn from_setting(value: &str) -> Self {
70        match value {
71            "compact" => Self::Compact,
72            "comfortable" => Self::Comfortable,
73            _ => Self::Default,
74        }
75    }
76}
77
78/// Shape and density shared by every component.
79#[derive(Clone, Copy, Debug, PartialEq)]
80pub struct WorkbenchStyle {
81    /// Control and row heights.
82    pub density: Density,
83    /// Buttons, text fields, selects, steppers, context menus, and egui widgets.
84    pub control_radius: u8,
85    /// Hover fills of icon buttons, nav items, and segmented controls.
86    pub item_radius: u8,
87    /// Small shapes inside other shapes: menu and tree rows, checkboxes, segments,
88    /// toolbar buttons. Tiny hover targets use one point less ([`Self::tight`]).
89    pub inner_radius: u8,
90    /// Cards, popovers, legends, and egui windows.
91    pub container_radius: u8,
92    /// Modal dialogs and toasts.
93    pub dialog_radius: u8,
94    /// Capsules: badges, switches, and the title-bar search. Clamped to half the
95    /// shape's height, so the default draws full capsules at any height.
96    pub pill_radius: u8,
97    /// Borders of controls, cards, popovers, and dialogs (`0.0` removes them).
98    /// Separators and focus rings keep their own widths.
99    pub border_width: f32,
100    /// Multiplies every font size (body, buttons, menus, chrome). Clamped to
101    /// `0.75..=1.5`; heights follow the density, not the text.
102    pub text_scale: f32,
103}
104
105impl Default for WorkbenchStyle {
106    fn default() -> Self {
107        Self {
108            density: Density::Default,
109            control_radius: 6,
110            item_radius: 5,
111            inner_radius: 4,
112            container_radius: 8,
113            dialog_radius: 10,
114            pill_radius: 12,
115            border_width: 1.0,
116            text_scale: 1.0,
117        }
118    }
119}
120
121impl WorkbenchStyle {
122    /// Square corners everywhere, for a flat or "technical" look.
123    pub fn sharp() -> Self {
124        Self {
125            control_radius: 0,
126            item_radius: 0,
127            inner_radius: 0,
128            container_radius: 0,
129            dialog_radius: 0,
130            pill_radius: 2,
131            ..Self::default()
132        }
133    }
134
135    /// Larger radii for a softer look.
136    pub fn rounded() -> Self {
137        Self {
138            control_radius: 9,
139            item_radius: 7,
140            inner_radius: 5,
141            container_radius: 12,
142            dialog_radius: 14,
143            pill_radius: u8::MAX,
144            ..Self::default()
145        }
146    }
147
148    /// The same style with another density.
149    pub fn with_density(mut self, density: Density) -> Self {
150        self.density = density;
151        self
152    }
153
154    /// A reference height scaled by the density, on whole points.
155    pub fn scaled(&self, height: f32) -> f32 {
156        (height * self.density.factor()).round()
157    }
158
159    /// Height of text fields, selects, steppers, and dialog buttons.
160    pub fn control_height(&self) -> f32 {
161        self.scaled(metrics::CONTROL_HEIGHT)
162    }
163
164    /// Height of a builder button of `size`.
165    pub fn size_height(&self, size: Size) -> f32 {
166        self.scaled(size.height())
167    }
168
169    /// Button padding of `size`, vertical part scaled by the density.
170    pub fn size_padding(&self, size: Size) -> Vec2 {
171        let padding = size.padding();
172        Vec2::new(padding.x, (padding.y * self.density.factor()).round())
173    }
174
175    /// Height of a context-menu row.
176    pub fn menu_row_height(&self) -> f32 {
177        self.scaled(metrics::MENU_ROW_HEIGHT)
178    }
179
180    /// Height of a palette or keyboard-menu row.
181    pub fn list_row_height(&self) -> f32 {
182        self.scaled(metrics::LIST_ROW_HEIGHT)
183    }
184
185    /// Height of an explorer tree row.
186    pub fn tree_row_height(&self) -> f32 {
187        self.scaled(metrics::TREE_ROW_HEIGHT)
188    }
189
190    /// Corner radius of controls.
191    pub fn control(&self) -> CornerRadius {
192        CornerRadius::same(self.control_radius)
193    }
194
195    /// Corner radius of row and icon hover fills.
196    pub fn item(&self) -> CornerRadius {
197        CornerRadius::same(self.item_radius)
198    }
199
200    /// Corner radius of cards, popovers, and menus.
201    pub fn container(&self) -> CornerRadius {
202        CornerRadius::same(self.container_radius)
203    }
204
205    /// Corner radius of dialogs and toasts.
206    pub fn dialog(&self) -> CornerRadius {
207        CornerRadius::same(self.dialog_radius)
208    }
209
210    /// Corner radius of shapes nested in other shapes (menu rows, checkboxes).
211    pub fn inner(&self) -> CornerRadius {
212        CornerRadius::same(self.inner_radius)
213    }
214
215    /// One point under [`Self::inner`]: tiny hover targets such as a tab's close
216    /// button or a stepper arrow.
217    pub fn tight(&self) -> CornerRadius {
218        CornerRadius::same(self.inner_radius.saturating_sub(1))
219    }
220
221    /// Indicator bars and underlines (1 pt, square in a sharp style).
222    pub fn mark(&self) -> CornerRadius {
223        CornerRadius::same(self.inner_radius.min(1))
224    }
225
226    /// Corner radius of a capsule `height` points tall.
227    pub fn pill(&self, height: f32) -> CornerRadius {
228        let half = (height / 2.0).round().clamp(0.0, 255.0) as u8;
229        CornerRadius::same(self.pill_radius.min(half))
230    }
231
232    /// A border of the style's width.
233    pub fn border(&self, color: Color32) -> Stroke {
234        Stroke::new(self.border_width.max(0.0), color)
235    }
236
237    /// The effective text scale.
238    pub fn text_scale(&self) -> f32 {
239        if self.text_scale.is_finite() {
240            self.text_scale.clamp(0.75, 1.5)
241        } else {
242            1.0
243        }
244    }
245
246    /// A reference font size (in points) scaled by [`Self::text_scale`].
247    pub fn font_size(&self, points: f32) -> f32 {
248        points * self.text_scale()
249    }
250
251    /// The proportional font of a reference size.
252    pub fn font(&self, points: f32) -> FontId {
253        FontId::proportional(self.font_size(points))
254    }
255
256    /// The monospace font of a reference size.
257    pub fn mono(&self, points: f32) -> FontId {
258        FontId::monospace(self.font_size(points))
259    }
260
261    /// The label size of a builder [`Size`].
262    pub fn text(&self, size: Size) -> f32 {
263        self.font_size(size.text())
264    }
265}
266
267/// The reference type scale installed into egui's text styles (before
268/// [`WorkbenchStyle::text_scale`]).
269pub const TYPE_SCALE: [(TextStyle, f32); 5] = [
270    (TextStyle::Body, 14.0),
271    (TextStyle::Button, 12.5),
272    (TextStyle::Small, 11.0),
273    (TextStyle::Monospace, 13.0),
274    (TextStyle::Heading, 20.0),
275];
276
277fn key() -> Id {
278    Id::unique("crisol::style")
279}
280
281/// The installed style (the default when none was set).
282pub fn get(ctx: &Context) -> WorkbenchStyle {
283    ctx.data(|data| data.get_temp::<WorkbenchStyle>(key()))
284        .unwrap_or_default()
285}
286
287/// Install a style and update egui's own widgets (radius, interact height) to match.
288/// Themes applied later keep it.
289pub fn set(ctx: &Context, style: WorkbenchStyle) {
290    ctx.data_mut(|data| data.insert_temp(key(), style));
291    apply_to_egui(ctx, &style);
292}
293
294/// Copy the shape and type scale into egui's styles; called by [`set`] and after
295/// every theme change.
296pub(crate) fn apply_to_egui(ctx: &Context, style: &WorkbenchStyle) {
297    let radius = style.control();
298    let border = style.border_width.max(0.0);
299    ctx.all_styles_mut(|egui_style| {
300        let widgets = &mut egui_style.visuals.widgets;
301        for state in [
302            &mut widgets.noninteractive,
303            &mut widgets.inactive,
304            &mut widgets.hovered,
305            &mut widgets.active,
306            &mut widgets.open,
307        ] {
308            state.corner_radius = radius;
309        }
310        // Borders follow the style; the 2 pt focus ring of the active state stays.
311        for state in [&mut widgets.noninteractive, &mut widgets.inactive, &mut widgets.hovered] {
312            state.bg_stroke.width = border;
313        }
314        egui_style.visuals.window_stroke.width = border;
315        egui_style.visuals.window_corner_radius = style.container();
316        egui_style.visuals.menu_corner_radius = style.control();
317        egui_style.spacing.interact_size.y = style.scaled(24.0);
318        egui_style.spacing.button_padding.y = style.scaled(3.0);
319        for (text_style, points) in TYPE_SCALE {
320            let font = if text_style == TextStyle::Monospace {
321                style.mono(points)
322            } else {
323                style.font(points)
324            };
325            egui_style.text_styles.insert(text_style, font);
326        }
327    });
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn the_default_style_reproduces_the_metrics() {
336        let style = WorkbenchStyle::default();
337        assert_eq!(style.control_height(), metrics::CONTROL_HEIGHT);
338        assert_eq!(style.menu_row_height(), metrics::MENU_ROW_HEIGHT);
339        assert_eq!(style.list_row_height(), metrics::LIST_ROW_HEIGHT);
340        assert_eq!(style.tree_row_height(), metrics::TREE_ROW_HEIGHT);
341        for size in [Size::Sm, Size::Md, Size::Lg] {
342            assert_eq!(style.size_height(size), size.height());
343            assert_eq!(style.size_padding(size), size.padding());
344        }
345    }
346
347    #[test]
348    fn capsules_clamp_to_half_the_height() {
349        let style = WorkbenchStyle::default();
350        assert_eq!(style.pill(20.0), CornerRadius::same(10));
351        assert_eq!(style.pill(24.0), CornerRadius::same(12));
352        assert_eq!(WorkbenchStyle::sharp().pill(24.0), CornerRadius::same(2));
353        assert_eq!(WorkbenchStyle::rounded().pill(30.0), CornerRadius::same(15));
354    }
355
356    #[test]
357    fn the_text_scale_reaches_egui_and_is_clamped() {
358        let ctx = Context::default();
359        set(
360            &ctx,
361            WorkbenchStyle {
362                text_scale: 1.2,
363                border_width: 0.0,
364                ..WorkbenchStyle::default()
365            },
366        );
367        let style = ctx.style_of(egui::Theme::Light);
368        assert_eq!(style.text_styles[&TextStyle::Body].size, 14.0 * 1.2);
369        assert_eq!(style.visuals.widgets.inactive.bg_stroke.width, 0.0);
370        let huge = WorkbenchStyle {
371            text_scale: 9.0,
372            ..WorkbenchStyle::default()
373        };
374        assert_eq!(huge.font_size(10.0), 15.0);
375    }
376
377    #[test]
378    fn densities_order_the_heights() {
379        let heights: Vec<f32> = Density::ALL
380            .iter()
381            .map(|density| WorkbenchStyle::default().with_density(*density).control_height())
382            .collect();
383        assert!(heights[0] < heights[1] && heights[1] < heights[2], "{heights:?}");
384        for density in Density::ALL {
385            assert_eq!(Density::from_setting(density.as_setting()), density);
386        }
387    }
388
389    #[test]
390    fn the_style_survives_in_the_context_and_reaches_egui() {
391        let ctx = Context::default();
392        set(&ctx, WorkbenchStyle::sharp());
393        assert_eq!(get(&ctx).control_radius, 0);
394        assert_eq!(
395            ctx.style_of(egui::Theme::Light).visuals.widgets.inactive.corner_radius,
396            CornerRadius::ZERO
397        );
398    }
399}