Skip to main content

nsh_core/ui/
theme.rs

1//! The theme of Rust components: semantic colors with a light and a dark
2//! value, corner radii and the base font size. Field names and the JSON
3//! format follow gpui-kit's themes (`primary.background`,
4//! `primary.active.background`, ...), so a gpui-kit theme file styles the
5//! mobile components too; keys only desktop components use are ignored.
6//!
7//! The app's theme is `nsh.json`'s `"theme"`: a theme file's path or its
8//! content, `{ "themes": [{ "mode": "light", "colors": { … } }, { "mode":
9//! "dark", … }] }`, over the default (`default-theme.json`). Colors are CSS
10//! colors or Tailwind palette names (`neutral-900`).
11
12use std::sync::LazyLock;
13
14use super::style::AdaptiveColor;
15use crate::{JsonValue, style::Color, tailwind};
16
17macro_rules! theme_colors {
18    ($( $(#[doc = $doc:literal])* $field:ident = $key:literal $(| $alias:literal)* ),* $(,)?) => {
19        /// The theme's semantic colors (gpui-kit's names).
20        #[derive(Debug, Clone, Copy, PartialEq, Default)]
21        pub struct ThemeColors {
22            $( $(#[doc = $doc])* pub $field: AdaptiveColor, )*
23        }
24
25        impl ThemeColors {
26            /// The color of JSON key `key`.
27            fn by_key(&mut self, key: &str) -> Option<&mut AdaptiveColor> {
28                Some(match key {
29                    $( $key $(| $alias)* => &mut self.$field, )*
30                    _ => return None,
31                })
32            }
33        }
34    };
35}
36
37theme_colors! {
38    /// Accents: the background of a selected or highlighted item.
39    accent = "accent.background",
40    /// Text on [`Self::accent`].
41    accent_foreground = "accent.foreground",
42    /// The app's background.
43    background = "background",
44    /// Text and icons on [`Self::background`].
45    foreground = "foreground",
46    /// Borders and dividers.
47    border = "border",
48    /// The text cursor.
49    caret = "caret",
50    /// Destructive actions.
51    danger = "danger.background",
52    /// [`Self::danger`] while pressed.
53    danger_active = "danger.active.background",
54    /// Text on [`Self::danger`].
55    danger_foreground = "danger.foreground",
56    /// A contained surface: cards, grouped content.
57    group_box = "group_box.background",
58    /// Text on [`Self::group_box`].
59    group_box_foreground = "group_box.foreground",
60    /// Informational messages.
61    info = "info.background",
62    /// [`Self::info`] while pressed.
63    info_active = "info.active.background",
64    /// Text on [`Self::info`].
65    info_foreground = "info.foreground",
66    /// The border of text inputs.
67    input = "input.border",
68    /// Links.
69    link = "link" | "link.foreground",
70    /// Links while pressed.
71    link_active = "link.active" | "link.active.foreground",
72    /// The background of lists.
73    list = "list.background",
74    /// The selected row.
75    list_active = "list.active.background",
76    /// The selected row's border.
77    list_active_border = "list.active.border",
78    /// Every other row.
79    list_even = "list.even.background",
80    /// List headers.
81    list_head = "list.head.background",
82    /// Muted surfaces.
83    muted = "muted.background",
84    /// Secondary text: hints, captions, placeholders.
85    muted_foreground = "muted.foreground",
86    /// Dims what is under a sheet or a dialog.
87    overlay = "overlay",
88    /// Floating surfaces: menus, popovers, sheets.
89    popover = "popover.background",
90    /// Text on [`Self::popover`].
91    popover_foreground = "popover.foreground",
92    /// The main action.
93    primary = "primary.background",
94    /// [`Self::primary`] while pressed.
95    primary_active = "primary.active.background",
96    /// Text on [`Self::primary`].
97    primary_foreground = "primary.foreground",
98    /// The filled part of progress bars.
99    progress_bar = "progress.bar.background" | "progress_bar.background",
100    /// Focus rings.
101    ring = "ring",
102    /// Secondary actions.
103    secondary = "secondary.background",
104    /// [`Self::secondary`] while pressed.
105    secondary_active = "secondary.active.background",
106    /// Text on [`Self::secondary`].
107    secondary_foreground = "secondary.foreground",
108    /// Selected text.
109    selection = "selection.background",
110    /// Loading placeholders.
111    skeleton = "skeleton.background",
112    /// A slider's filled track.
113    slider_bar = "slider.background" | "slider.bar.background",
114    /// A slider's thumb.
115    slider_thumb = "slider.thumb.background",
116    /// Success.
117    success = "success.background",
118    /// [`Self::success`] while pressed.
119    success_active = "success.active.background",
120    /// Text on [`Self::success`].
121    success_foreground = "success.foreground",
122    /// A switch's track while off.
123    switch = "switch.background",
124    /// A switch's thumb.
125    switch_thumb = "switch.thumb.background",
126    /// A tab.
127    tab = "tab.background",
128    /// The selected tab.
129    tab_active = "tab.active.background",
130    /// The selected tab's text.
131    tab_active_foreground = "tab.active.foreground",
132    /// The bar holding tabs.
133    tab_bar = "tab_bar.background",
134    /// A segmented tab bar.
135    tab_bar_segmented = "tab_bar.segmented.background",
136    /// A tab's text.
137    tab_foreground = "tab.foreground",
138    /// Warnings.
139    warning = "warning.background",
140    /// [`Self::warning`] while pressed.
141    warning_active = "warning.active.background",
142    /// Text on [`Self::warning`].
143    warning_foreground = "warning.foreground",
144}
145
146/// The theme components render with ([`super::RenderCx::theme`]). Derefs
147/// to its colors: `theme.primary`.
148#[derive(Debug, Clone, PartialEq)]
149pub struct Theme {
150    /// The semantic colors.
151    pub colors: ThemeColors,
152    /// The corner radius of controls (buttons, inputs), in points.
153    pub radius: f32,
154    /// The corner radius of large surfaces (cards, sheets, dialogs).
155    pub radius_lg: f32,
156    /// The base font size, in points.
157    pub font_size: f32,
158}
159
160impl std::ops::Deref for Theme {
161    type Target = ThemeColors;
162
163    fn deref(&self) -> &ThemeColors {
164        &self.colors
165    }
166}
167
168/// A theme that does not parse.
169#[derive(Debug, Clone, PartialEq)]
170pub struct ThemeError(pub String);
171
172impl std::fmt::Display for ThemeError {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        f.write_str(&self.0)
175    }
176}
177
178impl std::error::Error for ThemeError {}
179
180static DEFAULT: LazyLock<Theme> = LazyLock::new(|| {
181    let mut theme = Theme {
182        colors: ThemeColors::default(),
183        radius: 0.0,
184        radius_lg: 0.0,
185        font_size: 0.0,
186    };
187    theme
188        .apply(include_str!("default-theme.json"))
189        .expect("the default theme parses");
190    theme
191});
192
193impl Default for Theme {
194    fn default() -> Self {
195        DEFAULT.clone()
196    }
197}
198
199/// A CSS color or a Tailwind palette name.
200fn color(value: &JsonValue) -> Option<Color> {
201    let s = value.as_str()?;
202    Color::parse(s).or_else(|| PALETTE.colors.get(s).copied())
203}
204
205type Field = fn(&mut ThemeColors) -> &mut AdaptiveColor;
206
207/// Base colors and their pressed variants.
208static PRESSED: &[(&str, &str, Field)] = &[
209    ("primary.background", "primary.active.background", |c| {
210        &mut c.primary_active
211    }),
212    ("secondary.background", "secondary.active.background", |c| {
213        &mut c.secondary_active
214    }),
215    ("danger.background", "danger.active.background", |c| {
216        &mut c.danger_active
217    }),
218    ("info.background", "info.active.background", |c| {
219        &mut c.info_active
220    }),
221    ("success.background", "success.active.background", |c| {
222        &mut c.success_active
223    }),
224    ("warning.background", "warning.active.background", |c| {
225        &mut c.warning_active
226    }),
227    ("link", "link.active", |c| &mut c.link_active),
228];
229
230/// `c` moved `amount` of the way to gray level `level` (alpha kept): a
231/// pressed shade, darker in light appearance, lighter in dark.
232fn mix(c: Color, level: u8, amount: f32) -> Color {
233    let channel = |shift: u32| {
234        let v = ((c.0 >> shift) & 0xff) as f32;
235        ((v + (f32::from(level) - v) * amount).round() as u32) << shift
236    };
237    Color(channel(24) | channel(16) | channel(8) | c.0 & 0xff)
238}
239
240static PALETTE: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
241
242impl Theme {
243    /// The default theme with `json` (a gpui-kit theme file's content)
244    /// over it.
245    pub fn from_json(json: &str) -> Result<Self, ThemeError> {
246        let mut theme = Self::default();
247        theme.apply(json)?;
248        Ok(theme)
249    }
250
251    /// Applies the themes of `json` over `self`: each entry's `mode` picks
252    /// the colors it sets; `radius`, `radius.lg` and `font.size` come from
253    /// any entry.
254    fn apply(&mut self, json: &str) -> Result<(), ThemeError> {
255        let value: JsonValue =
256            serde_json::from_str(json).map_err(|e| ThemeError(format!("not JSON: {e}")))?;
257        let entries = match value.get("themes") {
258            Some(JsonValue::Array(entries)) => entries.as_slice(),
259            _ => return Err(ThemeError("expected `{ \"themes\": [...] }`".into())),
260        };
261        for entry in entries {
262            let dark = match entry.get("mode").and_then(JsonValue::as_str) {
263                Some("dark") => true,
264                Some("light") | None => false,
265                Some(m) => return Err(ThemeError(format!("unknown mode `{m}`"))),
266            };
267            let number = |key: &str| entry.get(key).and_then(JsonValue::as_f64).map(|n| n as f32);
268            if let Some(r) = number("radius") {
269                self.radius = r;
270            }
271            if let Some(r) = number("radius.lg") {
272                self.radius_lg = r;
273            }
274            if let Some(s) = number("font.size") {
275                self.font_size = s;
276            }
277            let Some(JsonValue::Object(colors)) = entry.get("colors") else {
278                continue;
279            };
280            // A pressed color the theme leaves out (or null) follows its
281            // base color.
282            for (base, active, field) in PRESSED {
283                if colors.get(*active).is_none_or(JsonValue::is_null)
284                    && let Some(c) = colors.get(*base).and_then(color)
285                {
286                    let field = field(&mut self.colors);
287                    if dark {
288                        field.dark = mix(c, 0xff, 0.12);
289                    } else {
290                        field.light = mix(c, 0x00, 0.12);
291                    }
292                }
293            }
294            for (key, value) in colors {
295                // Keys of desktop components (sidebars, title bars, ...)
296                // have no field here.
297                let Some(field) = self.colors.by_key(key) else {
298                    continue;
299                };
300                // gpui-kit writes the colors a theme leaves unset as null.
301                if value.is_null() {
302                    continue;
303                }
304                let c = color(value)
305                    .ok_or_else(|| ThemeError(format!("`{key}`: not a color: {value}")))?;
306                if dark {
307                    field.dark = c;
308                } else {
309                    field.light = c;
310                }
311            }
312        }
313        Ok(())
314    }
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320    use crate::ui::rgb;
321
322    #[test]
323    fn the_default_theme_has_every_color_in_both_modes() {
324        let theme = Theme::default();
325        assert_eq!(theme.primary.light, rgb(0x171717));
326        assert_eq!(theme.primary.dark, rgb(0xfafafa));
327        assert_eq!(
328            (theme.radius, theme.radius_lg, theme.font_size),
329            (12.0, 16.0, 16.0)
330        );
331    }
332
333    #[test]
334    fn a_theme_overrides_the_default_and_derives_pressed_colors() {
335        let theme = Theme::from_json(
336            r##"{ "themes": [
337                { "mode": "light", "radius": 8, "colors": {
338                    "primary.background": "#7c3aed", "border": "red-500", "sidebar.background": "#000" } },
339                { "mode": "dark", "colors": { "primary.background": "#a78bfa", "primary.active.background": "#ffffff" } }
340            ] }"##,
341        )
342        .unwrap();
343        assert_eq!(theme.primary.light, rgb(0x7c3aed));
344        // Left out: darker in light appearance; set: as given.
345        assert_eq!(theme.primary_active.light, mix(rgb(0x7c3aed), 0, 0.12));
346        assert_eq!(theme.primary_active.dark, rgb(0xffffff));
347        // Palette names; keys only desktop components use are ignored.
348        assert_eq!(theme.border.light, PALETTE.colors["red-500"]);
349        assert_eq!(theme.radius, 8.0);
350        assert_eq!(theme.secondary, Theme::default().secondary);
351        assert!(Theme::from_json(r#"{ "themes": [{ "colors": { "ring": 3 } }] }"#).is_err());
352    }
353
354    #[test]
355    fn colors_a_gpui_kit_theme_leaves_unset_keep_their_value() {
356        // gpui-kit serializes unset colors (and numbers) as null.
357        let theme = Theme::from_json(
358            r##"{ "themes": [{ "mode": "dark", "radius": null, "colors": {
359                "primary.background": null, "primary.active.background": null,
360                "danger.background": "#ff0000", "danger.active.background": null,
361                "ring": "#ff0000", "sidebar.background": null } }] }"##,
362        )
363        .unwrap();
364        let default = Theme::default();
365        assert_eq!(theme.primary, default.primary);
366        assert_eq!(theme.primary_active, default.primary_active);
367        assert_eq!(theme.radius, default.radius);
368        assert_eq!(theme.ring.dark, rgb(0xff0000));
369        assert_eq!(theme.ring.light, default.ring.light);
370        // A null pressed color follows its base color.
371        assert_eq!(theme.danger_active.dark, mix(rgb(0xff0000), 0xff, 0.12));
372    }
373}