Skip to main content

gpui_component/theme/
color.rs

1use std::{collections::HashMap, fmt::Display};
2
3use gpui::{
4    Background, Hsla, LinearColorStop, SharedString, hsla, linear_color_stop, linear_gradient,
5};
6use serde::{Deserialize, Deserializer, de::Error as _};
7
8use anyhow::{Error, Result, anyhow};
9
10/// Create a [`gpui::Hsla`] color.
11///
12/// - h: 0..360.0
13/// - s: 0.0..100.0
14/// - l: 0.0..100.0
15#[inline]
16pub fn hsl(h: f32, s: f32, l: f32) -> Hsla {
17    hsla(h / 360., s / 100.0, l / 100.0, 1.0)
18}
19
20pub trait Colorize: Sized {
21    /// Returns a new color with the given opacity.
22    ///
23    /// The opacity is a value between 0.0 and 1.0, where 0.0 is fully transparent and 1.0 is fully opaque.
24    fn opacity(&self, opacity: f32) -> Self;
25    /// Returns a new color with each channel divided by the given divisor.
26    ///
27    /// The divisor in range of 0.0 .. 1.0
28    fn divide(&self, divisor: f32) -> Self;
29    /// Return inverted color
30    fn invert(&self) -> Self;
31    /// Return inverted lightness
32    fn invert_l(&self) -> Self;
33    /// Return a new color with the lightness increased by the given factor.
34    ///
35    /// factor range: 0.0 .. 1.0
36    fn lighten(&self, amount: f32) -> Self;
37    /// Return a new color with the darkness increased by the given factor.
38    ///
39    /// factor range: 0.0 .. 1.0
40    fn darken(&self, amount: f32) -> Self;
41    /// Return a new color with the same lightness and alpha but different hue and saturation.
42    fn apply(&self, base_color: Self) -> Self;
43
44    /// Mix two colors together, the `factor` is a value between 0.0 and 1.0 for first color.
45    fn mix(&self, other: Self, factor: f32) -> Self;
46    /// Mix two colors together in Oklab color space, the `factor` is a value between 0.0 and 1.0 for first color.
47    ///
48    /// This is similar to CSS `color-mix(in oklab, color1 factor%, color2)`.
49    fn mix_oklab(&self, other: Self, factor: f32) -> Self;
50    /// Change the `Hue` of the color by the given in range: 0.0 .. 1.0
51    fn hue(&self, hue: f32) -> Self;
52    /// Change the `Saturation` of the color by the given value in range: 0.0 .. 1.0
53    fn saturation(&self, saturation: f32) -> Self;
54    /// Change the `Lightness` of the color by the given value in range: 0.0 .. 1.0
55    fn lightness(&self, lightness: f32) -> Self;
56
57    /// Convert the color to a hex string. For example, "#F8FAFC".
58    fn to_hex(&self) -> String;
59    /// Parse a hex string to a color.
60    fn parse_hex(hex: &str) -> Result<Self>;
61}
62
63/// Helper functions for Oklab color space conversions
64mod oklab {
65    use gpui::Rgba;
66
67    /// Convert sRGB component to linear RGB
68    #[inline]
69    fn to_linear(c: f32) -> f32 {
70        if c <= 0.04045 {
71            c / 12.92
72        } else {
73            ((c + 0.055) / 1.055).powf(2.4)
74        }
75    }
76
77    /// Convert linear RGB component to sRGB
78    #[inline]
79    fn from_linear(c: f32) -> f32 {
80        if c <= 0.0031308 {
81            c * 12.92
82        } else {
83            1.055 * c.powf(1.0 / 2.4) - 0.055
84        }
85    }
86
87    /// Convert RGB to Oklab color space
88    #[allow(non_snake_case)]
89    pub fn rgb_to_oklab(rgb: Rgba) -> (f32, f32, f32) {
90        // sRGB to linear RGB
91        let lr = to_linear(rgb.r);
92        let lg = to_linear(rgb.g);
93        let lb = to_linear(rgb.b);
94
95        // Linear RGB to LMS
96        let l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb;
97        let m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb;
98        let s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb;
99
100        // LMS to Oklab (using cube root)
101        let l_ = l.cbrt();
102        let m_ = m.cbrt();
103        let s_ = s.cbrt();
104
105        let L = 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_;
106        let a = 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_;
107        let b = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_;
108
109        (L, a, b)
110    }
111
112    /// Convert Oklab to RGB color space
113    #[allow(non_snake_case)]
114    pub fn oklab_to_rgb(L: f32, a: f32, b: f32) -> Rgba {
115        // Oklab to LMS
116        let l_ = L + 0.3963377774 * a + 0.2158037573 * b;
117        let m_ = L - 0.1055613458 * a - 0.0638541728 * b;
118        let s_ = L - 0.0894841775 * a - 1.2914855480 * b;
119
120        let l = l_ * l_ * l_;
121        let m = m_ * m_ * m_;
122        let s = s_ * s_ * s_;
123
124        // LMS to Linear RGB
125        let lr = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;
126        let lg = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;
127        let lb = -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s;
128
129        // Linear RGB to sRGB
130        Rgba {
131            r: from_linear(lr).clamp(0.0, 1.0),
132            g: from_linear(lg).clamp(0.0, 1.0),
133            b: from_linear(lb).clamp(0.0, 1.0),
134            a: 1.0,
135        }
136    }
137}
138
139/// Builds a color from OkLCH, the cylindrical form of the perceptually uniform
140/// Oklab color space.
141///
142/// Unlike HSL, rotating `hue` while holding `lightness` and `chroma` keeps the
143/// perceived brightness and vividness of every hue equal, so a generated color
144/// ring reads as one family instead of a raw rainbow.
145///
146/// `lightness` is `0.0 .. 1.0`, `chroma` is an absolute Oklab distance
147/// (roughly `0.0 .. 0.37`), and `hue` is in degrees. A request outside the sRGB
148/// gamut is clipped per channel, which costs a little chroma but not the hue.
149pub fn oklch(lightness: f32, chroma: f32, hue: f32) -> Hsla {
150    let hue = hue.to_radians();
151    let rgb = oklab::oklab_to_rgb(lightness, chroma * hue.cos(), chroma * hue.sin());
152    rgb.into()
153}
154
155impl Colorize for Hsla {
156    fn opacity(&self, factor: f32) -> Self {
157        Self {
158            a: self.a * factor.clamp(0.0, 1.0),
159            ..*self
160        }
161    }
162
163    fn divide(&self, divisor: f32) -> Self {
164        Self {
165            a: divisor,
166            ..*self
167        }
168    }
169
170    fn invert(&self) -> Self {
171        Self {
172            h: 1.0 - self.h,
173            s: 1.0 - self.s,
174            l: 1.0 - self.l,
175            a: self.a,
176        }
177    }
178
179    fn invert_l(&self) -> Self {
180        Self {
181            l: 1.0 - self.l,
182            ..*self
183        }
184    }
185
186    fn lighten(&self, factor: f32) -> Self {
187        let l = self.l * (1.0 + factor.clamp(0.0, 1.0));
188
189        Hsla { l, ..*self }
190    }
191
192    fn darken(&self, factor: f32) -> Self {
193        let l = self.l * (1.0 - factor.clamp(0.0, 1.0));
194
195        Self { l, ..*self }
196    }
197
198    fn apply(&self, new_color: Self) -> Self {
199        Hsla {
200            h: new_color.h,
201            s: new_color.s,
202            l: self.l,
203            a: self.a,
204        }
205    }
206
207    /// Reference:
208    /// https://github.com/bevyengine/bevy/blob/85eceb022da0326b47ac2b0d9202c9c9f01835bb/crates/bevy_color/src/hsla.rs#L112
209    fn mix(&self, other: Self, factor: f32) -> Self {
210        let factor = factor.clamp(0.0, 1.0);
211        let inv = 1.0 - factor;
212
213        #[inline]
214        fn lerp_hue(a: f32, b: f32, t: f32) -> f32 {
215            let diff = (b - a + 180.0).rem_euclid(360.) - 180.;
216            (a + diff * t).rem_euclid(360.0)
217        }
218
219        Hsla {
220            h: lerp_hue(self.h * 360., other.h * 360., factor) / 360.,
221            s: self.s * factor + other.s * inv,
222            l: self.l * factor + other.l * inv,
223            a: self.a * factor + other.a * inv,
224        }
225    }
226
227    #[allow(non_snake_case)]
228    fn mix_oklab(&self, other: Self, factor: f32) -> Self {
229        let factor = factor.clamp(0.0, 1.0);
230        let inv = 1.0 - factor;
231
232        // Interpolate alpha first
233        let result_alpha = self.a * factor + other.a * inv;
234
235        // Handle the case where result alpha is zero
236        if result_alpha == 0.0 {
237            return Self {
238                h: 0.0,
239                s: 0.0,
240                l: 0.0,
241                a: 0.0,
242            };
243        }
244
245        // Convert both colors to RGB
246        let rgb1 = self.to_rgb();
247        let rgb2 = other.to_rgb();
248
249        // Convert to Oklab color space
250        let (l1, a1, b1) = oklab::rgb_to_oklab(rgb1);
251        let (l2, a2, b2) = oklab::rgb_to_oklab(rgb2);
252
253        // Premultiply alpha in Oklab space (using alpha-premultiplied interpolation)
254        // This matches CSS color-mix behavior
255        let alpha1 = self.a;
256        let alpha2 = other.a;
257
258        // Premultiply
259        let l1_pm = l1 * alpha1;
260        let a1_pm = a1 * alpha1;
261        let b1_pm = b1 * alpha1;
262
263        let l2_pm = l2 * alpha2;
264        let a2_pm = a2 * alpha2;
265        let b2_pm = b2 * alpha2;
266
267        // Interpolate premultiplied values
268        let L_pm = l1_pm * factor + l2_pm * inv;
269        let a_pm = a1_pm * factor + a2_pm * inv;
270        let b_pm = b1_pm * factor + b2_pm * inv;
271
272        // Unpremultiply
273        let L = L_pm / result_alpha;
274        let a = a_pm / result_alpha;
275        let b = b_pm / result_alpha;
276
277        // Convert back to RGB
278        let mut rgb = oklab::oklab_to_rgb(L, a, b);
279        rgb.a = result_alpha;
280
281        // Convert RGB to HSLA
282        rgb.into()
283    }
284
285    fn to_hex(&self) -> String {
286        let rgb = self.to_rgb();
287
288        if rgb.a < 1. {
289            return format!(
290                "#{:02X}{:02X}{:02X}{:02X}",
291                ((rgb.r * 255.) as u32),
292                ((rgb.g * 255.) as u32),
293                ((rgb.b * 255.) as u32),
294                ((self.a * 255.) as u32)
295            );
296        }
297
298        format!(
299            "#{:02X}{:02X}{:02X}",
300            ((rgb.r * 255.) as u32),
301            ((rgb.g * 255.) as u32),
302            ((rgb.b * 255.) as u32)
303        )
304    }
305
306    fn parse_hex(hex: &str) -> Result<Self> {
307        let hex = hex.trim_start_matches('#');
308        let len = hex.len();
309        // Check the digits before slicing: a non-ASCII character would make
310        // the byte slices below panic, and `from_str_radix` accepts a sign.
311        if (len != 6 && len != 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
312            return Err(anyhow::anyhow!("invalid hex color"));
313        }
314
315        let r = u8::from_str_radix(&hex[0..2], 16)? as f32 / 255.;
316        let g = u8::from_str_radix(&hex[2..4], 16)? as f32 / 255.;
317        let b = u8::from_str_radix(&hex[4..6], 16)? as f32 / 255.;
318        let a = if len == 8 {
319            u8::from_str_radix(&hex[6..8], 16)? as f32 / 255.
320        } else {
321            1.
322        };
323
324        let v = gpui::Rgba { r, g, b, a };
325        let color: Hsla = v.into();
326        Ok(color)
327    }
328
329    fn hue(&self, hue: f32) -> Self {
330        let mut color = *self;
331        color.h = hue.clamp(0., 1.);
332        color
333    }
334
335    fn saturation(&self, saturation: f32) -> Self {
336        let mut color = *self;
337        color.s = saturation.clamp(0., 1.);
338        color
339    }
340
341    fn lightness(&self, lightness: f32) -> Self {
342        let mut color = *self;
343        color.l = lightness.clamp(0., 1.);
344        color
345    }
346}
347
348pub(crate) static DEFAULT_COLORS: once_cell::sync::Lazy<ShadcnColors> =
349    once_cell::sync::Lazy::new(|| {
350        serde_json::from_str(include_str!("./default-colors.json"))
351            .expect("failed to parse default-colors.json")
352    });
353
354type ColorScales = HashMap<usize, ShadcnColor>;
355
356mod color_scales {
357    use std::collections::HashMap;
358
359    use super::{ColorScales, ShadcnColor};
360
361    use serde::de::{Deserialize, Deserializer};
362
363    pub fn deserialize<'de, D>(deserializer: D) -> Result<ColorScales, D::Error>
364    where
365        D: Deserializer<'de>,
366    {
367        let mut map = HashMap::new();
368        for color in Vec::<ShadcnColor>::deserialize(deserializer)? {
369            map.insert(color.scale, color);
370        }
371        Ok(map)
372    }
373}
374
375/// Enum representing the available color names.
376#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
377pub enum ColorName {
378    White,
379    Black,
380    Neutral,
381    Gray,
382    Red,
383    Orange,
384    Amber,
385    Yellow,
386    Lime,
387    Green,
388    Emerald,
389    Teal,
390    Cyan,
391    Sky,
392    Blue,
393    Indigo,
394    Violet,
395    Purple,
396    Fuchsia,
397    Pink,
398    Rose,
399}
400
401impl Display for ColorName {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        write!(f, "{:?}", self)
404    }
405}
406
407// Strict color name parser.
408impl TryFrom<&str> for ColorName {
409    type Error = anyhow::Error;
410    fn try_from(value: &str) -> std::result::Result<Self, Self::Error> {
411        match value.to_lowercase().as_str() {
412            "white" => Ok(ColorName::White),
413            "black" => Ok(ColorName::Black),
414            "neutral" => Ok(ColorName::Neutral),
415            "gray" => Ok(ColorName::Gray),
416            "red" => Ok(ColorName::Red),
417            "orange" => Ok(ColorName::Orange),
418            "amber" => Ok(ColorName::Amber),
419            "yellow" => Ok(ColorName::Yellow),
420            "lime" => Ok(ColorName::Lime),
421            "green" => Ok(ColorName::Green),
422            "emerald" => Ok(ColorName::Emerald),
423            "teal" => Ok(ColorName::Teal),
424            "cyan" => Ok(ColorName::Cyan),
425            "sky" => Ok(ColorName::Sky),
426            "blue" => Ok(ColorName::Blue),
427            "indigo" => Ok(ColorName::Indigo),
428            "violet" => Ok(ColorName::Violet),
429            "purple" => Ok(ColorName::Purple),
430            "fuchsia" => Ok(ColorName::Fuchsia),
431            "pink" => Ok(ColorName::Pink),
432            "rose" => Ok(ColorName::Rose),
433            _ => Err(anyhow::anyhow!("Invalid color name")),
434        }
435    }
436}
437
438impl TryFrom<SharedString> for ColorName {
439    type Error = anyhow::Error;
440    fn try_from(value: SharedString) -> std::result::Result<Self, Self::Error> {
441        value.as_ref().try_into()
442    }
443}
444
445impl ColorName {
446    /// Returns all available color names.
447    pub fn all() -> [Self; 19] {
448        [
449            ColorName::Neutral,
450            ColorName::Gray,
451            ColorName::Red,
452            ColorName::Orange,
453            ColorName::Amber,
454            ColorName::Yellow,
455            ColorName::Lime,
456            ColorName::Green,
457            ColorName::Emerald,
458            ColorName::Teal,
459            ColorName::Cyan,
460            ColorName::Sky,
461            ColorName::Blue,
462            ColorName::Indigo,
463            ColorName::Violet,
464            ColorName::Purple,
465            ColorName::Fuchsia,
466            ColorName::Pink,
467            ColorName::Rose,
468        ]
469    }
470
471    /// Returns the color for the given scale.
472    ///
473    /// The `scale` is any of `[50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950]`
474    /// falls back to 500 if out of range.
475    pub fn scale(&self, scale: usize) -> Hsla {
476        if self == &ColorName::White {
477            return DEFAULT_COLORS.white.hsla;
478        }
479        if self == &ColorName::Black {
480            return DEFAULT_COLORS.black.hsla;
481        }
482
483        let colors = match self {
484            ColorName::Neutral => &DEFAULT_COLORS.neutral,
485            ColorName::Gray => &DEFAULT_COLORS.gray,
486            ColorName::Red => &DEFAULT_COLORS.red,
487            ColorName::Orange => &DEFAULT_COLORS.orange,
488            ColorName::Amber => &DEFAULT_COLORS.amber,
489            ColorName::Yellow => &DEFAULT_COLORS.yellow,
490            ColorName::Lime => &DEFAULT_COLORS.lime,
491            ColorName::Green => &DEFAULT_COLORS.green,
492            ColorName::Emerald => &DEFAULT_COLORS.emerald,
493            ColorName::Teal => &DEFAULT_COLORS.teal,
494            ColorName::Cyan => &DEFAULT_COLORS.cyan,
495            ColorName::Sky => &DEFAULT_COLORS.sky,
496            ColorName::Blue => &DEFAULT_COLORS.blue,
497            ColorName::Indigo => &DEFAULT_COLORS.indigo,
498            ColorName::Violet => &DEFAULT_COLORS.violet,
499            ColorName::Purple => &DEFAULT_COLORS.purple,
500            ColorName::Fuchsia => &DEFAULT_COLORS.fuchsia,
501            ColorName::Pink => &DEFAULT_COLORS.pink,
502            ColorName::Rose => &DEFAULT_COLORS.rose,
503            _ => unreachable!(),
504        };
505
506        if let Some(color) = colors.get(&scale) {
507            color.hsla
508        } else {
509            colors.get(&500).unwrap().hsla
510        }
511    }
512}
513
514#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)]
515pub(crate) struct ShadcnColors {
516    pub(crate) black: ShadcnColor,
517    pub(crate) white: ShadcnColor,
518    #[serde(with = "color_scales")]
519    pub(crate) slate: ColorScales,
520    #[serde(with = "color_scales")]
521    pub(crate) gray: ColorScales,
522    #[serde(with = "color_scales")]
523    pub(crate) zinc: ColorScales,
524    #[serde(with = "color_scales")]
525    pub(crate) neutral: ColorScales,
526    #[serde(with = "color_scales")]
527    pub(crate) stone: ColorScales,
528    #[serde(with = "color_scales")]
529    pub(crate) red: ColorScales,
530    #[serde(with = "color_scales")]
531    pub(crate) orange: ColorScales,
532    #[serde(with = "color_scales")]
533    pub(crate) amber: ColorScales,
534    #[serde(with = "color_scales")]
535    pub(crate) yellow: ColorScales,
536    #[serde(with = "color_scales")]
537    pub(crate) lime: ColorScales,
538    #[serde(with = "color_scales")]
539    pub(crate) green: ColorScales,
540    #[serde(with = "color_scales")]
541    pub(crate) emerald: ColorScales,
542    #[serde(with = "color_scales")]
543    pub(crate) teal: ColorScales,
544    #[serde(with = "color_scales")]
545    pub(crate) cyan: ColorScales,
546    #[serde(with = "color_scales")]
547    pub(crate) sky: ColorScales,
548    #[serde(with = "color_scales")]
549    pub(crate) blue: ColorScales,
550    #[serde(with = "color_scales")]
551    pub(crate) indigo: ColorScales,
552    #[serde(with = "color_scales")]
553    pub(crate) violet: ColorScales,
554    #[serde(with = "color_scales")]
555    pub(crate) purple: ColorScales,
556    #[serde(with = "color_scales")]
557    pub(crate) fuchsia: ColorScales,
558    #[serde(with = "color_scales")]
559    pub(crate) pink: ColorScales,
560    #[serde(with = "color_scales")]
561    pub(crate) rose: ColorScales,
562}
563
564#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Deserialize)]
565pub(crate) struct ShadcnColor {
566    #[serde(default)]
567    pub(crate) scale: usize,
568    #[serde(deserialize_with = "from_hsl_channel", alias = "hslChannel")]
569    pub(crate) hsla: Hsla,
570}
571
572/// Deserialize Hsla from a string in the format "210 40% 98%"
573fn from_hsl_channel<'de, D>(deserializer: D) -> Result<Hsla, D::Error>
574where
575    D: Deserializer<'de>,
576{
577    let s: String = Deserialize::deserialize(deserializer).unwrap();
578
579    let mut parts = s.split_whitespace();
580    if parts.clone().count() != 3 {
581        return Err(D::Error::custom(
582            "expected hslChannel has 3 parts, e.g: '210 40% 98%'",
583        ));
584    }
585
586    fn parse_number(s: &str) -> f32 {
587        s.trim_end_matches('%')
588            .parse()
589            .expect("failed to parse number")
590    }
591
592    let (h, s, l) = (
593        parse_number(parts.next().unwrap()),
594        parse_number(parts.next().unwrap()),
595        parse_number(parts.next().unwrap()),
596    );
597
598    Ok(hsl(h, s, l))
599}
600
601macro_rules! color_method {
602    ($color:tt, $scale:tt) => {
603        paste::paste! {
604            #[inline]
605            #[allow(unused)]
606            pub fn [<$color _ $scale>]() -> Hsla {
607                if let Some(color) = DEFAULT_COLORS.$color.get(&($scale as usize)) {
608                    return color.hsla;
609                }
610
611                black()
612            }
613        }
614    };
615}
616
617macro_rules! color_methods {
618    ($color:tt) => {
619        paste::paste! {
620            /// Get color by scale number.
621            ///
622            /// The possible scale numbers are:
623            /// 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950
624            ///
625            /// If the scale number is not found, it will return black color.
626            #[inline]
627            pub fn [<$color>](scale: usize) -> Hsla {
628                if let Some(color) = DEFAULT_COLORS.$color.get(&scale) {
629                    return color.hsla;
630                }
631
632                black()
633            }
634        }
635
636        color_method!($color, 50);
637        color_method!($color, 100);
638        color_method!($color, 200);
639        color_method!($color, 300);
640        color_method!($color, 400);
641        color_method!($color, 500);
642        color_method!($color, 600);
643        color_method!($color, 700);
644        color_method!($color, 800);
645        color_method!($color, 900);
646        color_method!($color, 950);
647    };
648}
649
650pub fn black() -> Hsla {
651    DEFAULT_COLORS.black.hsla
652}
653
654pub fn white() -> Hsla {
655    DEFAULT_COLORS.white.hsla
656}
657
658color_methods!(slate);
659color_methods!(gray);
660color_methods!(zinc);
661color_methods!(neutral);
662color_methods!(stone);
663color_methods!(red);
664color_methods!(orange);
665color_methods!(amber);
666color_methods!(yellow);
667color_methods!(lime);
668color_methods!(green);
669color_methods!(emerald);
670color_methods!(teal);
671color_methods!(cyan);
672color_methods!(sky);
673color_methods!(blue);
674color_methods!(indigo);
675color_methods!(violet);
676color_methods!(purple);
677color_methods!(fuchsia);
678color_methods!(pink);
679color_methods!(rose);
680
681/// Try to parse the color, HEX or [Tailwind Color](https://tailwindcss.com/docs/colors) expression.
682///
683/// # Parameter `color` should be one string value listed below:
684///
685/// - `#RRGGBB` - The HEX color string.
686/// - `#RRGGBBAA` - The HEX color string with alpha.
687///
688/// Or the Tailwind Color format:
689///
690/// - `name` - The color name `black`, `white`, or any other defined in `crate::color`.
691/// - `name-scale` - The color name with scale.
692/// - `name/opacity` - The color name with opacity, `opacity` should be an integer between 0 and 100.
693/// - `name-scale/opacity` - The color name with scale and opacity.
694///
695pub fn try_parse_color(color: &str) -> Result<Hsla> {
696    if color.starts_with("#") {
697        let rgba = gpui::Rgba::try_from(color)?;
698        return Ok(rgba.into());
699    }
700
701    let mut name = String::new();
702    let mut scale = None;
703    let mut opacity = None;
704    // 0: name, 1: scale, 2: opacity
705    let mut state = 0;
706    let mut part = String::new();
707
708    for c in color.chars() {
709        match c {
710            '-' if state == 0 => {
711                name = std::mem::take(&mut part);
712                state = 1;
713            }
714            '/' if state <= 1 => {
715                if state == 0 {
716                    name = std::mem::take(&mut part);
717                } else if state == 1 {
718                    scale = part.parse::<usize>().ok();
719                    part.clear();
720                }
721                state = 2;
722            }
723            _ => part.push(c),
724        }
725    }
726
727    match state {
728        0 => name = part,
729        1 => scale = part.parse::<usize>().ok(),
730        2 => opacity = part.parse::<f32>().ok(),
731        _ => {}
732    }
733
734    if name.is_empty() {
735        return Err(anyhow!("Empty color name"));
736    }
737
738    let mut hsla = match name.as_str() {
739        "black" => Ok::<Hsla, Error>(crate::black()),
740        "white" => Ok(crate::white()),
741        _ => {
742            let color_name = ColorName::try_from(name.as_str())?;
743            if let Some(scale) = scale {
744                Ok(color_name.scale(scale))
745            } else {
746                Ok(color_name.scale(500))
747            }
748        }
749    }?;
750
751    if let Some(opacity) = opacity {
752        if opacity > 100. {
753            return Err(anyhow!("Invalid color opacity"));
754        }
755        hsla = hsla.opacity(opacity / 100.);
756    }
757
758    Ok(hsla)
759}
760
761/// Try to parse a theme background value.
762///
763/// Supports all values accepted by [`try_parse_color`] and CSS-style two-stop
764/// `linear-gradient(...)` values.
765pub fn try_parse_background(background: &str) -> Result<Background> {
766    if let Ok(color) = try_parse_color(background) {
767        return Ok(color.into());
768    }
769
770    let gradient = parse_linear_gradient(background)?;
771    Ok(linear_gradient(gradient.angle, gradient.from, gradient.to))
772}
773
774/// Parse a background, clamping every color stop's alpha to at most `max`.
775///
776/// Unlike [`Background::opacity`], which scales all stops by a single factor,
777/// this caps each gradient stop independently, so a bright `to` stop (or a
778/// transparent `from` stop) can never push the rendered highlight past `max`.
779pub(crate) fn try_parse_background_clamped(background: &str, max: f32) -> Result<Background> {
780    if let Ok(color) = try_parse_color(background) {
781        return Ok(color.alpha(color.a.min(max)).into());
782    }
783
784    let gradient = parse_linear_gradient(background)?;
785    let clamp = |stop: LinearColorStop| {
786        linear_color_stop(stop.color.alpha(stop.color.a.min(max)), stop.percentage)
787    };
788    Ok(linear_gradient(
789        gradient.angle,
790        clamp(gradient.from),
791        clamp(gradient.to),
792    ))
793}
794
795pub(crate) fn try_parse_theme_color(color: &str) -> Result<Hsla> {
796    if let Ok(color) = try_parse_color(color) {
797        return Ok(color);
798    }
799
800    Ok(parse_linear_gradient(color)?.from.color)
801}
802
803struct ParsedLinearGradient {
804    angle: f32,
805    from: LinearColorStop,
806    to: LinearColorStop,
807}
808
809fn parse_linear_gradient(background: &str) -> Result<ParsedLinearGradient> {
810    const PREFIX: &str = "linear-gradient(";
811
812    let background = background.trim();
813    if !background.to_ascii_lowercase().starts_with(PREFIX) || !background.ends_with(')') {
814        return Err(anyhow!("Unsupported background value"));
815    }
816
817    let inner = &background[PREFIX.len()..background.len() - 1];
818    let parts = split_top_level_commas(inner);
819    let (angle, from, to) = match parts.as_slice() {
820        [from, to] => (
821            180.,
822            parse_linear_color_stop(from, 0.)?,
823            parse_linear_color_stop(to, 1.)?,
824        ),
825        [angle, from, to] => (
826            parse_linear_gradient_angle(angle)?,
827            parse_linear_color_stop(from, 0.)?,
828            parse_linear_color_stop(to, 1.)?,
829        ),
830        _ => {
831            return Err(anyhow!(
832                "Expected linear-gradient with two color stops, e.g. linear-gradient(135deg, #000, #fff)"
833            ));
834        }
835    };
836
837    Ok(ParsedLinearGradient { angle, from, to })
838}
839
840fn split_top_level_commas(value: &str) -> Vec<String> {
841    let mut parts = Vec::new();
842    let mut depth = 0usize;
843    let mut start = 0usize;
844
845    for (ix, ch) in value.char_indices() {
846        match ch {
847            '(' => depth += 1,
848            ')' => depth = depth.saturating_sub(1),
849            ',' if depth == 0 => {
850                parts.push(value[start..ix].trim().to_string());
851                start = ix + ch.len_utf8();
852            }
853            _ => {}
854        }
855    }
856
857    parts.push(value[start..].trim().to_string());
858    parts
859}
860
861fn parse_linear_gradient_angle(angle: &str) -> Result<f32> {
862    let angle = angle.trim().to_ascii_lowercase();
863
864    if let Some(degrees) = angle.strip_suffix("deg") {
865        return Ok(degrees.trim().parse::<f32>()?.rem_euclid(360.));
866    }
867
868    if let Some(direction) = angle.strip_prefix("to ") {
869        return parse_linear_gradient_direction(direction);
870    }
871
872    Err(anyhow!("Unsupported linear-gradient angle: {angle}"))
873}
874
875fn parse_linear_gradient_direction(direction: &str) -> Result<f32> {
876    let mut top = false;
877    let mut right = false;
878    let mut bottom = false;
879    let mut left = false;
880
881    for part in direction.split_whitespace() {
882        match part {
883            "top" => top = true,
884            "right" => right = true,
885            "bottom" => bottom = true,
886            "left" => left = true,
887            _ => {
888                return Err(anyhow!(
889                    "Unsupported linear-gradient direction: {direction}"
890                ));
891            }
892        }
893    }
894
895    match (top, right, bottom, left) {
896        (true, false, false, false) => Ok(0.),
897        (false, true, false, false) => Ok(90.),
898        (false, false, true, false) => Ok(180.),
899        (false, false, false, true) => Ok(270.),
900        (true, true, false, false) => Ok(45.),
901        (false, true, true, false) => Ok(135.),
902        (false, false, true, true) => Ok(225.),
903        (true, false, false, true) => Ok(315.),
904        _ => Err(anyhow!(
905            "Unsupported linear-gradient direction: {direction}"
906        )),
907    }
908}
909
910fn parse_linear_color_stop(stop: &str, default_percentage: f32) -> Result<LinearColorStop> {
911    let stop = stop.trim();
912    let mut parts = stop.split_whitespace().collect::<Vec<_>>();
913    let percentage = parts
914        .last()
915        .and_then(|part| part.strip_suffix('%'))
916        .map(|part| part.parse::<f32>().map(|value| value / 100.))
917        .transpose()?
918        .unwrap_or(default_percentage);
919
920    if stop.ends_with('%') {
921        parts.pop();
922    }
923
924    let color = parts.join(" ");
925    if color.is_empty() {
926        return Err(anyhow!("Expected color in linear-gradient color stop"));
927    }
928
929    Ok(linear_color_stop(
930        try_parse_color(&color)?,
931        percentage.clamp(0., 1.),
932    ))
933}
934
935#[cfg(test)]
936mod tests {
937    use gpui::{rgb, rgba};
938
939    use super::*;
940
941    #[test]
942    fn test_default_colors() {
943        assert_eq!(white(), hsl(0.0, 0.0, 100.0));
944        assert_eq!(black(), hsl(0.0, 0.0, 0.0));
945
946        assert_eq!(slate_50(), hsl(210.0, 40.0, 98.0));
947        assert_eq!(slate_100(), hsl(210.0, 40.0, 96.1));
948        assert_eq!(slate_900(), hsl(222.2, 47.4, 11.2));
949
950        assert_eq!(red_50(), hsl(0.0, 85.7, 97.3));
951        assert_eq!(yellow_100(), hsl(54.9, 96.7, 88.0));
952        assert_eq!(green_200(), hsl(141.0, 78.9, 85.1));
953        assert_eq!(cyan_300(), hsl(187.0, 92.4, 69.0));
954        assert_eq!(blue_400(), hsl(213.1, 93.9, 67.8));
955        assert_eq!(indigo_500(), hsl(238.7, 83.5, 66.7));
956    }
957
958    #[test]
959    fn test_to_hex_string() {
960        let color: Hsla = rgb(0xf8fafc).into();
961        assert_eq!(color.to_hex(), "#F8FAFC");
962
963        let color: Hsla = rgb(0xfef2f2).into();
964        assert_eq!(color.to_hex(), "#FEF2F2");
965
966        let color: Hsla = rgba(0x0413fcaa).into();
967        assert_eq!(color.to_hex(), "#0413FCAA");
968    }
969
970    #[test]
971    fn test_from_hex_string() {
972        let color: Hsla = Hsla::parse_hex("#F8FAFC").unwrap();
973        assert_eq!(color, rgb(0xf8fafc).into());
974
975        let color: Hsla = Hsla::parse_hex("#FEF2F2").unwrap();
976        assert_eq!(color, rgb(0xfef2f2).into());
977
978        let color: Hsla = Hsla::parse_hex("#0413FCAA").unwrap();
979        assert_eq!(color, rgba(0x0413fcaa).into());
980    }
981
982    #[test]
983    fn test_parse_hex_rejects_non_hex_digits() {
984        assert!(Hsla::parse_hex("#+f+f+f").is_err());
985        assert!(Hsla::parse_hex("#ff00+f").is_err());
986        // Six bytes, but the second character is two bytes wide.
987        assert!(Hsla::parse_hex("#a\u{e9}aaa").is_err());
988        assert!(Hsla::parse_hex("#a\u{e9}aaaaa").is_err());
989    }
990
991    #[test]
992    fn test_lighten() {
993        let color = super::hsl(240.0, 5.0, 30.0);
994        let color = color.lighten(0.5);
995        assert_eq!(color.l, 0.45000002);
996        let color = color.lighten(0.5);
997        assert_eq!(color.l, 0.675);
998        let color = color.lighten(0.1);
999        assert_eq!(color.l, 0.7425);
1000    }
1001
1002    #[test]
1003    fn test_darken() {
1004        let color = super::hsl(240.0, 5.0, 96.0);
1005        let color = color.darken(0.5);
1006        assert_eq!(color.l, 0.48);
1007        let color = color.darken(0.5);
1008        assert_eq!(color.l, 0.24);
1009    }
1010
1011    #[test]
1012    fn test_mix() {
1013        let red = Hsla::parse_hex("#FF0000").unwrap();
1014        let blue = Hsla::parse_hex("#0000FF").unwrap();
1015        let green = Hsla::parse_hex("#00FF00").unwrap();
1016        let yellow = Hsla::parse_hex("#FFFF00").unwrap();
1017
1018        assert_eq!(red.mix(blue, 0.5).to_hex(), "#FF00FF");
1019        assert_eq!(green.mix(red, 0.5).to_hex(), "#FFFF00");
1020        assert_eq!(blue.mix(yellow, 0.2).to_hex(), "#0098FF");
1021    }
1022
1023    #[test]
1024    fn test_mix_oklab() {
1025        let red = Hsla::parse_hex("#FF0000").unwrap();
1026        let blue = Hsla::parse_hex("#0000FF").unwrap();
1027        let transparent = gpui::Hsla {
1028            h: 0.0,
1029            s: 0.0,
1030            l: 0.0,
1031            a: 0.0,
1032        };
1033
1034        // Test mixing red with transparent (similar to CSS color-mix example)
1035        // color-mix(in oklab, red 20%, transparent) should give red with 20% opacity
1036        let result = red.mix_oklab(transparent, 0.2);
1037        assert!((result.a - 0.2).abs() < 0.01); // Alpha should be 20%
1038
1039        // The color should remain red (hue should be preserved)
1040        let rgb_result = result.to_rgb();
1041        let rgb_red = red.to_rgb();
1042        // Allow some tolerance due to color space conversions
1043        assert!(
1044            (rgb_result.r - rgb_red.r).abs() < 0.05,
1045            "Red channel should be preserved"
1046        );
1047        assert!(rgb_result.g < 0.05, "Green channel should be near 0");
1048        assert!(rgb_result.b < 0.05, "Blue channel should be near 0");
1049
1050        // Test basic color mixing in Oklab space
1051        let purple = red.mix_oklab(blue, 0.5);
1052        // Oklab mixing should produce different results than HSL mixing
1053        let purple_hsl = red.mix(blue, 0.5);
1054        assert_ne!(purple.to_hex(), purple_hsl.to_hex());
1055
1056        // Test factor boundaries (allowing small floating point errors)
1057        let result_0 = red.mix_oklab(blue, 0.0);
1058        let result_1 = red.mix_oklab(blue, 1.0);
1059
1060        // Check that result is close to expected (within 1 color unit per channel)
1061        let rgb_0 = result_0.to_rgb();
1062        let rgb_blue = blue.to_rgb();
1063        assert!((rgb_0.r - rgb_blue.r).abs() < 0.01);
1064        assert!((rgb_0.g - rgb_blue.g).abs() < 0.01);
1065        assert!((rgb_0.b - rgb_blue.b).abs() < 0.01);
1066
1067        let rgb_1 = result_1.to_rgb();
1068        let rgb_red = red.to_rgb();
1069        assert!((rgb_1.r - rgb_red.r).abs() < 0.01);
1070        assert!((rgb_1.g - rgb_red.g).abs() < 0.01);
1071        assert!((rgb_1.b - rgb_red.b).abs() < 0.01);
1072    }
1073
1074    #[test]
1075    fn test_color_name() {
1076        assert_eq!(ColorName::Purple.to_string(), "Purple");
1077        assert_eq!(format!("{}", ColorName::Green), "Green");
1078        assert_eq!(format!("{:?}", ColorName::Yellow), "Yellow");
1079
1080        let color = ColorName::Green;
1081        assert_eq!(color.scale(500).to_hex(), "#21C55E");
1082        assert_eq!(color.scale(1500).to_hex(), "#21C55E");
1083
1084        for name in ColorName::all().iter() {
1085            let name1: ColorName = name.to_string().as_str().try_into().unwrap();
1086            assert_eq!(name1, *name);
1087        }
1088    }
1089
1090    #[test]
1091    fn test_h_s_l() {
1092        let color = hsl(260., 94., 80.);
1093        assert_eq!(color.hue(200. / 360.), hsl(200., 94., 80.));
1094        assert_eq!(color.saturation(74. / 100.), hsl(260., 74., 80.));
1095        assert_eq!(color.lightness(74. / 100.), hsl(260., 94., 74.));
1096    }
1097
1098    #[test]
1099    fn test_try_parse_color() {
1100        assert_eq!(
1101            try_parse_color("#F2F200").ok(),
1102            Some(hsla(0.16666667, 1., 0.4745098, 1.0))
1103        );
1104        assert_eq!(
1105            try_parse_color("#00f21888").ok(),
1106            Some(hsla(0.34986225, 1.0, 0.4745098, 0.53333336))
1107        );
1108        assert_eq!(try_parse_color("black").ok(), Some(crate::black()));
1109        assert_eq!(try_parse_color("white-800").ok(), Some(crate::white()));
1110        assert_eq!(try_parse_color("red").ok(), Some(crate::red_500()));
1111        assert_eq!(try_parse_color("blue-600").ok(), Some(crate::blue_600()));
1112        assert_eq!(
1113            try_parse_color("pink/33").ok(),
1114            Some(crate::pink_500().opacity(0.33))
1115        );
1116        assert_eq!(
1117            try_parse_color("orange-300/66").ok(),
1118            Some(crate::orange_300().opacity(0.66))
1119        );
1120    }
1121
1122    #[test]
1123    fn test_try_parse_background_linear_gradient() {
1124        let from = try_parse_color("#4F46E5").unwrap();
1125        let to = try_parse_color("#06B6D4").unwrap();
1126
1127        assert_eq!(
1128            try_parse_background("linear-gradient(135deg, #4F46E5, #06B6D4)").unwrap(),
1129            gpui::linear_gradient(
1130                135.,
1131                gpui::linear_color_stop(from, 0.),
1132                gpui::linear_color_stop(to, 1.)
1133            )
1134        );
1135    }
1136
1137    #[test]
1138    fn test_try_parse_background_linear_gradient_direction_and_stops() {
1139        assert_eq!(
1140            try_parse_background("linear-gradient(to right, red-500 25%, blue-600 75%)").unwrap(),
1141            gpui::linear_gradient(
1142                90.,
1143                gpui::linear_color_stop(crate::red_500(), 0.25),
1144                gpui::linear_color_stop(crate::blue_600(), 0.75)
1145            )
1146        );
1147    }
1148}