use std::sync::LazyLock;
use super::style::AdaptiveColor;
use crate::{JsonValue, style::Color, tailwind};
macro_rules! theme_colors {
($( $(#[doc = $doc:literal])* $field:ident = $key:literal $(| $alias:literal)* ),* $(,)?) => {
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct ThemeColors {
$( $(#[doc = $doc])* pub $field: AdaptiveColor, )*
}
impl ThemeColors {
fn by_key(&mut self, key: &str) -> Option<&mut AdaptiveColor> {
Some(match key {
$( $key $(| $alias)* => &mut self.$field, )*
_ => return None,
})
}
}
};
}
theme_colors! {
accent = "accent.background",
accent_foreground = "accent.foreground",
background = "background",
foreground = "foreground",
border = "border",
caret = "caret",
danger = "danger.background",
danger_active = "danger.active.background",
danger_foreground = "danger.foreground",
group_box = "group_box.background",
group_box_foreground = "group_box.foreground",
info = "info.background",
info_active = "info.active.background",
info_foreground = "info.foreground",
input = "input.border",
link = "link" | "link.foreground",
link_active = "link.active" | "link.active.foreground",
list = "list.background",
list_active = "list.active.background",
list_active_border = "list.active.border",
list_even = "list.even.background",
list_head = "list.head.background",
muted = "muted.background",
muted_foreground = "muted.foreground",
overlay = "overlay",
popover = "popover.background",
popover_foreground = "popover.foreground",
primary = "primary.background",
primary_active = "primary.active.background",
primary_foreground = "primary.foreground",
progress_bar = "progress.bar.background" | "progress_bar.background",
ring = "ring",
secondary = "secondary.background",
secondary_active = "secondary.active.background",
secondary_foreground = "secondary.foreground",
selection = "selection.background",
skeleton = "skeleton.background",
slider_bar = "slider.background" | "slider.bar.background",
slider_thumb = "slider.thumb.background",
success = "success.background",
success_active = "success.active.background",
success_foreground = "success.foreground",
switch = "switch.background",
switch_thumb = "switch.thumb.background",
tab = "tab.background",
tab_active = "tab.active.background",
tab_active_foreground = "tab.active.foreground",
tab_bar = "tab_bar.background",
tab_bar_segmented = "tab_bar.segmented.background",
tab_foreground = "tab.foreground",
warning = "warning.background",
warning_active = "warning.active.background",
warning_foreground = "warning.foreground",
}
#[derive(Debug, Clone, PartialEq)]
pub struct Theme {
pub colors: ThemeColors,
pub radius: f32,
pub radius_lg: f32,
pub font_size: f32,
}
impl std::ops::Deref for Theme {
type Target = ThemeColors;
fn deref(&self) -> &ThemeColors {
&self.colors
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ThemeError(pub String);
impl std::fmt::Display for ThemeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for ThemeError {}
static DEFAULT: LazyLock<Theme> = LazyLock::new(|| {
let mut theme = Theme {
colors: ThemeColors::default(),
radius: 0.0,
radius_lg: 0.0,
font_size: 0.0,
};
theme
.apply(include_str!("default-theme.json"))
.expect("the default theme parses");
theme
});
impl Default for Theme {
fn default() -> Self {
DEFAULT.clone()
}
}
fn color(value: &JsonValue) -> Option<Color> {
let s = value.as_str()?;
Color::parse(s).or_else(|| PALETTE.colors.get(s).copied())
}
type Field = fn(&mut ThemeColors) -> &mut AdaptiveColor;
static PRESSED: &[(&str, &str, Field)] = &[
("primary.background", "primary.active.background", |c| {
&mut c.primary_active
}),
("secondary.background", "secondary.active.background", |c| {
&mut c.secondary_active
}),
("danger.background", "danger.active.background", |c| {
&mut c.danger_active
}),
("info.background", "info.active.background", |c| {
&mut c.info_active
}),
("success.background", "success.active.background", |c| {
&mut c.success_active
}),
("warning.background", "warning.active.background", |c| {
&mut c.warning_active
}),
("link", "link.active", |c| &mut c.link_active),
];
fn mix(c: Color, level: u8, amount: f32) -> Color {
let channel = |shift: u32| {
let v = ((c.0 >> shift) & 0xff) as f32;
((v + (f32::from(level) - v) * amount).round() as u32) << shift
};
Color(channel(24) | channel(16) | channel(8) | c.0 & 0xff)
}
static PALETTE: LazyLock<tailwind::Theme> = LazyLock::new(tailwind::Theme::default);
impl Theme {
pub fn from_json(json: &str) -> Result<Self, ThemeError> {
let mut theme = Self::default();
theme.apply(json)?;
Ok(theme)
}
fn apply(&mut self, json: &str) -> Result<(), ThemeError> {
let value: JsonValue =
serde_json::from_str(json).map_err(|e| ThemeError(format!("not JSON: {e}")))?;
let entries = match value.get("themes") {
Some(JsonValue::Array(entries)) => entries.as_slice(),
_ => return Err(ThemeError("expected `{ \"themes\": [...] }`".into())),
};
for entry in entries {
let dark = match entry.get("mode").and_then(JsonValue::as_str) {
Some("dark") => true,
Some("light") | None => false,
Some(m) => return Err(ThemeError(format!("unknown mode `{m}`"))),
};
let number = |key: &str| entry.get(key).and_then(JsonValue::as_f64).map(|n| n as f32);
if let Some(r) = number("radius") {
self.radius = r;
}
if let Some(r) = number("radius.lg") {
self.radius_lg = r;
}
if let Some(s) = number("font.size") {
self.font_size = s;
}
let Some(JsonValue::Object(colors)) = entry.get("colors") else {
continue;
};
for (base, active, field) in PRESSED {
if colors.get(*active).is_none_or(JsonValue::is_null)
&& let Some(c) = colors.get(*base).and_then(color)
{
let field = field(&mut self.colors);
if dark {
field.dark = mix(c, 0xff, 0.12);
} else {
field.light = mix(c, 0x00, 0.12);
}
}
}
for (key, value) in colors {
let Some(field) = self.colors.by_key(key) else {
continue;
};
if value.is_null() {
continue;
}
let c = color(value)
.ok_or_else(|| ThemeError(format!("`{key}`: not a color: {value}")))?;
if dark {
field.dark = c;
} else {
field.light = c;
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ui::rgb;
#[test]
fn the_default_theme_has_every_color_in_both_modes() {
let theme = Theme::default();
assert_eq!(theme.primary.light, rgb(0x171717));
assert_eq!(theme.primary.dark, rgb(0xfafafa));
assert_eq!(
(theme.radius, theme.radius_lg, theme.font_size),
(12.0, 16.0, 16.0)
);
}
#[test]
fn a_theme_overrides_the_default_and_derives_pressed_colors() {
let theme = Theme::from_json(
r##"{ "themes": [
{ "mode": "light", "radius": 8, "colors": {
"primary.background": "#7c3aed", "border": "red-500", "sidebar.background": "#000" } },
{ "mode": "dark", "colors": { "primary.background": "#a78bfa", "primary.active.background": "#ffffff" } }
] }"##,
)
.unwrap();
assert_eq!(theme.primary.light, rgb(0x7c3aed));
assert_eq!(theme.primary_active.light, mix(rgb(0x7c3aed), 0, 0.12));
assert_eq!(theme.primary_active.dark, rgb(0xffffff));
assert_eq!(theme.border.light, PALETTE.colors["red-500"]);
assert_eq!(theme.radius, 8.0);
assert_eq!(theme.secondary, Theme::default().secondary);
assert!(Theme::from_json(r#"{ "themes": [{ "colors": { "ring": 3 } }] }"#).is_err());
}
#[test]
fn colors_a_gpui_kit_theme_leaves_unset_keep_their_value() {
let theme = Theme::from_json(
r##"{ "themes": [{ "mode": "dark", "radius": null, "colors": {
"primary.background": null, "primary.active.background": null,
"danger.background": "#ff0000", "danger.active.background": null,
"ring": "#ff0000", "sidebar.background": null } }] }"##,
)
.unwrap();
let default = Theme::default();
assert_eq!(theme.primary, default.primary);
assert_eq!(theme.primary_active, default.primary_active);
assert_eq!(theme.radius, default.radius);
assert_eq!(theme.ring.dark, rgb(0xff0000));
assert_eq!(theme.ring.light, default.ring.light);
assert_eq!(theme.danger_active.dark, mix(rgb(0xff0000), 0xff, 0.12));
}
}