Skip to main content

fc_ui/capabilities/primitives/
text.rs

1//! Text component - Typography with theming and semantic variants.
2
3use crate::capabilities::foundation::theme::use_theme;
4use gpui::{prelude::FluentBuilder as _, *};
5
6/// Text variants for semantic typography
7#[derive(Copy, Clone, Debug, PartialEq, Eq)]
8pub enum TextVariant {
9    /// Extra large heading (32px, bold)
10    H1,
11    /// Large heading (28px, semibold)
12    H2,
13    /// Medium heading (24px, semibold)
14    H3,
15    /// Small heading (20px, semibold)
16    H4,
17    /// Extra small heading (18px, medium)
18    H5,
19    /// Tiny heading (16px, medium)
20    H6,
21    /// Body text - large (16px, regular)
22    BodyLarge,
23    /// Body text - default (14px, regular)
24    Body,
25    /// Body text - small (13px, regular)
26    BodySmall,
27    /// Caption text (12px, regular)
28    Caption,
29    /// Label text (14px, medium)
30    Label,
31    /// Label text - small (12px, medium)
32    LabelSmall,
33    /// Code/monospace text (14px, mono font)
34    Code,
35    /// Code/monospace - small (12px, mono font)
36    CodeSmall,
37    /// Custom - use size(), weight(), etc. for full control
38    Custom,
39}
40
41impl TextVariant {
42    /// Get the text size for this variant
43    pub fn size(&self) -> Pixels {
44        match self {
45            Self::H1 => px(32.0),
46            Self::H2 => px(28.0),
47            Self::H3 => px(24.0),
48            Self::H4 => px(20.0),
49            Self::H5 => px(18.0),
50            Self::H6 => px(16.0),
51            Self::BodyLarge => px(16.0),
52            Self::Body => px(14.0),
53            Self::BodySmall => px(13.0),
54            Self::Caption => px(12.0),
55            Self::Label => px(14.0),
56            Self::LabelSmall => px(12.0),
57            Self::Code => px(14.0),
58            Self::CodeSmall => px(12.0),
59            Self::Custom => px(14.0), // Default for custom
60        }
61    }
62
63    /// Get the font weight for this variant
64    pub fn weight(&self) -> FontWeight {
65        match self {
66            Self::H1 => FontWeight::BOLD,
67            Self::H2 | Self::H3 | Self::H4 => FontWeight::SEMIBOLD,
68            Self::H5 | Self::H6 | Self::Label | Self::LabelSmall => FontWeight::MEDIUM,
69            Self::BodyLarge | Self::Body | Self::BodySmall | Self::Caption => FontWeight::NORMAL,
70            Self::Code | Self::CodeSmall => FontWeight::NORMAL,
71            Self::Custom => FontWeight::NORMAL,
72        }
73    }
74
75    /// Check if this variant uses monospace font
76    pub fn is_mono(&self) -> bool {
77        matches!(self, Self::Code | Self::CodeSmall)
78    }
79
80    /// Get line height multiplier for this variant
81    pub fn line_height(&self) -> f32 {
82        match self {
83            Self::H1 | Self::H2 | Self::H3 | Self::H4 => 1.2,
84            Self::H5 | Self::H6 => 1.3,
85            Self::BodyLarge | Self::Body | Self::BodySmall => 1.5,
86            Self::Caption | Self::Label | Self::LabelSmall => 1.4,
87            Self::Code | Self::CodeSmall => 1.6,
88            Self::Custom => 1.5,
89        }
90    }
91}
92
93/// Text component with automatic theming and typography
94#[derive(IntoElement)]
95pub struct Text {
96    content: SharedString,
97    variant: TextVariant,
98    size: Option<Pixels>,
99    weight: Option<FontWeight>,
100    color: Option<Hsla>,
101    muted: bool,
102    font: Option<SharedString>,
103    line_height: Option<f32>,
104    italic: bool,
105    underline: bool,
106    strikethrough: bool,
107    wrap: bool,
108    truncate: bool,
109    style: StyleRefinement,
110}
111
112impl Text {
113    /// Create new text with content
114    pub fn new<S: Into<SharedString>>(content: S) -> Self {
115        Self {
116            content: content.into(),
117            variant: TextVariant::Body,
118            size: None,
119            weight: None,
120            color: None,
121            muted: false,
122            font: None,
123            line_height: None,
124            italic: false,
125            underline: false,
126            strikethrough: false,
127            wrap: true,
128            truncate: false,
129            style: StyleRefinement::default(),
130        }
131    }
132
133    /// Set the text variant (heading, body, etc.)
134    pub fn variant(mut self, variant: TextVariant) -> Self {
135        self.variant = variant;
136        self
137    }
138
139    /// Set custom font size (overrides variant size)
140    pub fn size(mut self, size: Pixels) -> Self {
141        self.size = Some(size);
142        self
143    }
144
145    /// Set custom font weight (overrides variant weight)
146    pub fn weight(mut self, weight: FontWeight) -> Self {
147        self.weight = Some(weight);
148        self
149    }
150
151    /// Set text color (overrides theme foreground)
152    pub fn color(mut self, color: Hsla) -> Self {
153        self.color = Some(color);
154        self
155    }
156
157    /// Use the current theme's muted foreground color.
158    pub fn muted(mut self) -> Self {
159        self.muted = true;
160        self
161    }
162
163    /// Set custom font family (overrides theme font)
164    pub fn font(mut self, font: impl Into<SharedString>) -> Self {
165        self.font = Some(font.into());
166        self
167    }
168
169    /// Set custom line height multiplier
170    pub fn line_height(mut self, line_height: f32) -> Self {
171        self.line_height = Some(line_height);
172        self
173    }
174
175    /// Make text italic
176    pub fn italic(mut self) -> Self {
177        self.italic = true;
178        self
179    }
180
181    /// Add underline
182    pub fn underline(mut self) -> Self {
183        self.underline = true;
184        self
185    }
186
187    /// Add strikethrough
188    pub fn strikethrough(mut self) -> Self {
189        self.strikethrough = true;
190        self
191    }
192
193    /// Disable text wrapping (single line)
194    pub fn no_wrap(mut self) -> Self {
195        self.wrap = false;
196        self
197    }
198
199    /// Enable text truncation with ellipsis
200    pub fn truncate(mut self) -> Self {
201        self.truncate = true;
202        self.wrap = false; // Truncate requires no wrap
203        self
204    }
205
206    /// Get the effective text size
207    fn effective_size(&self) -> Pixels {
208        self.size.unwrap_or_else(|| self.variant.size())
209    }
210
211    /// Get the effective font weight
212    fn effective_weight(&self) -> FontWeight {
213        self.weight.unwrap_or_else(|| self.variant.weight())
214    }
215
216    /// Get the effective line height
217    fn effective_line_height(&self) -> f32 {
218        self.line_height
219            .unwrap_or_else(|| self.variant.line_height())
220    }
221}
222
223impl Styled for Text {
224    fn style(&mut self) -> &mut StyleRefinement {
225        &mut self.style
226    }
227}
228
229impl RenderOnce for Text {
230    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
231        let theme = use_theme(cx);
232
233        let size = self.effective_size();
234        let weight = self.effective_weight();
235        let line_height = self.effective_line_height();
236
237        let font_family = if let Some(font) = self.font {
238            font
239        } else if self.variant.is_mono() {
240            theme.tokens.font_mono.clone()
241        } else {
242            theme.tokens.font_family.clone()
243        };
244
245        let text_color = self.color.unwrap_or({
246            if self.muted {
247                theme.tokens.muted_foreground
248            } else {
249                theme.tokens.foreground
250            }
251        });
252
253        let mut base = div();
254        *base.style() = self.style;
255
256        let needs_highlights = self.italic || self.strikethrough;
257        let styled_text = if needs_highlights {
258            let mut highlight_style = HighlightStyle::default();
259
260            if self.italic {
261                highlight_style.font_style = Some(FontStyle::Italic);
262            }
263            if self.strikethrough {
264                highlight_style.strikethrough = Some(StrikethroughStyle {
265                    color: Some(text_color),
266                    thickness: px(1.0),
267                });
268            }
269
270            let text_len = self.content.len();
271            StyledText::new(self.content.clone())
272                .with_highlights(vec![(0..text_len, highlight_style)])
273        } else {
274            StyledText::new(self.content.clone())
275        };
276
277        base.font_family(font_family)
278            .text_size(size)
279            .font_weight(weight)
280            .text_color(text_color)
281            .line_height(relative(line_height))
282            .when(self.underline, |this| this.underline())
283            .when(!self.wrap, |this| this.whitespace_nowrap())
284            .when(self.truncate, |this| this.overflow_hidden().text_ellipsis())
285            .child(styled_text)
286    }
287}
288
289/// Create heading 1 text
290pub fn h1<S: Into<SharedString>>(content: S) -> Text {
291    Text::new(content).variant(TextVariant::H1)
292}
293
294/// Create heading 2 text
295pub fn h2<S: Into<SharedString>>(content: S) -> Text {
296    Text::new(content).variant(TextVariant::H2)
297}
298
299/// Create heading 3 text
300pub fn h3<S: Into<SharedString>>(content: S) -> Text {
301    Text::new(content).variant(TextVariant::H3)
302}
303
304/// Create heading 4 text
305pub fn h4<S: Into<SharedString>>(content: S) -> Text {
306    Text::new(content).variant(TextVariant::H4)
307}
308
309/// Create heading 5 text
310pub fn h5<S: Into<SharedString>>(content: S) -> Text {
311    Text::new(content).variant(TextVariant::H5)
312}
313
314/// Create heading 6 text
315pub fn h6<S: Into<SharedString>>(content: S) -> Text {
316    Text::new(content).variant(TextVariant::H6)
317}
318
319/// Create body text (default)
320pub fn body<S: Into<SharedString>>(content: S) -> Text {
321    Text::new(content).variant(TextVariant::Body)
322}
323
324/// Create large body text
325pub fn body_large<S: Into<SharedString>>(content: S) -> Text {
326    Text::new(content).variant(TextVariant::BodyLarge)
327}
328
329/// Create small body text
330pub fn body_small<S: Into<SharedString>>(content: S) -> Text {
331    Text::new(content).variant(TextVariant::BodySmall)
332}
333
334/// Create caption text
335pub fn caption<S: Into<SharedString>>(content: S) -> Text {
336    Text::new(content).variant(TextVariant::Caption)
337}
338
339/// Create label text
340pub fn label<S: Into<SharedString>>(content: S) -> Text {
341    Text::new(content).variant(TextVariant::Label)
342}
343
344/// Create small label text
345pub fn label_small<S: Into<SharedString>>(content: S) -> Text {
346    Text::new(content).variant(TextVariant::LabelSmall)
347}
348
349/// Create code/monospace text
350pub fn code<S: Into<SharedString>>(content: S) -> Text {
351    Text::new(content).variant(TextVariant::Code)
352}
353
354/// Create small code text
355pub fn code_small<S: Into<SharedString>>(content: S) -> Text {
356    Text::new(content).variant(TextVariant::CodeSmall)
357}
358
359/// Create muted text (secondary color)
360pub fn muted<S: Into<SharedString>>(content: S) -> Text {
361    Text::new(content).variant(TextVariant::Body).muted()
362}
363
364/// Create muted small text
365pub fn muted_small<S: Into<SharedString>>(content: S) -> Text {
366    Text::new(content).variant(TextVariant::BodySmall).muted()
367}
368
369#[cfg(test)]
370mod tests {
371    use super::Text;
372    use gpui::{div, point, px, size, AvailableSpace, IntoElement, TestAppContext};
373
374    const LONG_TEXT: &str =
375        "A long customer-facing label whose natural width must survive truncation";
376
377    #[gpui::test]
378    fn truncated_text_recomputes_its_natural_width_after_a_constrained_measurement(
379        cx: &mut TestAppContext,
380    ) {
381        let cx = cx.add_empty_window();
382        let mut measurements = None;
383        cx.draw(
384            point(px(0.0), px(0.0)),
385            size(px(800.0), px(600.0)),
386            |window, cx| {
387                let mut text = Text::new(LONG_TEXT).truncate().into_any_element();
388                let constrained = text.layout_as_root(
389                    size(
390                        AvailableSpace::Definite(px(96.0)),
391                        AvailableSpace::MaxContent,
392                    ),
393                    window,
394                    cx,
395                );
396                let unconstrained = text.layout_as_root(
397                    size(AvailableSpace::MaxContent, AvailableSpace::MaxContent),
398                    window,
399                    cx,
400                );
401                measurements = Some((constrained, unconstrained));
402                div()
403            },
404        );
405        let (constrained, unconstrained) =
406            measurements.expect("both text measurements should complete");
407
408        assert!(
409            unconstrained.width > constrained.width,
410            "an unconstrained measurement must not reuse the truncated width"
411        );
412    }
413}