Skip to main content

gpui_material_theme/
typography.rs

1use std::sync::{Arc, LazyLock};
2
3use crate::{
4    LayoutPolicy,
5    generated::{BASELINE_TYPE_STYLES, EMPHASIZED_TYPE_STYLES},
6};
7
8/// The two Material typeface families.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum Typeface {
11    /// Expressive display and headline typeface (`brand`).
12    Brand,
13    /// Neutral body and UI label typeface (`plain`).
14    Plain,
15}
16
17/// Family preference and ordered fallback for one typeface.
18///
19/// Uses shared [`Arc<str>`] storage so cloning [`crate::MaterialTheme`] does not
20/// allocate on the heap.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct FontFamilies {
23    /// Preferred primary font family name (defaults to `"Roboto"`).
24    pub primary: Arc<str>,
25    /// Ordered fallback font family names tried when [`Self::primary`] is unavailable.
26    pub fallback: Arc<[Arc<str>]>,
27}
28
29impl FontFamilies {
30    /// Creates a font family stack from a primary family and ordered fallbacks.
31    pub fn new(
32        primary: impl Into<Arc<str>>,
33        fallback: impl IntoIterator<Item = impl Into<Arc<str>>>,
34    ) -> Self {
35        Self {
36            primary: primary.into(),
37            fallback: fallback.into_iter().map(Into::into).collect(),
38        }
39    }
40
41    /// Replaces the preferred primary font family name.
42    pub fn with_primary(mut self, primary: impl Into<Arc<str>>) -> Self {
43        self.primary = primary.into();
44        self
45    }
46
47    /// Replaces the ordered fallback font family names.
48    pub fn with_fallback(
49        mut self,
50        fallback: impl IntoIterator<Item = impl Into<Arc<str>>>,
51    ) -> Self {
52        self.fallback = fallback.into_iter().map(Into::into).collect();
53        self
54    }
55}
56
57impl Default for FontFamilies {
58    fn default() -> Self {
59        static DEFAULT: LazyLock<FontFamilies> = LazyLock::new(|| {
60            FontFamilies::new(
61                "Roboto",
62                [
63                    "SF Pro Text",
64                    "Segoe UI",
65                    "Noto Sans",
66                    "PingFang SC",
67                    "Microsoft YaHei UI",
68                    "Noto Sans CJK SC",
69                ],
70            )
71        });
72        DEFAULT.clone()
73    }
74}
75
76#[cfg(feature = "serde")]
77impl serde::Serialize for FontFamilies {
78    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
79        #[derive(serde::Serialize)]
80        #[serde(rename = "FontFamilies")]
81        struct SerializedFontFamilies<'a> {
82            primary: &'a str,
83            fallback: Vec<&'a str>,
84        }
85
86        SerializedFontFamilies {
87            primary: self.primary.as_ref(),
88            fallback: self.fallback.iter().map(Arc::as_ref).collect(),
89        }
90        .serialize(serializer)
91    }
92}
93
94#[cfg(feature = "serde")]
95impl<'de> serde::Deserialize<'de> for FontFamilies {
96    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
97        #[derive(serde::Deserialize)]
98        #[serde(rename = "FontFamilies")]
99        struct SerializedFontFamilies {
100            primary: String,
101            fallback: Vec<String>,
102        }
103
104        let raw = SerializedFontFamilies::deserialize(deserializer)?;
105        Ok(Self::new(raw.primary, raw.fallback))
106    }
107}
108
109/// One of the fifteen Material text roles.
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub enum TypeRole {
112    /// Large body copy (`16 sp`).
113    BodyLarge,
114    /// Default body copy (`14 sp`).
115    BodyMedium,
116    /// Small body or supporting copy (`12 sp`).
117    BodySmall,
118    /// Largest display headline (`57 sp`).
119    DisplayLarge,
120    /// Medium display headline (`45 sp`).
121    DisplayMedium,
122    /// Small display headline (`36 sp`).
123    DisplaySmall,
124    /// Large section headline (`32 sp`).
125    HeadlineLarge,
126    /// Medium section headline (`28 sp`).
127    HeadlineMedium,
128    /// Small section headline (`24 sp`).
129    HeadlineSmall,
130    /// Prominent control label (`14 sp`).
131    LabelLarge,
132    /// Standard control label (`12 sp`).
133    LabelMedium,
134    /// Compact label or badge text (`11 sp`).
135    LabelSmall,
136    /// Large title (`22 sp`).
137    TitleLarge,
138    /// Medium title (`16 sp`).
139    TitleMedium,
140    /// Small title (`14 sp`).
141    TitleSmall,
142}
143
144impl TypeRole {
145    /// All 15 Material text roles in stable token order.
146    pub const ALL: [Self; 15] = [
147        Self::BodyLarge,
148        Self::BodyMedium,
149        Self::BodySmall,
150        Self::DisplayLarge,
151        Self::DisplayMedium,
152        Self::DisplaySmall,
153        Self::HeadlineLarge,
154        Self::HeadlineMedium,
155        Self::HeadlineSmall,
156        Self::LabelLarge,
157        Self::LabelMedium,
158        Self::LabelSmall,
159        Self::TitleLarge,
160        Self::TitleMedium,
161        Self::TitleSmall,
162    ];
163
164    /// Returns the unscaled Material [`TypeStyle`] for this role and emphasis level.
165    pub const fn style(self, emphasis: TypographyEmphasis) -> TypeStyle {
166        match emphasis {
167            TypographyEmphasis::Baseline => BASELINE_TYPE_STYLES[self as usize],
168            TypographyEmphasis::Emphasized => EMPHASIZED_TYPE_STYLES[self as usize],
169        }
170    }
171}
172
173/// Emphasis tier for Material 3 Expressive typography.
174#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
175pub enum TypographyEmphasis {
176    /// Standard Material 3 type scale weights (default).
177    #[default]
178    Baseline,
179    /// Heavier Material 3 Expressive emphasized type scale weights.
180    Emphasized,
181}
182
183/// Material type metrics in scale-independent units (sp).
184#[derive(Clone, Copy, Debug, PartialEq)]
185pub struct TypeStyle {
186    /// Logical typeface slot (`Brand` or `Plain`).
187    pub typeface: Typeface,
188    /// Font size in `sp`.
189    pub size: f32,
190    /// Line height in `sp`.
191    pub line_height: f32,
192    /// Letter spacing (tracking) in `sp`.
193    pub tracking: f32,
194    /// Numeric font weight (`100..=900`).
195    pub weight: u16,
196}
197
198/// Family names for the Material scale. The host resolves available fonts
199/// and measures the resulting text.
200#[derive(Clone, Debug, PartialEq)]
201#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
202pub struct Typography {
203    /// Font family stack used for [`Typeface::Brand`] roles.
204    pub brand: FontFamilies,
205    /// Font family stack used for [`Typeface::Plain`] roles.
206    pub plain: FontFamilies,
207    #[cfg_attr(
208        feature = "serde",
209        serde(
210            default = "default_text_scale",
211            deserialize_with = "deserialize_text_scale"
212        )
213    )]
214    text_scale: f32,
215}
216
217impl Default for Typography {
218    fn default() -> Self {
219        Self {
220            brand: FontFamilies::default(),
221            plain: FontFamilies::default(),
222            text_scale: default_text_scale(),
223        }
224    }
225}
226
227impl Typography {
228    /// Sets the theme's text scale. The range is 1.0–2.0, with NaN using 1.0.
229    pub fn with_text_scale(mut self, scale: f32) -> Self {
230        self.text_scale = normalize_text_scale(scale);
231        self
232    }
233
234    /// Returns the active text scale multiplier in `1.0..=2.0`.
235    pub fn text_scale(&self) -> f32 {
236        self.text_scale
237    }
238
239    /// Resolves a Material role using the theme's text scale.
240    pub fn style(&self, role: TypeRole, emphasis: TypographyEmphasis) -> TypeStyle {
241        self.scale_style(role.style(emphasis))
242    }
243
244    /// Scales an unscaled style's size, line height and tracking.
245    pub fn scale_style(&self, style: TypeStyle) -> TypeStyle {
246        LayoutPolicy::scale_text(style, self.text_scale)
247    }
248
249    /// Returns the configured [`FontFamilies`] for a logical [`Typeface`] slot.
250    pub fn families(&self, typeface: Typeface) -> &FontFamilies {
251        match typeface {
252            Typeface::Brand => &self.brand,
253            Typeface::Plain => &self.plain,
254        }
255    }
256}
257
258fn default_text_scale() -> f32 {
259    1.0
260}
261
262fn normalize_text_scale(scale: f32) -> f32 {
263    if scale.is_nan() {
264        default_text_scale()
265    } else {
266        scale.clamp(1.0, 2.0)
267    }
268}
269
270#[cfg(feature = "serde")]
271fn deserialize_text_scale<'de, D: serde::Deserializer<'de>>(
272    deserializer: D,
273) -> Result<f32, D::Error> {
274    <f32 as serde::Deserialize>::deserialize(deserializer).map(normalize_text_scale)
275}