Skip to main content

gpui_material_components/
text.rs

1use gpui::{
2    App, ElementId, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels, RenderOnce, Role,
3    SharedString, StatefulInteractiveElement, Styled, TextAlign, Window, canvas, div, px,
4};
5use gpui_base::TestSupportExt;
6use gpui_material_foundation::{color, shape_text, window_material_theme, wrapped_text};
7use gpui_material_theme::{ColorRole, Direction, TypeRole, TypeStyle, TypographyEmphasis};
8
9/// Single-line Material text. Measurement and painting share Foundation's
10/// shaped glyphs, including font fallback and letter spacing.
11#[derive(IntoElement)]
12pub struct Text {
13    value: SharedString,
14    id: Option<ElementId>,
15    role: TypeRole,
16    emphasis: TypographyEmphasis,
17    font_scale: f32,
18    color: Option<ColorRole>,
19    max_width: Option<gpui::Pixels>,
20    wrap: bool,
21}
22
23impl Text {
24    pub fn new(value: impl Into<SharedString>) -> Self {
25        Self {
26            value: value.into(),
27            id: None,
28            role: TypeRole::BodyLarge,
29            emphasis: TypographyEmphasis::Baseline,
30            font_scale: 1.,
31            color: None,
32            max_width: None,
33            wrap: false,
34        }
35    }
36
37    /// Supplies a stable ID for this label within its parent.
38    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
39        self.id = Some(id.into());
40        self
41    }
42
43    pub fn role(mut self, role: TypeRole) -> Self {
44        self.role = role;
45        self
46    }
47
48    pub fn emphasized(mut self, emphasized: bool) -> Self {
49        self.emphasis = if emphasized {
50            TypographyEmphasis::Emphasized
51        } else {
52            TypographyEmphasis::Baseline
53        };
54        self
55    }
56
57    pub fn font_scale(mut self, scale: f32) -> Self {
58        self.font_scale = scale;
59        self
60    }
61
62    pub fn color(mut self, role: ColorRole) -> Self {
63        self.color = Some(role);
64        self
65    }
66
67    pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
68        self.max_width = Some(max_width.max(px(0.)));
69        self.wrap = false;
70        self
71    }
72
73    /// Wraps at the available width and preserves explicit line breaks.
74    /// This uses GPUI's native Unicode layout, whose pinned version does not
75    /// expose custom tracking for wrapped text. Single-line text retains tracking.
76    pub fn wrap(mut self) -> Self {
77        self.wrap = true;
78        self.max_width = None;
79        self
80    }
81}
82
83impl RenderOnce for Text {
84    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
85        let tint = self.color.map_or_else(
86            || window.text_style().color,
87            |role| color(window_material_theme(window, cx).colors.color(role)),
88        );
89        let text = if self.wrap {
90            wrapped_text(
91                self.value.clone(),
92                self.role.style(self.emphasis),
93                self.font_scale,
94                tint,
95                window,
96                cx,
97            )
98        } else {
99            single_line(
100                self.value.clone(),
101                self.role.style(self.emphasis),
102                self.font_scale,
103                tint,
104                (self.max_width, 1., 1.),
105                window,
106                cx,
107            )
108        };
109        text.id(self.id.unwrap_or_else(|| "material-text".into()))
110            .test_support()
111            .role(Role::Label)
112            .aria_label(self.value)
113    }
114}
115
116pub(crate) fn single_line(
117    value: SharedString,
118    style: TypeStyle,
119    font_scale: f32,
120    tint: Hsla,
121    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
122    window: &Window,
123    cx: &App,
124) -> gpui::Div {
125    let clean = if value.contains(['\r', '\n']) {
126        SharedString::from(value.replace(['\r', '\n'], " "))
127    } else {
128        value
129    };
130    let theme = window_material_theme(window, cx);
131    let typography = theme.typography.clone();
132    let align = if theme.layout.direction == Direction::Rtl {
133        TextAlign::Right
134    } else {
135        TextAlign::Left
136    };
137    let shaped = shape_text(
138        clean.clone(),
139        style,
140        &typography,
141        font_scale,
142        tint,
143        window,
144        cx,
145    )
146    .expect("single-line text");
147    let width = shaped.line().width.ceil();
148    let height = shaped.line_height();
149    div()
150        .min_w_0()
151        .w(max_width.map_or(width, |max| width.min(max)) * expansion)
152        .max_w_full()
153        .h(height)
154        .overflow_hidden()
155        .opacity(opacity)
156        .child(
157            canvas(
158                move |bounds, window, cx| {
159                    let maximum = bounds.size.width;
160                    if shaped.line().width <= maximum || expansion < 1. {
161                        return Some(shaped);
162                    }
163                    let shape = |value: SharedString| {
164                        shape_text(value, style, &typography, font_scale, tint, window, cx)
165                            .expect("single-line text")
166                    };
167                    let ellipsis = shape("…".into());
168                    if ellipsis.line().width > maximum {
169                        return None;
170                    }
171                    // Use shaped cluster boundaries to preserve ligatures and combining text.
172                    let mut ends = shaped
173                        .line()
174                        .runs
175                        .iter()
176                        .flat_map(|run| &run.glyphs)
177                        .map(|glyph| glyph.index)
178                        .filter(|&index| clean.is_char_boundary(index))
179                        .collect::<Vec<_>>();
180                    ends.sort_unstable();
181                    ends.dedup();
182                    ends.into_iter()
183                        .rev()
184                        .filter(|&end| end > 0)
185                        .map(|end| shape(format!("{}…", &clean[..end]).into()))
186                        .find(|line| line.line().width <= maximum)
187                        .or(Some(ellipsis))
188                },
189                move |bounds, shaped, window, cx| {
190                    if let Some(shaped) = shaped {
191                        let _ =
192                            shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
193                    }
194                },
195            )
196            .size_full(),
197        )
198}