Skip to main content

theme/
color.rs

1//! Color math: the oklch → sRGB → HSL converters behind the token constructors,
2//! WCAG contrast for the palette tests, and small paint helpers.
3
4use gpui::{Hsla, hsla};
5
6/// A neutral (chroma 0) oklch tone as Hsla. Chroma 0 means r == g == b exactly,
7/// so this goes straight to an achromatic Hsla (skipping the hue math avoids
8/// float-noise saturation).
9pub fn neutral(lightness: f32) -> Hsla {
10    let [v, _, _] = oklch_to_srgb(lightness, 0.0, 0.0);
11    hsla(0.0, 0.0, v, 1.0)
12}
13
14/// An exact achromatic tone from an 8-bit channel value (`grey(13)` ≡ `#0d0d0d`)
15/// — for surfaces matched against reference-screenshot samples.
16pub fn grey(value: u8) -> Hsla {
17    hsla(0.0, 0.0, value as f32 / 255.0, 1.0)
18}
19
20/// Convert an oklch color (CSS notation: L 0..1, C, H in degrees) to gpui Hsla.
21pub fn oklch(l: f32, c: f32, h_deg: f32) -> Hsla {
22    let [r, g, b] = oklch_to_srgb(l, c, h_deg);
23    let (h, s, l) = rgb_to_hsl(r, g, b);
24    hsla(h, s, l, 1.0)
25}
26
27/// oklch → sRGB (each 0..1, clamped/gamut-clipped per channel).
28/// Reference: Björn Ottosson's OKLab definition (the same matrices CSS Color 4 uses).
29pub fn oklch_to_srgb(l: f32, c: f32, h_deg: f32) -> [f32; 3] {
30    let [r, g, b] = oklch_to_linear(l, c, h_deg);
31    [gamma_encode(r), gamma_encode(g), gamma_encode(b)]
32}
33
34/// oklch → *linear* sRGB, unclamped: a component outside 0..1 is a color the
35/// display cannot make, which is what [`fit_chroma`] tests for.
36fn oklch_to_linear(l: f32, c: f32, h_deg: f32) -> [f32; 3] {
37    let h = h_deg.to_radians();
38    oklab_to_linear(l, c * h.cos(), c * h.sin())
39}
40
41/// OKLab → *linear* sRGB, unclamped.
42fn oklab_to_linear(l: f32, a: f32, b: f32) -> [f32; 3] {
43    // OKLab → LMS (cube roots undone)
44    let l_ = l + 0.396_337_78 * a + 0.215_803_76 * b;
45    let m_ = l - 0.105_561_346 * a - 0.063_854_17 * b;
46    let s_ = l - 0.089_484_18 * a - 1.291_485_5 * b;
47    let (l3, m3, s3) = (l_ * l_ * l_, m_ * m_ * m_, s_ * s_ * s_);
48
49    // LMS → linear sRGB
50    let r = 4.076_741_7 * l3 - 3.307_711_6 * m3 + 0.230_969_93 * s3;
51    let g = -1.268_438 * l3 + 2.609_757_4 * m3 - 0.341_319_4 * s3;
52    let b = -0.004_196_086_3 * l3 - 0.703_418_6 * m3 + 1.707_614_7 * s3;
53
54    [r, g, b]
55}
56
57fn gamma_encode(x: f32) -> f32 {
58    let x = x.clamp(0.0, 1.0);
59    if x <= 0.003_130_8 {
60        12.92 * x
61    } else {
62        1.055 * x.powf(1.0 / 2.4) - 0.055
63    }
64}
65
66fn gamma_decode(x: f32) -> f32 {
67    let x = x.clamp(0.0, 1.0);
68    if x <= 0.040_449_936 {
69        x / 12.92
70    } else {
71        ((x + 0.055) / 1.055).powf(2.4)
72    }
73}
74
75/// Linear sRGB → OKLab.
76fn linear_to_oklab([r, g, b]: [f32; 3]) -> [f32; 3] {
77    let l = (0.412_221_47 * r + 0.536_332_55 * g + 0.051_445_995 * b).cbrt();
78    let m = (0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b).cbrt();
79    let s = (0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b).cbrt();
80    [
81        0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
82        1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
83        0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
84    ]
85}
86
87/// `from` moved `t` of the way to `to` (0..1) in OKLab, alpha alongside.
88pub fn mix_oklab(from: Hsla, to: Hsla, t: f32) -> Hsla {
89    let t = t.clamp(0.0, 1.0);
90    let lab = |color: Hsla| {
91        let [r, g, b] = hsl_to_rgb(color.h, color.s, color.l);
92        linear_to_oklab([gamma_decode(r), gamma_decode(g), gamma_decode(b)])
93    };
94    let (a, b) = (lab(from), lab(to));
95    let [l, x, y] = std::array::from_fn(|ix| a[ix] + (b[ix] - a[ix]) * t);
96    let [r, g, bl] = oklab_to_linear(l, x, y);
97    let (h, s, l) = rgb_to_hsl(gamma_encode(r), gamma_encode(g), gamma_encode(bl));
98    hsla(h, s, l, from.a + (to.a - from.a) * t)
99}
100
101/// The oklch lightness of an achromatic tone: [`neutral`] inverted.
102///
103/// Only greys round-trip through this. A grey's three channels are equal, and
104/// the three LMS matrix rows each sum to 1, so the whole OKLab transform
105/// collapses to one cube root — no inverse matrix needed.
106pub fn lightness(color: Hsla) -> f32 {
107    gamma_decode(color.l).cbrt()
108}
109
110/// The most chroma sRGB can hold at this lightness and hue, up to `chroma`.
111///
112/// Near black and near white the gamut is a needle: asking for a mid-ramp
113/// chroma there produces an out-of-range component, and clamping it per channel
114/// shifts the hue instead of dropping the saturation. Tailwind's neutral ramps
115/// taper their chroma at both ends by hand for the same reason; here the taper
116/// is whatever the gamut allows, so no ramp has to be tabulated.
117fn fit_chroma(l: f32, chroma: f32, hue: f32) -> f32 {
118    let fits = |c: f32| {
119        oklch_to_linear(l, c, hue)
120            .iter()
121            .all(|x| (-1e-4..=1.0 + 1e-4).contains(x))
122    };
123    if fits(chroma) {
124        return chroma;
125    }
126    let (mut lo, mut hi) = (0.0, chroma);
127    for _ in 0..24 {
128        let mid = 0.5 * (lo + hi);
129        if fits(mid) { lo = mid } else { hi = mid }
130    }
131    lo
132}
133
134/// Re-emit an achromatic tone at `hue`, carrying as much `chroma` as its
135/// lightness can hold. Alpha rides through untouched.
136pub fn tint(color: Hsla, hue: f32, chroma: f32) -> Hsla {
137    if chroma <= 0.0 {
138        return color;
139    }
140    let l = lightness(color);
141    let mut out = oklch(l, fit_chroma(l, chroma, hue), hue);
142    out.a = color.a;
143    out
144}
145
146/// sRGB (0..1 components) → HSL, all components 0..1 (gpui's Hsla convention).
147pub fn rgb_to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
148    let max = r.max(g).max(b);
149    let min = r.min(g).min(b);
150    let l = (max + min) / 2.0;
151    let delta = max - min;
152    if delta < f32::EPSILON {
153        return (0.0, 0.0, l);
154    }
155    let s = if l > 0.5 {
156        delta / (2.0 - max - min)
157    } else {
158        delta / (max + min)
159    };
160    let h = if (max - r).abs() < f32::EPSILON {
161        ((g - b) / delta).rem_euclid(6.0)
162    } else if (max - g).abs() < f32::EPSILON {
163        (b - r) / delta + 2.0
164    } else {
165        (r - g) / delta + 4.0
166    } / 6.0;
167    (h, s, l)
168}
169
170/// HSL (gpui convention, all 0..1) → sRGB components 0..1.
171pub fn hsl_to_rgb(h: f32, s: f32, l: f32) -> [f32; 3] {
172    if s <= f32::EPSILON {
173        return [l, l, l];
174    }
175    let q = if l < 0.5 {
176        l * (1.0 + s)
177    } else {
178        l + s - l * s
179    };
180    let p = 2.0 * l - q;
181    let hue = |mut t: f32| {
182        t = t.rem_euclid(1.0);
183        if t < 1.0 / 6.0 {
184            p + (q - p) * 6.0 * t
185        } else if t < 0.5 {
186            q
187        } else if t < 2.0 / 3.0 {
188            p + (q - p) * (2.0 / 3.0 - t) * 6.0
189        } else {
190            p
191        }
192    };
193    [hue(h + 1.0 / 3.0), hue(h), hue(h - 1.0 / 3.0)]
194}
195
196/// WCAG 2.1 relative luminance of an opaque color.
197pub fn relative_luminance(color: Hsla) -> f32 {
198    let lin = |c: f32| {
199        if c <= 0.040_45 {
200            c / 12.92
201        } else {
202            ((c + 0.055) / 1.055).powf(2.4)
203        }
204    };
205    let [r, g, b] = hsl_to_rgb(color.h, color.s, color.l);
206    0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
207}
208
209/// WCAG 2.1 contrast ratio between two opaque colors (1.0 … 21.0).
210///
211/// Used by the palette tests to prove each light token reproduces the contrast
212/// its dark counterpart had, rather than merely looking plausible.
213pub fn contrast_ratio(a: Hsla, b: Hsla) -> f32 {
214    let (la, lb) = (relative_luminance(a), relative_luminance(b));
215    let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
216    (hi + 0.05) / (lo + 0.05)
217}
218
219/// Composite `fg` (which may be translucent) over an opaque `bg`, returning the
220/// opaque result — the color the eye actually receives.
221pub fn flatten(fg: Hsla, bg: Hsla) -> Hsla {
222    let a = fg.a.clamp(0.0, 1.0);
223    let [fr, fg_, fb] = hsl_to_rgb(fg.h, fg.s, fg.l);
224    let [br, bg_, bb] = hsl_to_rgb(bg.h, bg.s, bg.l);
225    let (h, s, l) = rgb_to_hsl(
226        fr * a + br * (1.0 - a),
227        fg_ * a + bg_ * (1.0 - a),
228        fb * a + bb * (1.0 - a),
229    );
230    hsla(h, s, l, 1.0)
231}
232
233/// Linear per-component mix of two colors (paint helper for the gradient spinner).
234pub fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla {
235    let t = t.clamp(0.0, 1.0);
236    let lerp = |x: f32, y: f32| x + (y - x) * t;
237    // Mix through hue naively — both spinner endpoints sit close enough on the
238    // wheel that shortest-arc handling isn't needed for our palette.
239    hsla(
240        lerp(a.h, b.h),
241        lerp(a.s, b.s),
242        lerp(a.l, b.l),
243        lerp(a.a, b.a),
244    )
245}