Skip to main content

gpui_material_theme/
typography.rs

1use crate::{
2    LayoutPolicy,
3    generated::{BASELINE_TYPE_STYLES, EMPHASIZED_TYPE_STYLES},
4};
5
6/// The two Material typeface families.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum Typeface {
9    /// Expressive display and headline typeface (`brand`).
10    Brand,
11    /// Neutral body and UI label typeface (`plain`).
12    Plain,
13}
14
15/// Family preference and ordered fallback for one typeface.
16#[derive(Clone, Debug, PartialEq, Eq)]
17#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
18pub struct FontFamilies {
19    /// Preferred primary font family name (defaults to `"Roboto"`).
20    pub primary: String,
21    /// Ordered fallback font family names tried when [`Self::primary`] is unavailable.
22    pub fallback: Vec<String>,
23}
24
25impl Default for FontFamilies {
26    fn default() -> Self {
27        Self {
28            primary: "Roboto".into(),
29            fallback: [
30                "SF Pro Text",
31                "Segoe UI",
32                "Noto Sans",
33                "PingFang SC",
34                "Microsoft YaHei UI",
35                "Noto Sans CJK SC",
36            ]
37            .map(str::to_owned)
38            .into(),
39        }
40    }
41}
42
43/// One of the fifteen Material text roles.
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum TypeRole {
46    /// Large body copy (`16 sp`).
47    BodyLarge,
48    /// Default body copy (`14 sp`).
49    BodyMedium,
50    /// Small body or supporting copy (`12 sp`).
51    BodySmall,
52    /// Largest display headline (`57 sp`).
53    DisplayLarge,
54    /// Medium display headline (`45 sp`).
55    DisplayMedium,
56    /// Small display headline (`36 sp`).
57    DisplaySmall,
58    /// Large section headline (`32 sp`).
59    HeadlineLarge,
60    /// Medium section headline (`28 sp`).
61    HeadlineMedium,
62    /// Small section headline (`24 sp`).
63    HeadlineSmall,
64    /// Prominent control label (`14 sp`).
65    LabelLarge,
66    /// Standard control label (`12 sp`).
67    LabelMedium,
68    /// Compact label or badge text (`11 sp`).
69    LabelSmall,
70    /// Large title (`22 sp`).
71    TitleLarge,
72    /// Medium title (`16 sp`).
73    TitleMedium,
74    /// Small title (`14 sp`).
75    TitleSmall,
76}
77
78impl TypeRole {
79    /// All 15 Material text roles in stable token order.
80    pub const ALL: [Self; 15] = [
81        Self::BodyLarge,
82        Self::BodyMedium,
83        Self::BodySmall,
84        Self::DisplayLarge,
85        Self::DisplayMedium,
86        Self::DisplaySmall,
87        Self::HeadlineLarge,
88        Self::HeadlineMedium,
89        Self::HeadlineSmall,
90        Self::LabelLarge,
91        Self::LabelMedium,
92        Self::LabelSmall,
93        Self::TitleLarge,
94        Self::TitleMedium,
95        Self::TitleSmall,
96    ];
97
98    /// Returns the unscaled Material [`TypeStyle`] for this role and emphasis level.
99    pub const fn style(self, emphasis: TypographyEmphasis) -> TypeStyle {
100        match emphasis {
101            TypographyEmphasis::Baseline => BASELINE_TYPE_STYLES[self as usize],
102            TypographyEmphasis::Emphasized => EMPHASIZED_TYPE_STYLES[self as usize],
103        }
104    }
105}
106
107/// Emphasis tier for Material 3 Expressive typography.
108#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
109pub enum TypographyEmphasis {
110    /// Standard Material 3 type scale weights (default).
111    #[default]
112    Baseline,
113    /// Heavier Material 3 Expressive emphasized type scale weights.
114    Emphasized,
115}
116
117/// Material type metrics in scale-independent units (sp).
118#[derive(Clone, Copy, Debug, PartialEq)]
119pub struct TypeStyle {
120    /// Logical typeface slot (`Brand` or `Plain`).
121    pub typeface: Typeface,
122    /// Font size in `sp`.
123    pub size: f32,
124    /// Line height in `sp`.
125    pub line_height: f32,
126    /// Letter spacing (tracking) in `sp`.
127    pub tracking: f32,
128    /// Numeric font weight (`100..=900`).
129    pub weight: u16,
130}
131
132/// Family names for the Material scale. The host resolves available fonts
133/// and measures the resulting text.
134#[derive(Clone, Debug, PartialEq)]
135#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
136pub struct Typography {
137    /// Font family stack used for [`Typeface::Brand`] roles.
138    pub brand: FontFamilies,
139    /// Font family stack used for [`Typeface::Plain`] roles.
140    pub plain: FontFamilies,
141    #[cfg_attr(
142        feature = "serde",
143        serde(
144            default = "default_text_scale",
145            deserialize_with = "deserialize_text_scale"
146        )
147    )]
148    text_scale: f32,
149}
150
151impl Default for Typography {
152    fn default() -> Self {
153        Self {
154            brand: FontFamilies::default(),
155            plain: FontFamilies::default(),
156            text_scale: default_text_scale(),
157        }
158    }
159}
160
161impl Typography {
162    /// Sets the theme's text scale. The range is 1.0–2.0, with NaN using 1.0.
163    pub fn with_text_scale(mut self, scale: f32) -> Self {
164        self.text_scale = normalize_text_scale(scale);
165        self
166    }
167
168    /// Returns the active text scale multiplier in `1.0..=2.0`.
169    pub fn text_scale(&self) -> f32 {
170        self.text_scale
171    }
172
173    /// Resolves a Material role using the theme's text scale.
174    pub fn style(&self, role: TypeRole, emphasis: TypographyEmphasis) -> TypeStyle {
175        self.scale_style(role.style(emphasis))
176    }
177
178    /// Scales an unscaled style's size, line height and tracking.
179    pub fn scale_style(&self, style: TypeStyle) -> TypeStyle {
180        LayoutPolicy::scale_text(style, self.text_scale)
181    }
182
183    /// Returns the configured [`FontFamilies`] for a logical [`Typeface`] slot.
184    pub fn families(&self, typeface: Typeface) -> &FontFamilies {
185        match typeface {
186            Typeface::Brand => &self.brand,
187            Typeface::Plain => &self.plain,
188        }
189    }
190}
191
192fn default_text_scale() -> f32 {
193    1.0
194}
195
196fn normalize_text_scale(scale: f32) -> f32 {
197    if scale.is_nan() {
198        default_text_scale()
199    } else {
200        scale.clamp(1.0, 2.0)
201    }
202}
203
204#[cfg(feature = "serde")]
205fn deserialize_text_scale<'de, D: serde::Deserializer<'de>>(
206    deserializer: D,
207) -> Result<f32, D::Error> {
208    <f32 as serde::Deserialize>::deserialize(deserializer).map(normalize_text_scale)
209}