Skip to main content

kitchen_ui/theme/
color.rs

1//! The colours: shared neutrals (greys with a slight cool bias: surfaces from the deepest, text,
2//! borders), the data ground ([`canvas`], [`grid`]), status colours, the selection, and the accent
3//! ([`super::Look::active_palette`]), resolved for the current look. The values are the Design
4//! System's tokens (`tokens.json`), one for one.
5//!
6//! Every function here reads the look set with [`super::set_look`], so code can ask for a colour
7//! without a context (`color::text_muted()`). [`Colors::resolve`] gives the same values for any
8//! look, for tests and for drawing a theme that is not the current one.
9//!
10//! Surfaces step clearly apart; in the dark theme a border is a step lighter than the surfaces it
11//! divides (an edge, not a ridge); text passes WCAG AA (≥ 4.5:1) on every surface and on the
12//! canvas, marks ≥ 3:1 (designparser `wcag-contrast`). The tests check each pair.
13
14use gpui_kit::{Hsla, Rgba, rgb};
15
16use super::{Look, look};
17
18/// The shared neutrals as `(dark, light)` RGB pairs: greys with a slight cool bias (blue a little
19/// above red), so warm data and any accent stand off them.
20pub mod neutrals {
21    /// Title bar, menu row, status bar, and the window ground panes sit on.
22    pub const CHROME: (u32, u32) = (0x16181b, 0xe9ebee);
23    /// Panels and panes: where content sits.
24    pub const PANEL: (u32, u32) = (0x1d1f23, 0xf6f7f9);
25    /// Raised blocks inside panels, popovers, panel group headers, the code editor ground.
26    pub const RAISED: (u32, u32) = (0x24272b, 0xffffff);
27    /// Controls at rest: buttons, inputs, slider tracks.
28    pub const CONTROL: (u32, u32) = (0x2c2f34, 0xe4e7eb);
29    /// A control or row under the pointer; the editor's current line at half opacity.
30    pub const HOVER: (u32, u32) = (0x363a40, 0xd8dce1);
31    /// Separators and outlines, one pixel.
32    pub const BORDER: (u32, u32) = (0x33373d, 0xc9ced5);
33    /// Body text and icons.
34    pub const TEXT: (u32, u32) = (0xe8eaed, 0x16191d);
35    /// Secondary text: labels, captions, hints, axis text.
36    pub const TEXT_MUTED: (u32, u32) = (0xa9aeb6, 0x4f5660);
37    /// Text of disabled controls only (no contrast requirement).
38    pub const TEXT_DISABLED: (u32, u32) = (0x646a73, 0x9aa1aa);
39    /// The ground data is drawn on: traces, slides, figures, the pipeline graph. Deeper than the
40    /// panel in the dark theme, white in the light one.
41    pub const CANVAS: (u32, u32) = (0x0e0f11, 0xffffff);
42    /// Gridlines and the pipeline's dot grid on the canvas. Never for text.
43    pub const GRID: (u32, u32) = (0x23262b, 0xe9ecef);
44    /// Errors and failed runs (text, marks and fills; always with a word or an icon).
45    pub const DANGER: (u32, u32) = (0xff8577, 0xc22f22);
46    /// Success and finished runs (text, marks and fills; always with a word or an icon).
47    pub const SUCCESS: (u32, u32) = (0x46b583, 0x1b7448);
48    /// Warnings and running jobs (text, marks and fills).
49    pub const WARNING: (u32, u32) = (0xe8a838, 0x8a5a00);
50    /// Neutral notices and reused runs (a result taken from an earlier run).
51    pub const INFO: (u32, u32) = (0x7fa8ff, 0x2f5fb3);
52}
53
54/// The data colours (Okabe & Ito 2008), in the order to use them: groups in figures, overlays on
55/// video, channels. Told apart with every common colour blindness, the same in both themes. The
56/// seventh (yellow) reads poorly on light grounds: use it only when six are not enough.
57pub const DATA: [u32; 7] = [0x0072b2, 0xe69f00, 0x009e73, 0xcc79a7, 0x56b4e9, 0xd55e00, 0xf0e442];
58
59/// Data colour `i` (wrapping after [`DATA`]'s seven).
60pub fn data(i: usize) -> Hsla {
61    rgb_hsla(DATA[i % DATA.len()])
62}
63
64/// Every colour of one look, resolved.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct Colors {
67    /// Title bar, tool columns, tab strips; the window background between panes.
68    pub chrome: Hsla,
69    /// Panels and panes.
70    pub panel: Hsla,
71    /// Raised blocks inside panels, popovers.
72    pub raised: Hsla,
73    /// Controls: buttons, inputs, slider tracks.
74    pub control: Hsla,
75    /// A control or row under the pointer.
76    pub hover: Hsla,
77    /// Separators and outlines.
78    pub border: Hsla,
79    /// Body text.
80    pub text: Hsla,
81    /// Secondary text.
82    pub text_muted: Hsla,
83    /// Disabled text only.
84    pub text_disabled: Hsla,
85    /// The accent fill: primary buttons, selection backgrounds (at a low opacity).
86    pub accent: Hsla,
87    /// The accent fill under the pointer.
88    pub accent_hover: Hsla,
89    /// Text and icons on the accent fill.
90    pub on_accent: Hsla,
91    /// Thin accent marks and accent text: slider fills, focus rings, links, selected borders.
92    pub accent_mark: Hsla,
93    /// Errors.
94    pub danger: Hsla,
95    /// Success.
96    pub success: Hsla,
97    /// Warnings.
98    pub warning: Hsla,
99    /// Neutral notices, reused runs.
100    pub info: Hsla,
101    /// The ground data is drawn on.
102    pub canvas: Hsla,
103    /// Gridlines on the canvas.
104    pub grid: Hsla,
105    /// A selected row, button or toggle: the accent at [`SELECTION_TINT`] over its surface (drawn
106    /// with a 1 px [`Colors::selection_edge`], 2 px on the left in lists).
107    pub selection: Hsla,
108    /// The edge of a selected item ([`Colors::accent_mark`]).
109    pub selection_edge: Hsla,
110    /// The focus ring: the accent mark, 2 px, outside the control.
111    pub focus: Hsla,
112    /// Background of an added line in a diff: [`Colors::success`] mixed into the panel.
113    pub diff_added: Hsla,
114    /// Background of a removed line in a diff: [`Colors::danger`] mixed into the panel.
115    pub diff_removed: Hsla,
116}
117
118/// How much of the status colour a diff line's background takes (the rest is the panel).
119pub const DIFF_TINT: f32 = 0.16;
120
121/// How much of the accent a selected item's background takes ([`Colors::selection`]), at most:
122/// less for an accent where this much would leave text unreadable ([`selection_tint`]).
123pub const SELECTION_TINT: f32 = 0.16;
124
125/// The tint of `accent` over `panel` for a selected item: [`SELECTION_TINT`], or the largest step
126/// below it at which each of `texts` still reads (≥ 4.5:1) and the selected edge `edge` still
127/// shows (≥ 3:1). A very light accent in the dark theme (a user's white, say) gets a fainter tint.
128pub fn selection_tint(panel: Hsla, accent: Hsla, texts: [Hsla; 2], edge: Hsla) -> f32 {
129    let mut t = SELECTION_TINT;
130    while t > 0.04 {
131        let bg = mix(panel, accent, t);
132        if texts.iter().all(|x| contrast(*x, bg) >= 4.5) && contrast(edge, bg) >= 3.0 {
133            break;
134        }
135        t -= 0.02;
136    }
137    t
138}
139
140/// Width of the focus ring (px).
141pub const FOCUS_RING_W: f32 = 2.;
142
143impl Colors {
144    /// The colours of `look`.
145    pub fn resolve(look: &Look) -> Colors {
146        let dark = look.dark;
147        let n = |pair: (u32, u32)| rgb_hsla(if dark { pair.0 } else { pair.1 });
148        let a = look.active_palette().accent(dark);
149        Colors {
150            chrome: n(neutrals::CHROME),
151            panel: n(neutrals::PANEL),
152            raised: n(neutrals::RAISED),
153            control: n(neutrals::CONTROL),
154            hover: n(neutrals::HOVER),
155            border: n(neutrals::BORDER),
156            text: n(neutrals::TEXT),
157            text_muted: n(neutrals::TEXT_MUTED),
158            text_disabled: n(neutrals::TEXT_DISABLED),
159            accent: rgb_hsla(a.fill),
160            accent_hover: rgb_hsla(a.fill_hover),
161            on_accent: rgb_hsla(a.on_fill),
162            accent_mark: rgb_hsla(a.mark),
163            danger: n(neutrals::DANGER),
164            success: n(neutrals::SUCCESS),
165            warning: n(neutrals::WARNING),
166            info: n(neutrals::INFO),
167            canvas: n(neutrals::CANVAS),
168            grid: n(neutrals::GRID),
169            selection: rgb_hsla(a.fill).opacity(selection_tint(n(neutrals::PANEL), rgb_hsla(a.fill), [n(neutrals::TEXT), n(neutrals::TEXT_MUTED)], rgb_hsla(a.mark))),
170            selection_edge: rgb_hsla(a.mark),
171            focus: rgb_hsla(a.mark),
172            diff_added: mix(n(neutrals::PANEL), n(neutrals::SUCCESS), DIFF_TINT),
173            diff_removed: mix(n(neutrals::PANEL), n(neutrals::DANGER), DIFF_TINT),
174        }
175    }
176}
177
178/// The colours of the current look.
179pub fn colors() -> Colors {
180    Colors::resolve(&look())
181}
182
183/// Title bar, tool columns, tab strips; the window background between panes.
184pub fn chrome() -> Hsla {
185    colors().chrome
186}
187/// Panels and panes.
188pub fn panel() -> Hsla {
189    colors().panel
190}
191/// Raised blocks inside panels, popovers, panel group headers.
192pub fn raised() -> Hsla {
193    colors().raised
194}
195/// Controls: buttons, inputs, slider tracks.
196pub fn control() -> Hsla {
197    colors().control
198}
199/// A control or row under the pointer.
200pub fn hover() -> Hsla {
201    colors().hover
202}
203/// Separators and outlines.
204pub fn border() -> Hsla {
205    colors().border
206}
207/// Body text.
208pub fn text() -> Hsla {
209    colors().text
210}
211/// Secondary text: ≥ 4.5:1 on every surface in both themes.
212pub fn text_muted() -> Hsla {
213    colors().text_muted
214}
215/// Disabled text only.
216pub fn text_disabled() -> Hsla {
217    colors().text_disabled
218}
219/// The accent fill: selection, the active tool, primary actions ([`on_accent`] text on it).
220pub fn accent() -> Hsla {
221    colors().accent
222}
223/// The accent fill under the pointer.
224pub fn accent_hover() -> Hsla {
225    colors().accent_hover
226}
227/// Text and icons on the accent fill.
228pub fn on_accent() -> Hsla {
229    colors().on_accent
230}
231/// Thin accent marks and accent text (≥ 3:1 on panels and controls).
232pub fn accent_mark() -> Hsla {
233    colors().accent_mark
234}
235/// Errors.
236pub fn danger() -> Hsla {
237    colors().danger
238}
239/// Success.
240pub fn success() -> Hsla {
241    colors().success
242}
243/// Warnings.
244pub fn warning() -> Hsla {
245    colors().warning
246}
247
248/// Neutral notices, reused runs.
249pub fn info() -> Hsla {
250    colors().info
251}
252/// The ground data is drawn on: traces, slides, figures, the pipeline graph.
253pub fn canvas() -> Hsla {
254    colors().canvas
255}
256/// Gridlines and the dot grid on the canvas. Never for text.
257pub fn grid() -> Hsla {
258    colors().grid
259}
260/// A selected item's background: the accent at 16 % (draw it with [`selection_edge`]).
261pub fn selection() -> Hsla {
262    colors().selection
263}
264/// The 1 px edge of a selected item.
265pub fn selection_edge() -> Hsla {
266    colors().selection_edge
267}
268/// The focus ring.
269pub fn focus() -> Hsla {
270    colors().focus
271}
272
273/// Background of an added line in a diff (text, muted text and the success mark pass on it).
274pub fn diff_added() -> Hsla {
275    colors().diff_added
276}
277/// Background of a removed line in a diff (text, muted text and the danger mark pass on it).
278pub fn diff_removed() -> Hsla {
279    colors().diff_removed
280}
281
282/// `a` with `t` (0–1) of `b` mixed in, in sRGB, opaque.
283pub fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla {
284    let (a, b) = (a.to_rgb(), b.to_rgb());
285    let m = |x: f32, y: f32| x + (y - x) * t;
286    Rgba { r: m(a.r, b.r), g: m(a.g, b.g), b: m(a.b, b.b), a: 1.0 }.into()
287}
288
289/// A colour from `0xRRGGBB`.
290pub fn rgb_hsla(c: u32) -> Hsla {
291    rgb(c).into()
292}
293
294/// A colour from 0–255 RGB.
295pub fn rgb8(c: [u8; 3]) -> Hsla {
296    rgb_hsla(((c[0] as u32) << 16) | ((c[1] as u32) << 8) | c[2] as u32)
297}
298
299/// Relative luminance (WCAG), alpha ignored.
300pub fn luminance(c: Hsla) -> f32 {
301    let Rgba { r, g, b, .. } = c.to_rgb();
302    let lin = |v: f32| if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) };
303    0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
304}
305
306/// WCAG contrast ratio of two colours (1 to 21).
307pub fn contrast(a: Hsla, b: Hsla) -> f32 {
308    let (la, lb) = (luminance(a), luminance(b));
309    (la.max(lb) + 0.05) / (la.min(lb) + 0.05)
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315    use crate::theme::Palette;
316
317    use crate::theme::Rgb;
318
319    /// Every app palette and every suggested accent, plus a few arbitrary picks, in both themes.
320    fn looks() -> Vec<Look> {
321        let mut accents: Vec<Option<Rgb>> = vec![None];
322        accents.extend(Rgb::SUGGESTED.map(Some));
323        accents.extend([0xfffacd, 0x0a1030, 0xff0000, 0xffffff, 0x000000].map(|c| Some(Rgb(c))));
324        let mut out = Vec::new();
325        for p in Palette::APPS {
326            for a in &accents {
327                for dark in [true, false] {
328                    out.push(Look::new(p).with_accent(*a).with_dark(dark));
329                }
330            }
331        }
332        out
333    }
334
335    #[test]
336    fn neutrals_have_a_slight_cool_bias() {
337        use neutrals::*;
338        let all = [("chrome", CHROME), ("panel", PANEL), ("raised", RAISED), ("control", CONTROL), ("hover", HOVER), ("border", BORDER), ("text", TEXT), ("text_muted", TEXT_MUTED), ("text_disabled", TEXT_DISABLED), ("canvas", CANVAS), ("grid", GRID)];
339        for (name, pair) in all {
340            for c in [pair.0, pair.1] {
341                let (r, g, b) = (c >> 16 & 0xff, c >> 8 & 0xff, c & 0xff);
342                assert!(r <= g && g <= b, "{name}: #{c:06x} leans warm");
343                assert!(b - r <= 20, "{name}: #{c:06x} is tinted, not neutral");
344            }
345        }
346    }
347
348    #[test]
349    fn data_ground_and_notices_pass() {
350        for dark in [true, false] {
351            let c = Colors::resolve(&Look::new(Palette::LIME).with_dark(dark));
352            for (tname, t) in [("text", c.text), ("text_muted", c.text_muted)] {
353                let r = contrast(t, c.canvas);
354                assert!(r >= 4.5, "dark={dark}: {tname} on canvas is {r:.2}:1");
355            }
356            assert!(c.grid != c.canvas, "dark={dark}: the grid shows on the canvas");
357            for (sname, s) in [("chrome", c.chrome), ("panel", c.panel), ("raised", c.raised)] {
358                let r = contrast(c.info, s);
359                assert!(r >= 4.5, "dark={dark}: info on {sname} is {r:.2}:1");
360            }
361            for (sname, s) in [("chrome", c.chrome), ("panel", c.panel), ("raised", c.raised), ("control", c.control), ("hover", c.hover)] {
362                let r = contrast(c.warning, s);
363                assert!(r >= 3.0, "dark={dark}: warning as a mark on {sname} is {r:.2}:1");
364            }
365        }
366    }
367
368    /// A selected row is the accent at up to 16 % over the panel: its text still reads, its edge
369    /// shows. The app palettes keep the full 16 %.
370    #[test]
371    fn selected_rows_pass() {
372        for l in looks() {
373            let c = Colors::resolve(&l);
374            let tint = c.selection.a;
375            assert!(tint <= SELECTION_TINT + 1e-6 && tint > 0.04, "tint {tint}");
376            if l.accent.is_none() {
377                assert!((tint - SELECTION_TINT).abs() < 1e-6, "{}: the app palette keeps 16 %", l.palette.name);
378            }
379            let bg = mix(c.panel, c.accent, tint);
380            let name = format!("{} accent={:?} dark={}", l.palette.name, l.accent, l.dark);
381            for (tname, t) in [("text", c.text), ("text_muted", c.text_muted)] {
382                let r = contrast(t, bg);
383                assert!(r >= 4.5, "{name}: {tname} on a selected row is {r:.2}:1");
384            }
385            let r = contrast(c.selection_edge, bg);
386            assert!(r >= 3.0, "{name}: the selected edge is {r:.2}:1");
387        }
388    }
389
390    #[test]
391    fn data_colours_are_okabe_ito() {
392        assert_eq!(DATA.len(), 7);
393        assert_eq!(data(0), data(7));
394        let set: std::collections::BTreeSet<u32> = DATA.into_iter().collect();
395        assert_eq!(set.len(), 7, "seven distinct colours");
396    }
397
398    #[test]
399    fn text_passes_aa_on_every_surface() {
400        for l in looks() {
401            let c = Colors::resolve(&l);
402            for (sname, s) in [("chrome", c.chrome), ("panel", c.panel), ("raised", c.raised), ("control", c.control), ("hover", c.hover)] {
403                for (tname, t) in [("text", c.text), ("text_muted", c.text_muted)] {
404                    let r = contrast(t, s);
405                    assert!(r >= 4.5, "{} dark={}: {tname} on {sname} is {r:.2}:1", l.palette.name, l.dark);
406                }
407            }
408            for (name, t) in [("danger", c.danger), ("success", c.success), ("warning", c.warning)] {
409                let r = contrast(t, c.panel);
410                assert!(r >= 4.5, "dark={}: {name} on panel is {r:.2}:1", l.dark);
411            }
412        }
413    }
414
415    #[test]
416    fn accents_pass_contrast() {
417        for l in looks() {
418            let c = Colors::resolve(&l);
419            let name = format!("{} {:?} dark={}", l.palette.name, l.accent, l.dark);
420            for (fname, f) in [("fill", c.accent), ("fill_hover", c.accent_hover)] {
421                let r = contrast(c.on_accent, f);
422                assert!(r >= 4.5, "{name}: text on {fname} is {r:.2}:1");
423            }
424            // Accent text (links) on panels; marks on controls
425            for (sname, s, min) in [("panel", c.panel, 4.5), ("raised", c.raised, 4.5), ("control", c.control, 3.0), ("hover", c.hover, 3.0)] {
426                let r = contrast(c.accent_mark, s);
427                assert!(r >= min, "{name}: mark on {sname} is {r:.2}:1");
428            }
429        }
430    }
431
432    #[test]
433    fn diff_lines_pass_contrast() {
434        for dark in [true, false] {
435            let c = Colors::resolve(&Look::new(Palette::LIME).with_dark(dark));
436            for (bname, bg, mark) in [("added", c.diff_added, c.success), ("removed", c.diff_removed, c.danger)] {
437                // The line's text and its line numbers
438                for (tname, t) in [("text", c.text), ("text_muted", c.text_muted)] {
439                    let r = contrast(t, bg);
440                    assert!(r >= 4.5, "dark={dark}: {tname} on the {bname} line is {r:.2}:1");
441                }
442                // The + / − sign is a mark
443                let r = contrast(mark, bg);
444                assert!(r >= 3.0, "dark={dark}: the sign on the {bname} line is {r:.2}:1");
445                // The tint is visible against the panel
446                assert!(bg != c.panel, "dark={dark}: the {bname} line is not tinted");
447            }
448        }
449    }
450
451    #[test]
452    fn surfaces_step_apart() {
453        for dark in [true, false] {
454            let c = Colors::resolve(&Look { dark, ..Look::new(Palette::LIME) });
455            let order = [c.chrome, c.panel, c.raised];
456            let l: Vec<f32> = order.iter().map(|c| luminance(*c)).collect();
457            assert!(l[0] < l[1] && l[1] < l[2], "dark={dark}: chrome < panel < raised in lightness");
458        }
459    }
460
461    #[test]
462    fn contrast_of_known_pairs() {
463        assert!((contrast(rgb_hsla(0x000000), rgb_hsla(0xffffff)) - 21.0).abs() < 0.01);
464        // The usual reference pairs: #767676 on white is 4.54:1 (the lightest grey passing AA),
465        // #777777 4.48:1 (fails). designparser `wcag-contrast` quotes 4.48 for #767676.
466        let r = contrast(rgb_hsla(0x767676), rgb_hsla(0xffffff));
467        assert!((r - 4.54).abs() < 0.01, "{r}");
468        let r = contrast(rgb_hsla(0x777777), rgb_hsla(0xffffff));
469        assert!((r - 4.48).abs() < 0.01, "{r}");
470        assert_eq!(rgb8([0x12, 0x34, 0x56]), rgb_hsla(0x123456));
471    }
472}