Skip to main content

gpui_m3/
theme.rs

1//! Material 3 Expressive color, typography and corner scale.
2//!
3//! The baseline schemes use the same tokens as the reference design (the M3 reference purple).
4//! [`Scheme::from_seed`] generates a dynamic (tonal spot) scheme from any color, and
5//! [`Scheme::from_seed_variant`] any of the nine Material variants at any contrast.
6
7use std::str::FromStr;
8
9use gpui::{App, BoxShadow, Global, Hsla, Pixels, Rgba, hsla, point, px, rgb};
10use material_colors::{
11    color::Argb,
12    hct::Hct,
13    scheme::variant::{
14        SchemeContent, SchemeExpressive, SchemeFidelity, SchemeFruitSalad, SchemeMonochrome,
15        SchemeNeutral, SchemeRainbow, SchemeTonalSpot, SchemeVibrant,
16    },
17};
18
19/// Default font family, registered by [`crate::init`] (Inter, static files).
20pub const FONT_FAMILY: &str = "Inter";
21
22/// Roboto, also registered by [`crate::init`].
23pub const ROBOTO_FONT_FAMILY: &str = "Roboto";
24
25static CURRENT_FONT: std::sync::RwLock<&'static str> = std::sync::RwLock::new(FONT_FAMILY);
26
27/// The font family components draw with: [`FONT_FAMILY`] unless the app chose another
28/// one with [`set_font_family`].
29pub fn font_family() -> &'static str {
30    *CURRENT_FONT.read().unwrap_or_else(|e| e.into_inner())
31}
32
33/// Switches the family every component uses from the next frame on (a bundled one or
34/// any installed family name). Refresh the windows after calling it.
35pub fn set_font_family(family: &'static str) {
36    *CURRENT_FONT.write().unwrap_or_else(|e| e.into_inner()) = family;
37}
38
39/// Monospace family for shortcuts and code (the platform's own; none is bundled).
40#[cfg(target_os = "windows")]
41pub const MONO_FONT_FAMILY: &str = "Consolas";
42#[cfg(target_os = "macos")]
43pub const MONO_FONT_FAMILY: &str = "Menlo";
44#[cfg(not(any(target_os = "windows", target_os = "macos")))]
45pub const MONO_FONT_FAMILY: &str = "DejaVu Sans Mono";
46
47/// M3 corner scale (0 · 4 · 8 · 12 · 16 · 20 · 28 · 32 · 48 · full).
48pub mod corner {
49    use gpui::{Pixels, px};
50
51    pub const NONE: Pixels = px(0.);
52    pub const XS: Pixels = px(4.);
53    pub const S: Pixels = px(8.);
54    pub const M: Pixels = px(12.);
55    pub const L: Pixels = px(16.);
56    pub const LI: Pixels = px(20.);
57    pub const XL: Pixels = px(28.);
58    pub const XLI: Pixels = px(32.);
59    pub const XXL: Pixels = px(48.);
60    /// Fully round: GPUI clamps a radius to half the shorter side.
61    pub const FULL: Pixels = px(9999.);
62}
63
64/// M3 color roles. Names follow the spec; the reference design's CSS token is in parentheses.
65#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct Scheme {
67    /// (--accent)
68    pub primary: Hsla,
69    /// (--on-accent)
70    pub on_primary: Hsla,
71    /// (--accent-soft)
72    pub primary_container: Hsla,
73    /// (--on-accent-soft)
74    pub on_primary_container: Hsla,
75    /// The secondary accent: less prominent than `primary`.
76    pub secondary: Hsla,
77    /// Content on `secondary`.
78    pub on_secondary: Hsla,
79    /// (--secondary)
80    pub secondary_container: Hsla,
81    /// (--on-secondary)
82    pub on_secondary_container: Hsla,
83    /// (--tertiary)
84    pub tertiary: Hsla,
85    /// Content on `tertiary`.
86    pub on_tertiary: Hsla,
87    /// (--tertiary-soft)
88    pub tertiary_container: Hsla,
89    /// (--on-tertiary-soft)
90    pub on_tertiary_container: Hsla,
91    /// (--pane)
92    pub surface: Hsla,
93    /// The darkest surface: behind everything, never brighter than `surface`.
94    pub surface_dim: Hsla,
95    /// The brightest surface: never dimmer than `surface`.
96    pub surface_bright: Hsla,
97    /// Sunk below the other containers (a field inside a card).
98    pub surface_container_lowest: Hsla,
99    /// Slightly above `surface`.
100    pub surface_container_low: Hsla,
101    /// (--bg, --raised)
102    pub surface_container: Hsla,
103    /// (--control, --hover)
104    pub surface_container_high: Hsla,
105    /// (--control-2)
106    pub surface_container_highest: Hsla,
107    /// (--text)
108    pub on_surface: Hsla,
109    /// (--muted)
110    pub on_surface_variant: Hsla,
111    /// (--outline, --faint)
112    pub outline: Hsla,
113    /// (--border)
114    pub outline_variant: Hsla,
115    /// Inverse of `surface`: snackbars and tooltips.
116    pub inverse_surface: Hsla,
117    /// Content on `inverse_surface`.
118    pub inverse_on_surface: Hsla,
119    /// An action on `inverse_surface` (a snackbar's button).
120    pub inverse_primary: Hsla,
121    /// Dims what is behind a modal.
122    pub scrim: Hsla,
123    /// (--bad)
124    pub error: Hsla,
125    /// Content on `error`.
126    pub on_error: Hsla,
127    pub error_container: Hsla,
128    pub on_error_container: Hsla,
129    /// (--ok)
130    pub success: Hsla,
131    /// (--warn)
132    pub warning: Hsla,
133    /// Shadow color for menus and FABs.
134    pub shadow: Hsla,
135}
136
137impl Scheme {
138    pub fn baseline_light() -> Self {
139        Self {
140            primary: rgb(0x6750a4).into(),
141            on_primary: rgb(0xffffff).into(),
142            primary_container: rgb(0xeaddff).into(),
143            on_primary_container: rgb(0x4f378b).into(),
144            secondary: rgb(0x625b71).into(),
145            on_secondary: rgb(0xffffff).into(),
146            secondary_container: rgb(0xe8def8).into(),
147            on_secondary_container: rgb(0x4a4458).into(),
148            tertiary: rgb(0x7d5260).into(),
149            on_tertiary: rgb(0xffffff).into(),
150            tertiary_container: rgb(0xffd8e4).into(),
151            on_tertiary_container: rgb(0x633b48).into(),
152            surface: rgb(0xfef7ff).into(),
153            surface_dim: rgb(0xded8e1).into(),
154            surface_bright: rgb(0xfef7ff).into(),
155            surface_container_lowest: rgb(0xffffff).into(),
156            surface_container_low: rgb(0xf7f2fa).into(),
157            surface_container: rgb(0xf3edf7).into(),
158            surface_container_high: rgb(0xece6f0).into(),
159            surface_container_highest: rgb(0xe6e0e9).into(),
160            on_surface: rgb(0x1d1b20).into(),
161            on_surface_variant: rgb(0x49454f).into(),
162            outline: rgb(0x79747e).into(),
163            outline_variant: rgb(0xcac4d0).into(),
164            inverse_surface: rgb(0x322f35).into(),
165            inverse_on_surface: rgb(0xf5eff7).into(),
166            inverse_primary: rgb(0xd0bcff).into(),
167            scrim: rgb(0x000000).into(),
168            error: rgb(0xb3261e).into(),
169            on_error: rgb(0xffffff).into(),
170            error_container: rgb(0xf9dedc).into(),
171            on_error_container: rgb(0x410e0b).into(),
172            success: rgb(0x146c2e).into(),
173            warning: rgb(0x8b5000).into(),
174            shadow: Hsla {
175                h: 0.,
176                s: 0.,
177                l: 0.,
178                a: 0.12,
179            },
180        }
181    }
182
183    pub fn baseline_dark() -> Self {
184        Self {
185            primary: rgb(0xd0bcff).into(),
186            on_primary: rgb(0x381e72).into(),
187            primary_container: rgb(0x4f378b).into(),
188            on_primary_container: rgb(0xeaddff).into(),
189            secondary: rgb(0xccc2dc).into(),
190            on_secondary: rgb(0x332d41).into(),
191            secondary_container: rgb(0x4a4458).into(),
192            on_secondary_container: rgb(0xe8def8).into(),
193            tertiary: rgb(0xefb8c8).into(),
194            on_tertiary: rgb(0x492532).into(),
195            tertiary_container: rgb(0x633b48).into(),
196            on_tertiary_container: rgb(0xffd8e4).into(),
197            surface: rgb(0x141218).into(),
198            surface_dim: rgb(0x141218).into(),
199            surface_bright: rgb(0x3b383e).into(),
200            surface_container_lowest: rgb(0x0f0d13).into(),
201            surface_container_low: rgb(0x1d1b20).into(),
202            surface_container: rgb(0x211f26).into(),
203            surface_container_high: rgb(0x2b2930).into(),
204            surface_container_highest: rgb(0x36343b).into(),
205            on_surface: rgb(0xe6e0e9).into(),
206            on_surface_variant: rgb(0xcac4d0).into(),
207            outline: rgb(0x938f99).into(),
208            outline_variant: rgb(0x49454f).into(),
209            inverse_surface: rgb(0xe6e0e9).into(),
210            inverse_on_surface: rgb(0x322f35).into(),
211            inverse_primary: rgb(0x6750a4).into(),
212            scrim: rgb(0x000000).into(),
213            error: rgb(0xf2b8b5).into(),
214            on_error: rgb(0x601410).into(),
215            error_container: rgb(0x8c1d18).into(),
216            on_error_container: rgb(0xf9dedc).into(),
217            success: rgb(0xa8dab5).into(),
218            warning: rgb(0xffb868).into(),
219            shadow: Hsla {
220                h: 0.,
221                s: 0.,
222                l: 0.,
223                a: 0.4,
224            },
225        }
226    }
227
228    /// Every role mixed between `self` (at `t = 0`) and `other` (at `t = 1`), in sRGB.
229    pub fn lerp(&self, other: &Scheme, t: f32) -> Scheme {
230        let m = |a: Hsla, b: Hsla| mix(b, a, t.clamp(0., 1.));
231        Scheme {
232            primary: m(self.primary, other.primary),
233            on_primary: m(self.on_primary, other.on_primary),
234            primary_container: m(self.primary_container, other.primary_container),
235            on_primary_container: m(self.on_primary_container, other.on_primary_container),
236            secondary: m(self.secondary, other.secondary),
237            on_secondary: m(self.on_secondary, other.on_secondary),
238            secondary_container: m(self.secondary_container, other.secondary_container),
239            on_secondary_container: m(self.on_secondary_container, other.on_secondary_container),
240            tertiary: m(self.tertiary, other.tertiary),
241            on_tertiary: m(self.on_tertiary, other.on_tertiary),
242            tertiary_container: m(self.tertiary_container, other.tertiary_container),
243            on_tertiary_container: m(self.on_tertiary_container, other.on_tertiary_container),
244            surface: m(self.surface, other.surface),
245            surface_dim: m(self.surface_dim, other.surface_dim),
246            surface_bright: m(self.surface_bright, other.surface_bright),
247            surface_container_lowest: m(
248                self.surface_container_lowest,
249                other.surface_container_lowest,
250            ),
251            surface_container_low: m(self.surface_container_low, other.surface_container_low),
252            surface_container: m(self.surface_container, other.surface_container),
253            surface_container_high: m(self.surface_container_high, other.surface_container_high),
254            surface_container_highest: m(
255                self.surface_container_highest,
256                other.surface_container_highest,
257            ),
258            on_surface: m(self.on_surface, other.on_surface),
259            on_surface_variant: m(self.on_surface_variant, other.on_surface_variant),
260            outline: m(self.outline, other.outline),
261            outline_variant: m(self.outline_variant, other.outline_variant),
262            inverse_surface: m(self.inverse_surface, other.inverse_surface),
263            inverse_on_surface: m(self.inverse_on_surface, other.inverse_on_surface),
264            inverse_primary: m(self.inverse_primary, other.inverse_primary),
265            scrim: m(self.scrim, other.scrim),
266            error: m(self.error, other.error),
267            on_error: m(self.on_error, other.on_error),
268            error_container: m(self.error_container, other.error_container),
269            on_error_container: m(self.on_error_container, other.on_error_container),
270            success: m(self.success, other.success),
271            warning: m(self.warning, other.warning),
272            shadow: m(self.shadow, other.shadow),
273        }
274    }
275
276    /// Dynamic "tonal spot" scheme (2021 spec) from a seed color.
277    pub fn from_seed(seed: Hsla, dark: bool) -> Self {
278        Self::from_seed_variant(seed, dark, SchemeVariant::TonalSpot, 0.)
279    }
280
281    /// A dynamic scheme from a seed color in one of the nine Material variants. `contrast`
282    /// goes from -1 (least) through 0 (the standard design) to 1 (most, for readability).
283    pub fn from_seed_variant(
284        seed: Hsla,
285        dark: bool,
286        variant: SchemeVariant,
287        contrast: f32,
288    ) -> Self {
289        let rgba = Rgba::from(seed);
290        let argb = Argb::new(
291            255,
292            (rgba.r * 255.).round() as u8,
293            (rgba.g * 255.).round() as u8,
294            (rgba.b * 255.).round() as u8,
295        );
296        let source = Hct::new(argb);
297        let contrast = Some(f64::from(contrast.clamp(-1., 1.)));
298        let s = match variant {
299            SchemeVariant::TonalSpot => SchemeTonalSpot::new(source, dark, contrast).scheme,
300            SchemeVariant::Expressive => SchemeExpressive::new(source, dark, contrast).scheme,
301            SchemeVariant::Vibrant => SchemeVibrant::new(source, dark, contrast).scheme,
302            SchemeVariant::Neutral => SchemeNeutral::new(source, dark, contrast).scheme,
303            SchemeVariant::Monochrome => SchemeMonochrome::new(source, dark, contrast).scheme,
304            SchemeVariant::Fidelity => SchemeFidelity::new(source, dark, contrast).scheme,
305            SchemeVariant::Content => SchemeContent::new(source, dark, contrast).scheme,
306            SchemeVariant::Rainbow => SchemeRainbow::new(source, dark, contrast).scheme,
307            SchemeVariant::FruitSalad => SchemeFruitSalad::new(source, dark, contrast).scheme,
308        };
309        let base = if dark {
310            Self::baseline_dark()
311        } else {
312            Self::baseline_light()
313        };
314        let c = |a: Argb| -> Hsla { rgb(u32::from_str_radix(&a.to_hex(), 16).unwrap_or(0)).into() };
315        Self {
316            primary: c(s.primary()),
317            on_primary: c(s.on_primary()),
318            primary_container: c(s.primary_container()),
319            on_primary_container: c(s.on_primary_container()),
320            secondary: c(s.secondary()),
321            on_secondary: c(s.on_secondary()),
322            secondary_container: c(s.secondary_container()),
323            on_secondary_container: c(s.on_secondary_container()),
324            tertiary: c(s.tertiary()),
325            on_tertiary: c(s.on_tertiary()),
326            tertiary_container: c(s.tertiary_container()),
327            on_tertiary_container: c(s.on_tertiary_container()),
328            surface: c(s.surface()),
329            surface_dim: c(s.surface_dim()),
330            surface_bright: c(s.surface_bright()),
331            surface_container_lowest: c(s.surface_container_lowest()),
332            surface_container_low: c(s.surface_container_low()),
333            surface_container: c(s.surface_container()),
334            surface_container_high: c(s.surface_container_high()),
335            surface_container_highest: c(s.surface_container_highest()),
336            on_surface: c(s.on_surface()),
337            on_surface_variant: c(s.on_surface_variant()),
338            outline: c(s.outline()),
339            outline_variant: c(s.outline_variant()),
340            inverse_surface: c(s.inverse_surface()),
341            inverse_on_surface: c(s.inverse_on_surface()),
342            inverse_primary: c(s.inverse_primary()),
343            scrim: c(s.scrim()),
344            error: c(s.error()),
345            on_error: c(s.on_error()),
346            error_container: c(s.error_container()),
347            on_error_container: c(s.on_error_container()),
348            ..base
349        }
350    }
351
352    /// Fills the roles a hand-made scheme has no color for from the ones it has: the secondary
353    /// and inverse roles, the `on_*` of each accent, the dim, bright, low and lowest surfaces
354    /// and the scrim. They are approximations that follow the scheme's own polarity; a
355    /// generated scheme ([`Scheme::from_seed_variant`]) already has the exact ones.
356    ///
357    /// ```ignore
358    /// Scheme { primary, on_primary, /* your tokens */ ..Scheme::baseline_dark() }.derive_roles()
359    /// ```
360    pub fn derive_roles(self) -> Self {
361        let light = self.surface.l > 0.5;
362        let white = hsla(0., 0., 1., 1.);
363        let black = hsla(0., 0., 0., 1.);
364        // `amount` of `from`, the rest `to`.
365        let blend = |from: Hsla, to: Hsla, amount: f32| mix(from, to, amount);
366        Self {
367            secondary: blend(self.secondary_container, self.on_secondary_container, 0.2),
368            on_secondary: self.on_primary,
369            on_tertiary: self.on_primary,
370            on_error: self.on_primary,
371            surface_dim: if light {
372                blend(self.surface_container_highest, black, 0.96)
373            } else {
374                self.surface
375            },
376            surface_bright: if light {
377                self.surface
378            } else {
379                blend(self.surface_container_highest, white, 0.94)
380            },
381            surface_container_lowest: if light {
382                blend(self.surface, white, 0.5)
383            } else {
384                blend(self.surface, black, 0.65)
385            },
386            surface_container_low: blend(self.surface, self.surface_container, 0.5),
387            inverse_surface: self.on_surface,
388            inverse_on_surface: if light {
389                self.surface_container
390            } else {
391                self.surface_container_highest
392            },
393            inverse_primary: self.primary_container,
394            scrim: black,
395            ..self
396        }
397    }
398}
399
400/// The nine dynamic color variants of Material 3, for [`Scheme::from_seed_variant`].
401#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
402pub enum SchemeVariant {
403    /// The default: calm, mid chroma.
404    #[default]
405    TonalSpot,
406    /// Playful: the accents' hue is shifted away from the seed's.
407    Expressive,
408    /// Very colorful, detached from the seed.
409    Vibrant,
410    /// Almost gray, with a hint of the seed.
411    Neutral,
412    /// Pure grays.
413    Monochrome,
414    /// Keeps the seed color as the primary.
415    Fidelity,
416    /// Like fidelity, with a tertiary analogous to the seed.
417    Content,
418    /// A rainbow of accents around the seed.
419    Rainbow,
420    /// Bolder, with an offset hue.
421    FruitSalad,
422}
423
424impl SchemeVariant {
425    /// Every variant, in the order the gallery lists them.
426    pub const ALL: [SchemeVariant; 9] = [
427        SchemeVariant::TonalSpot,
428        SchemeVariant::Expressive,
429        SchemeVariant::Vibrant,
430        SchemeVariant::Neutral,
431        SchemeVariant::Monochrome,
432        SchemeVariant::Fidelity,
433        SchemeVariant::Content,
434        SchemeVariant::Rainbow,
435        SchemeVariant::FruitSalad,
436    ];
437
438    pub fn label(self) -> &'static str {
439        match self {
440            SchemeVariant::TonalSpot => "Tonal spot",
441            SchemeVariant::Expressive => "Expressive",
442            SchemeVariant::Vibrant => "Vibrant",
443            SchemeVariant::Neutral => "Neutral",
444            SchemeVariant::Monochrome => "Monochrome",
445            SchemeVariant::Fidelity => "Fidelity",
446            SchemeVariant::Content => "Content",
447            SchemeVariant::Rainbow => "Rainbow",
448            SchemeVariant::FruitSalad => "Fruit salad",
449        }
450    }
451}
452
453/// The app's active theme. Read it with [`Theme::of`] and change it with [`Theme::set`].
454#[derive(Clone, Copy, Debug)]
455pub struct Theme {
456    pub scheme: Scheme,
457    pub dark: bool,
458    pub seed: Option<Hsla>,
459}
460
461impl Global for Theme {}
462
463impl Theme {
464    pub fn new(dark: bool, seed: Option<Hsla>) -> Self {
465        let scheme = match seed {
466            Some(seed) => Scheme::from_seed(seed, dark),
467            None if dark => Scheme::baseline_dark(),
468            None => Scheme::baseline_light(),
469        };
470        Self { scheme, dark, seed }
471    }
472
473    pub fn of(cx: &App) -> &Scheme {
474        &cx.global::<Theme>().scheme
475    }
476
477    pub fn get(cx: &App) -> Theme {
478        *cx.global::<Theme>()
479    }
480
481    /// Uses a custom scheme (e.g. your app's existing tokens) instead of generating one.
482    pub fn set_scheme(scheme: Scheme, dark: bool, cx: &mut App) {
483        cx.set_global(Theme {
484            scheme,
485            dark,
486            seed: None,
487        });
488        cx.refresh_windows();
489    }
490
491    /// Changes the theme and redraws every window.
492    pub fn set(dark: bool, seed: Option<Hsla>, cx: &mut App) {
493        cx.set_global(Theme::new(dark, seed));
494        cx.refresh_windows();
495    }
496
497    /// Uses `scheme` for the components of one window while it draws, without changing the
498    /// app's theme for the others (the theme is a single global). Call it at the start of the
499    /// root view's `render` and add the returned element as the root's last child: it puts the
500    /// previous theme back after the window has painted.
501    ///
502    /// ```ignore
503    /// fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
504    ///     let restore = Theme::scoped(Scheme::baseline_dark(), true, cx);
505    ///     div().child(Button::new("ok", "OK")).child(restore)
506    /// }
507    /// ```
508    pub fn scoped(scheme: Scheme, dark: bool, cx: &mut App) -> gpui::AnyElement {
509        use gpui::IntoElement as _;
510        let previous = Theme::get(cx);
511        cx.set_global(Theme {
512            scheme,
513            dark,
514            seed: None,
515        });
516        let restore = gpui::canvas(|_, _, _| {}, move |_, _, _, cx| cx.set_global(previous));
517        gpui::deferred(restore)
518            .with_priority(usize::MAX)
519            .into_any_element()
520    }
521}
522
523/// The M3 elevation levels. Higher levels cast a larger, softer shadow.
524///
525/// ```ignore
526/// div().bg(s.surface_container_low).shadow(Elevation::Level2.shadow(&s))
527/// ```
528#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
529pub enum Elevation {
530    /// Flat (0 dp): no shadow.
531    #[default]
532    Level0,
533    /// 1 dp: a resting card.
534    Level1,
535    /// 3 dp: a raised button or a menu bar.
536    Level2,
537    /// 6 dp: a FAB, a menu.
538    Level3,
539    /// 8 dp: a pressed or dragged card.
540    Level4,
541    /// 12 dp: a dialog.
542    Level5,
543}
544
545impl Elevation {
546    pub const ALL: [Elevation; 6] = [
547        Elevation::Level0,
548        Elevation::Level1,
549        Elevation::Level2,
550        Elevation::Level3,
551        Elevation::Level4,
552        Elevation::Level5,
553    ];
554
555    /// The level's distance from the surface, in dp (taken as px).
556    pub fn dp(self) -> f32 {
557        match self {
558            Elevation::Level0 => 0.,
559            Elevation::Level1 => 1.,
560            Elevation::Level2 => 3.,
561            Elevation::Level3 => 6.,
562            Elevation::Level4 => 8.,
563            Elevation::Level5 => 12.,
564        }
565    }
566
567    /// The shadow of this level: a key light that falls straight down and a tighter
568    /// ambient one, in the scheme's shadow color. Level 0 has none.
569    pub fn shadow(self, scheme: &Scheme) -> Vec<BoxShadow> {
570        let dp = self.dp();
571        if dp == 0. {
572            return Vec::new();
573        }
574        vec![
575            BoxShadow {
576                color: scheme.shadow,
577                offset: point(px(0.), px(dp * 0.5)),
578                blur_radius: px(dp * 1.5),
579                spread_radius: px(0.),
580            },
581            BoxShadow {
582                color: alpha(scheme.shadow, 0.7),
583                offset: point(px(0.), px(1.)),
584                blur_radius: px(2. + dp * 0.5),
585                spread_radius: px(0.),
586            },
587        ]
588    }
589}
590
591/// Parses a "#rrggbb" color.
592pub fn hex(value: &str) -> Hsla {
593    Argb::from_str(value)
594        .map(|a| rgb(((a.red as u32) << 16) | ((a.green as u32) << 8) | a.blue as u32).into())
595        .unwrap_or_default()
596}
597
598/// Mixes two colors in sRGB (like `color-mix(in srgb, a t%, b)` with `t` in 0–1).
599pub fn mix(a: Hsla, b: Hsla, t: f32) -> Hsla {
600    let (a, b) = (Rgba::from(a), Rgba::from(b));
601    Rgba {
602        r: a.r * t + b.r * (1. - t),
603        g: a.g * t + b.g * (1. - t),
604        b: a.b * t + b.b * (1. - t),
605        a: a.a * t + b.a * (1. - t),
606    }
607    .into()
608}
609
610/// The same color with a different opacity.
611pub fn alpha(color: Hsla, a: f32) -> Hsla {
612    Hsla {
613        a: color.a * a,
614        ..color
615    }
616}
617
618/// Text sizes used by the reference design with M3 Expressive.
619pub mod text {
620    use super::*;
621
622    pub const BODY: Pixels = px(13.5);
623    pub const LABEL: Pixels = px(12.5);
624    pub const TITLE: Pixels = px(16.);
625    pub const HEADLINE: Pixels = px(22.);
626    pub const DISPLAY: Pixels = px(32.);
627}
628
629/// The M3 type scale (`TypeScaleTokens`), with the Expressive emphasized weights.
630/// Sizes are the spec's sp taken as px.
631pub mod type_scale {
632    use gpui::{FontWeight, Pixels, Styled, px};
633
634    #[derive(Clone, Copy, Debug, PartialEq)]
635    pub struct TypeStyle {
636        pub size: Pixels,
637        pub line_height: Pixels,
638        pub weight: FontWeight,
639        /// The weight of the emphasized variant.
640        pub emphasized: FontWeight,
641    }
642
643    const fn style(size: f32, line: f32, weight: f32, emphasized: f32) -> TypeStyle {
644        TypeStyle {
645            size: px(size),
646            line_height: px(line),
647            weight: FontWeight(weight),
648            emphasized: FontWeight(emphasized),
649        }
650    }
651
652    pub const DISPLAY_LARGE: TypeStyle = style(57., 64., 400., 500.);
653    pub const DISPLAY_MEDIUM: TypeStyle = style(45., 52., 400., 500.);
654    pub const DISPLAY_SMALL: TypeStyle = style(36., 44., 400., 500.);
655    pub const HEADLINE_LARGE: TypeStyle = style(32., 40., 400., 500.);
656    pub const HEADLINE_MEDIUM: TypeStyle = style(28., 36., 400., 500.);
657    pub const HEADLINE_SMALL: TypeStyle = style(24., 32., 400., 500.);
658    pub const TITLE_LARGE: TypeStyle = style(22., 28., 400., 500.);
659    pub const TITLE_MEDIUM: TypeStyle = style(16., 24., 500., 700.);
660    pub const TITLE_SMALL: TypeStyle = style(14., 20., 500., 700.);
661    pub const BODY_LARGE: TypeStyle = style(16., 24., 400., 500.);
662    pub const BODY_MEDIUM: TypeStyle = style(14., 20., 400., 500.);
663    pub const BODY_SMALL: TypeStyle = style(12., 16., 400., 500.);
664    pub const LABEL_LARGE: TypeStyle = style(14., 20., 500., 700.);
665    pub const LABEL_MEDIUM: TypeStyle = style(12., 16., 500., 700.);
666    pub const LABEL_SMALL: TypeStyle = style(11., 16., 500., 700.);
667
668    /// `.type_style(BODY_MEDIUM)` or `.type_emphasized(TITLE_MEDIUM)`.
669    pub trait TypeScaleExt: Styled + Sized {
670        fn type_style(self, style: TypeStyle) -> Self {
671            self.text_size(style.size)
672                .line_height(style.line_height)
673                .font_weight(style.weight)
674        }
675
676        fn type_emphasized(self, style: TypeStyle) -> Self {
677            self.text_size(style.size)
678                .line_height(style.line_height)
679                .font_weight(style.emphasized)
680        }
681    }
682
683    impl<E: Styled> TypeScaleExt for E {}
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    const SEED: &str = "#0b57d0";
691
692    fn close(a: Hsla, b: Hsla) -> bool {
693        (a.h - b.h).abs() < 1e-3 && (a.s - b.s).abs() < 1e-3 && (a.l - b.l).abs() < 1e-3
694    }
695
696    #[test]
697    fn containers_climb_away_from_the_surface() {
698        for dark in [false, true] {
699            for variant in SchemeVariant::ALL {
700                let s = Scheme::from_seed_variant(hex(SEED), dark, variant, 0.);
701                let steps = [
702                    s.surface_container_lowest.l,
703                    s.surface_container_low.l,
704                    s.surface_container.l,
705                    s.surface_container_high.l,
706                    s.surface_container_highest.l,
707                ];
708                for pair in steps.windows(2) {
709                    let ordered = if dark {
710                        pair[0] <= pair[1]
711                    } else {
712                        pair[0] >= pair[1]
713                    };
714                    assert!(ordered, "{variant:?} dark={dark}: {steps:?}");
715                }
716            }
717        }
718    }
719
720    #[test]
721    fn variants_are_different_palettes() {
722        let primary = |variant| Scheme::from_seed_variant(hex(SEED), false, variant, 0.).primary;
723        let tonal = primary(SchemeVariant::TonalSpot);
724        assert!(!close(tonal, primary(SchemeVariant::Vibrant)));
725        assert!(!close(tonal, primary(SchemeVariant::Fidelity)));
726        assert!(
727            primary(SchemeVariant::Monochrome).s < 0.01,
728            "monochrome is gray"
729        );
730        assert!(close(tonal, Scheme::from_seed(hex(SEED), false).primary));
731    }
732
733    #[test]
734    fn more_contrast_separates_the_accent_from_its_content() {
735        let gap = |contrast| {
736            let s = Scheme::from_seed_variant(hex(SEED), false, SchemeVariant::TonalSpot, contrast);
737            (s.on_primary.l - s.primary.l).abs() + (s.on_surface_variant.l - s.surface.l).abs()
738        };
739        assert!(gap(1.) > gap(0.), "{} vs {}", gap(1.), gap(0.));
740        assert!(gap(0.) > gap(-1.), "{} vs {}", gap(0.), gap(-1.));
741    }
742
743    #[test]
744    fn derived_roles_follow_the_polarity_and_keep_the_given_ones() {
745        for (base, dark) in [
746            (Scheme::baseline_light(), false),
747            (Scheme::baseline_dark(), true),
748        ] {
749            let s = base.derive_roles();
750            assert_eq!(s.primary, base.primary);
751            assert_eq!(s.scrim, hsla(0., 0., 0., 1.));
752            assert_eq!(s.inverse_surface, base.on_surface);
753            if dark {
754                assert!(s.surface_dim.l <= s.surface.l && s.surface_bright.l >= s.surface.l);
755                assert!(s.surface_container_lowest.l <= s.surface.l);
756            } else {
757                assert!(s.surface_dim.l <= s.surface.l && s.surface_bright.l >= s.surface.l);
758                assert!(s.surface_container_lowest.l >= s.surface.l);
759            }
760        }
761    }
762
763    #[test]
764    fn each_level_casts_a_larger_shadow() {
765        let s = Scheme::baseline_light();
766        assert!(Elevation::Level0.shadow(&s).is_empty());
767        let reach = |level: Elevation| {
768            let shadows = level.shadow(&s);
769            assert_eq!(shadows.len(), 2);
770            f32::from(shadows[0].blur_radius) + f32::from(shadows[0].offset.y)
771        };
772        for pair in Elevation::ALL[1..].windows(2) {
773            assert!(reach(pair[0]) < reach(pair[1]), "{:?}", pair);
774        }
775    }
776
777    #[test]
778    fn lerp_reaches_the_new_roles() {
779        let (light, dark) = (Scheme::baseline_light(), Scheme::baseline_dark());
780        let end = light.lerp(&dark, 1.);
781        assert!(close(end.inverse_surface, dark.inverse_surface));
782        assert!(close(end.surface_container_low, dark.surface_container_low));
783        assert!(close(end.on_error, dark.on_error));
784    }
785}