Skip to main content

subspace_dashboard/
typography.rs

1//! Typography roles shared by the app shell and dashboard widgets.
2
3use gpui_kit::component::ActiveTheme as _;
4use gpui_kit::prelude::FluentBuilder;
5use gpui_kit::{App, FontWeight, Global, SharedString, Styled, px};
6
7pub const GROUP_HEADING_SIZE_DEFAULT: f32 = 13.;
8pub const GROUP_HEADING_SIZE_MIN: f32 = 10.;
9pub const GROUP_HEADING_SIZE_MAX: f32 = 24.;
10
11pub fn format_group_heading_size(size: f32) -> String {
12    format!("{size} px")
13}
14
15/// Typography for the title text of a collapsible row group.
16#[derive(Clone, Debug, PartialEq)]
17pub struct GroupHeading {
18    pub font: SharedString,
19    pub size: f32,
20    pub bold: bool,
21    pub italic: bool,
22}
23
24impl Default for GroupHeading {
25    fn default() -> Self {
26        Self {
27            font: SharedString::default(),
28            size: GROUP_HEADING_SIZE_DEFAULT,
29            bold: true,
30            italic: false,
31        }
32    }
33}
34
35/// Font choices that are not represented by GPUI Kit's body and mono roles.
36#[derive(Clone, Default)]
37pub struct Typography {
38    pub heading: SharedString,
39    pub group_heading: GroupHeading,
40}
41
42impl Global for Typography {}
43
44/// The installed family matching `requested`, compared without case.
45pub fn installed_family(requested: &str, installed: &[String]) -> Option<String> {
46    installed
47        .iter()
48        .find(|font| font.eq_ignore_ascii_case(requested))
49        .cloned()
50}
51
52/// The first installed family of a list of requested families, in order.
53///
54/// The Ghostty `font-family` keys are lists: the terminal panel asks for each
55/// family in turn and takes the first the host has installed.
56// qual:api
57pub fn first_installed_family(requested: &[String], installed: &[String]) -> Option<String> {
58    requested
59        .iter()
60        .find_map(|family| installed_family(family, installed))
61}
62
63/// The families a role request names, in order. A request is one family or a
64/// comma-separated list, as in CSS `font-family`, so a theme can ask for a
65/// family some machines lack and name the family to use on those machines.
66fn requested_families(requested: &str) -> Vec<&str> {
67    requested
68        .split(',')
69        .map(str::trim)
70        .filter(|family| !family.is_empty())
71        .collect()
72}
73
74/// The family for one role: the first requested family that is installed,
75/// else `fallback` with a warning naming the role. An empty request is not a
76/// failure; it means the role is unset and takes the fallback silently.
77///
78/// An installed family can itself contain a comma, so the whole request is
79/// matched first. Settings saves the exact installed name, which must keep
80/// matching rather than be read as a list.
81pub fn resolve_role(
82    role: &str,
83    requested: &str,
84    fallback: &str,
85    installed: &[String],
86    warnings: &mut Vec<String>,
87) -> String {
88    let requested = requested.trim();
89    if requested.is_empty() {
90        return fallback.to_owned();
91    }
92    if let Some(font) = installed_family(requested, installed) {
93        return font;
94    }
95    let families = requested_families(requested);
96    if families.is_empty() {
97        return fallback.to_owned();
98    }
99    if let Some(font) = families
100        .iter()
101        .find_map(|family| installed_family(family, installed))
102    {
103        return font;
104    }
105    let missing = match families.as_slice() {
106        [family] => format!("{family} is not installed"),
107        _ => format!("none of {} is installed", families.join(", ")),
108    };
109    warnings.push(format!("{role}: {missing}; using {fallback}"));
110    fallback.to_owned()
111}
112
113/// The heading family, falling back to the active theme's body family.
114pub fn heading_font(cx: &App) -> SharedString {
115    cx.try_global::<Typography>()
116        .map(|typography| typography.heading.clone())
117        .filter(|heading| !heading.is_empty())
118        .unwrap_or_else(|| cx.theme().font_family.clone())
119}
120
121/// Applies the group-heading role without affecting adjacent icons or counts.
122pub fn group_heading<T: Styled + FluentBuilder>(element: T, cx: &App) -> T {
123    let style = cx
124        .try_global::<Typography>()
125        .map(|typography| typography.group_heading.clone())
126        .unwrap_or_default();
127    let font = if style.font.is_empty() {
128        heading_font(cx)
129    } else {
130        style.font
131    };
132    element
133        .font_family(font)
134        .text_size(px(style.size))
135        .font_weight(if style.bold {
136            FontWeight::BOLD
137        } else {
138            FontWeight::NORMAL
139        })
140        .when(style.italic, |element| element.italic())
141}
142
143#[cfg(test)]
144mod tests {
145    use super::{
146        GroupHeading, first_installed_family, format_group_heading_size, installed_family,
147        resolve_role,
148    };
149
150    #[test]
151    fn an_installed_family_matches_without_case() {
152        let installed = ["Inter".to_owned(), "Arial".to_owned()];
153
154        assert_eq!(
155            installed_family("inter", &installed),
156            Some("Inter".to_owned())
157        );
158        assert_eq!(installed_family("Missing Sans", &installed), None);
159    }
160
161    #[test]
162    fn a_family_list_takes_the_first_installed_family() {
163        let installed = ["Menlo".to_owned(), "Arial".to_owned()];
164        let requested = ["Missing Mono".to_owned(), "menlo".to_owned()];
165
166        assert_eq!(
167            first_installed_family(&requested, &installed),
168            Some("Menlo".to_owned())
169        );
170        assert_eq!(first_installed_family(&[], &installed), None);
171    }
172
173    /// One `resolve_role` request: the request, the family it resolves to and
174    /// the warning it adds, if any.
175    struct RoleCase {
176        requested: &'static str,
177        family: &'static str,
178        warning: Option<&'static str>,
179    }
180
181    const ROLE_CASES: [RoleCase; 12] = [
182        // An unset role takes the fallback silently.
183        RoleCase {
184            requested: "",
185            family: "Menlo",
186            warning: None,
187        },
188        // A single family matches without case, as before.
189        RoleCase {
190            requested: "example sans",
191            family: "Example Sans",
192            warning: None,
193        },
194        // A missing single family keeps the existing warning.
195        RoleCase {
196            requested: "Missing Mono",
197            family: "Menlo",
198            warning: Some("Code: Missing Mono is not installed; using Menlo"),
199        },
200        // An installed family can contain a comma, so the whole request
201        // matches before it is read as a list.
202        RoleCase {
203            requested: "Example, Serif",
204            family: "Example, Serif",
205            warning: None,
206        },
207        RoleCase {
208            requested: " example, serif ",
209            family: "Example, Serif",
210            warning: None,
211        },
212        // A request that is not an installed family is still read as a list.
213        RoleCase {
214            requested: "Example, Serif, Example Sans",
215            family: "Example Sans",
216            warning: None,
217        },
218        // A list takes its first installed family, wherever it is.
219        RoleCase {
220            requested: "Missing Display, example sans",
221            family: "Example Sans",
222            warning: None,
223        },
224        RoleCase {
225            requested: "Menlo,Example Sans",
226            family: "Menlo",
227            warning: None,
228        },
229        // Spaces around families and empty entries are ignored.
230        RoleCase {
231            requested: ", Missing Mono ,, example sans ,",
232            family: "Example Sans",
233            warning: None,
234        },
235        // A list that reduces to one family uses the single-family warning.
236        RoleCase {
237            requested: " Missing Mono , ,",
238            family: "Menlo",
239            warning: Some("Code: Missing Mono is not installed; using Menlo"),
240        },
241        // A list with no installed family warns once and names the list.
242        RoleCase {
243            requested: "Missing Sans, Missing Display",
244            family: "Menlo",
245            warning: Some("Code: none of Missing Sans, Missing Display is installed; using Menlo"),
246        },
247        // A blank list is unset.
248        RoleCase {
249            requested: " , ",
250            family: "Menlo",
251            warning: None,
252        },
253    ];
254
255    #[test]
256    fn a_role_takes_the_first_installed_family_it_requests() {
257        let installed = ["Example, Serif", "Example Sans", "Menlo"].map(str::to_owned);
258
259        for case in &ROLE_CASES {
260            let mut warnings = Vec::new();
261            let family = resolve_role("Code", case.requested, "Menlo", &installed, &mut warnings);
262
263            assert_eq!(family, case.family, "{:?}", case.requested);
264            assert_eq!(warnings, case.warning.as_slice(), "{:?}", case.requested);
265        }
266    }
267
268    #[test]
269    fn group_heading_defaults_and_sizes_are_stable() {
270        let style = GroupHeading::default();
271        assert_eq!(style.size, 13.0);
272        assert!(style.bold);
273        assert!(!style.italic);
274        assert_eq!(format_group_heading_size(style.size), "13 px");
275        assert_eq!(format_group_heading_size(14.5), "14.5 px");
276    }
277}