Skip to main content

vtcode_ui/theme/
ui_palette.rs

1//! Shared UI palette tokens derived from the CLI theme registry.
2//!
3//! [`builtin_theme_colors`] is the consumer API: the desktop app (and any
4//! other UI consumer) renders these colors, which run through the same
5//! accessible style pipeline as the TUI. The [`gpui_kit_theme_colors`] family
6//! instead exposes the raw upstream spec rows and exists to verify the port
7//! (scheme agreement, upstream hue pins); for curated themes (Catppuccin,
8//! Gruvbox, Solarized) the registry intentionally overrides the spec rows, so
9//! the two answers differ there by design.
10
11use anstyle::{Color, RgbColor};
12use vtcode_config::constants::ui;
13
14/// Minimum canvas contrast for desktop-ready foreground text. Well above the
15/// 7:1 `muted_text` target so a secondary tier stays distinct on raised fills;
16/// reachable by every built-in palette, with a pure-neutral fallback where a
17/// mid-gray background cannot get there.
18pub(super) const TEXT_HEADROOM_RATIO: f32 = 12.0;
19
20use crate::theme::color_math::{aa_muted_text, contrast_ratio, filled_text, mix, relative_luminance};
21use crate::theme::gpui_kit::{UiThemePalette, UiThemeSpec, theme_specs};
22use crate::theme::registry::theme_definition;
23use crate::theme::types::ColorAccessibilityConfig;
24
25/// Semantic palette colors for one theme, ready for RGB/HSLA consumers.
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct UiThemeColors {
28    pub background: RgbColor,
29    pub foreground: RgbColor,
30    /// Brand accent: primary buttons, badges, focus rings.
31    pub accent: RgbColor,
32    /// Quieter companion accent for secondary highlights.
33    pub secondary: RgbColor,
34    pub danger: RgbColor,
35    pub warning: RgbColor,
36    pub info: RgbColor,
37    pub success: RgbColor,
38    /// Muted text that still clears the WCAG AA floor.
39    pub muted: RgbColor,
40    /// Nearest readable text color on a filled accent surface.
41    pub accent_contrast: RgbColor,
42}
43
44/// The six ANSI hue slots carried by every VT Code theme.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct UiAnsiSlots {
47    pub red: RgbColor,
48    pub green: RgbColor,
49    pub yellow: RgbColor,
50    pub blue: RgbColor,
51    pub magenta: RgbColor,
52    pub cyan: RgbColor,
53}
54
55/// Pack an RGB color as `0xRRGGBB`, the form GPUI/theme pickers consume.
56pub const fn rgb_u32(color: RgbColor) -> u32 {
57    (color.0 as u32) << 16 | (color.1 as u32) << 8 | color.2 as u32
58}
59
60/// Whether a theme id belongs to the upstream gpui-kit theme sets.
61pub fn is_gpui_kit_theme(theme_id: &str) -> bool {
62    find_spec(theme_id).is_some()
63}
64
65/// Display label of a gpui-kit theme id, for pickers and docs.
66pub fn gpui_kit_theme_label(theme_id: &str) -> Option<&'static str> {
67    find_spec(theme_id).map(|spec| spec.label)
68}
69
70/// Derive the raw upstream palette tokens for a gpui-kit theme id.
71/// Port-verification oracle only; UI consumers must use
72/// [`builtin_theme_colors`], which reflects the curated registry entries.
73pub fn gpui_kit_theme_colors(theme_id: &str) -> Option<UiThemeColors> {
74    find_spec(theme_id).map(|spec| colors_for(&spec.palette))
75}
76
77/// Every gpui-kit theme as `(id, dark, colors)`, in upstream order.
78/// Port-verification oracle only; see [`gpui_kit_theme_colors`].
79pub fn gpui_kit_theme_colors_all() -> impl Iterator<Item = (&'static str, bool, UiThemeColors)> {
80    theme_specs().iter().map(|spec| (spec.id, spec.dark, colors_for(&spec.palette)))
81}
82
83/// Shared desktop-ready colors for any built-in CLI theme.
84/// Uses the CLI registry and the same accessible text and semantic styles as the TUI.
85pub fn builtin_theme_colors(theme_id: &str) -> Option<UiThemeColors> {
86    let palette = &theme_definition(theme_id)?.palette;
87    let styles = palette.build_styles_with_accessibility(&ColorAccessibilityConfig::default());
88    let rgb = |color: Option<Color>, fallback: RgbColor| match color {
89        Some(Color::Rgb(color)) => color,
90        _ => fallback,
91    };
92    let original_foreground = rgb(Some(styles.foreground), palette.foreground);
93    // Desktop text needs the same crisp, high-headroom reading as the Noir
94    // palette on every theme. `muted_text` targets 7:1 on the raised popover
95    // fill, so an original foreground sitting at ~7:1 on the canvas leaves no
96    // room for a distinct muted tier and the whole page reads as one muddy
97    // tone. Move toward the contrast-strongest neutral (black on light
98    // backgrounds, white on dark) until the text clears TEXT_HEADROOM_RATIO
99    // on its own background, keeping as much of the palette hue as that floor
100    // allows. Themes whose background cannot reach the floor (e.g. mid-grays)
101    // fall back to the pure neutral, the best contrast their ground permits.
102    let black = RgbColor(0, 0, 0);
103    let white = RgbColor(255, 255, 255);
104    let target = if contrast_ratio(black, palette.background) > contrast_ratio(white, palette.background) {
105        black
106    } else {
107        white
108    };
109    let foreground = (0..=100)
110        .map(|step| mix(original_foreground, target, step as f32 / 100.0))
111        .find(|color| contrast_ratio(*color, palette.background) >= TEXT_HEADROOM_RATIO)
112        .unwrap_or(target);
113    let accent = rgb(styles.mcp.get_fg_color(), foreground);
114    Some(UiThemeColors {
115        background: palette.background,
116        foreground,
117        accent,
118        secondary: rgb(styles.secondary.get_fg_color(), foreground),
119        danger: rgb(styles.error.get_fg_color(), foreground),
120        warning: rgb(styles.warning.get_fg_color(), foreground),
121        info: rgb(styles.info.get_fg_color(), foreground),
122        success: if relative_luminance(palette.background) > 0.5 {
123            RgbColor(0x23, 0x7a, 0x45)
124        } else {
125            RgbColor(0x63, 0xc7, 0x79)
126        },
127        muted: aa_muted_text(palette.background, foreground),
128        accent_contrast: filled_text(accent),
129    })
130}
131
132fn find_spec(theme_id: &str) -> Option<&'static UiThemeSpec> {
133    let trimmed = theme_id.trim();
134    theme_specs().iter().find(|spec| spec.id.eq_ignore_ascii_case(trimmed))
135}
136
137fn colors_for(palette: &UiThemePalette) -> UiThemeColors {
138    let accent = pick_accent(&[palette.accent], palette);
139    UiThemeColors {
140        background: palette.background,
141        foreground: palette.foreground,
142        accent,
143        secondary: pick_accent(&[palette.magenta, palette.cyan, palette.blue], palette),
144        danger: pick_accent(&[palette.red], palette),
145        warning: warning_for(palette),
146        info: pick_accent(&[palette.blue, palette.cyan], palette),
147        success: pick_accent(&[palette.green], palette),
148        muted: aa_muted_text(palette.background, palette.foreground),
149        accent_contrast: filled_text(accent),
150    }
151}
152
153/// Keep the intended hue: first candidate that clears the configured contrast
154/// floor wins; otherwise the most readable candidate (the shared style
155/// pipeline then re-applies the floor with the foreground as fallback).
156fn pick_accent(candidates: &[RgbColor], palette: &UiThemePalette) -> RgbColor {
157    let floor = ui::THEME_MIN_CONTRAST_RATIO;
158    if let Some(&readable) = candidates.iter().find(|&&c| contrast_ratio(c, palette.background) >= floor) {
159        return readable;
160    }
161    candidates
162        .iter()
163        .copied()
164        .reduce(|best, candidate| {
165            if contrast_ratio(candidate, palette.background) > contrast_ratio(best, palette.background) {
166                candidate
167            } else {
168                best
169            }
170        })
171        .unwrap_or(palette.foreground)
172}
173
174/// Warning keeps the dedicated amber semantics the CLI token uses, falling
175/// back to the theme yellow and then the default amber before readability.
176fn warning_for(palette: &UiThemePalette) -> RgbColor {
177    const AMBER: RgbColor = RgbColor(0xD9, 0x9A, 0x4E);
178    const DARK_AMBER: RgbColor = RgbColor(0x98, 0x63, 0x11);
179    let (candidate, alternate) = if relative_luminance(palette.background) < 0.5 {
180        (AMBER, DARK_AMBER)
181    } else {
182        (DARK_AMBER, AMBER)
183    };
184    pick_accent(&[candidate, alternate, palette.yellow], palette)
185}