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
116fn clean_line(value: SharedString) -> SharedString {
117    if value.contains(['\r', '\n']) {
118        value.replace(['\r', '\n'], " ").into()
119    } else {
120        value
121    }
122}
123
124pub(crate) fn single_line_width(
125    value: &SharedString,
126    style: TypeStyle,
127    tint: Hsla,
128    window: &Window,
129    cx: &App,
130) -> Pixels {
131    let theme = window_material_theme(window, cx);
132    shape_text(
133        clean_line(value.clone()),
134        style,
135        &theme.typography,
136        1.,
137        tint,
138        window,
139        cx,
140    )
141    .expect("single-line text")
142    .line()
143    .width
144    .ceil()
145}
146
147pub(crate) fn single_line(
148    value: SharedString,
149    style: TypeStyle,
150    font_scale: f32,
151    tint: Hsla,
152    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
153    window: &Window,
154    cx: &App,
155) -> gpui::Div {
156    let clean = clean_line(value);
157    let theme = window_material_theme(window, cx);
158    let typography = theme.typography.clone();
159    let align = if theme.layout.direction == Direction::Rtl {
160        TextAlign::Right
161    } else {
162        TextAlign::Left
163    };
164    let shaped = shape_text(
165        clean.clone(),
166        style,
167        &typography,
168        font_scale,
169        tint,
170        window,
171        cx,
172    )
173    .expect("single-line text");
174    let width = shaped.line().width.ceil();
175    let height = shaped.line_height();
176    div()
177        .min_w_0()
178        .w(max_width.map_or(width, |max| width.min(max)) * expansion)
179        .max_w_full()
180        .h(height)
181        .overflow_hidden()
182        .opacity(opacity)
183        .child(
184            canvas(
185                move |bounds, window, cx| {
186                    let maximum = bounds.size.width;
187                    if shaped.line().width <= maximum || expansion < 1. {
188                        return Some(shaped);
189                    }
190                    let shape = |value: SharedString| {
191                        shape_text(value, style, &typography, font_scale, tint, window, cx)
192                            .expect("single-line text")
193                    };
194                    let ellipsis = shape("…".into());
195                    if ellipsis.line().width > maximum {
196                        return None;
197                    }
198                    // Use shaped cluster boundaries to preserve ligatures and combining text.
199                    let mut ends = shaped
200                        .line()
201                        .runs
202                        .iter()
203                        .flat_map(|run| &run.glyphs)
204                        .map(|glyph| glyph.index)
205                        .filter(|&index| clean.is_char_boundary(index))
206                        .collect::<Vec<_>>();
207                    ends.sort_unstable();
208                    ends.dedup();
209                    ends.into_iter()
210                        .rev()
211                        .filter(|&end| end > 0)
212                        .map(|end| shape(format!("{}…", &clean[..end]).into()))
213                        .find(|line| line.line().width <= maximum)
214                        .or(Some(ellipsis))
215                },
216                move |bounds, shaped, window, cx| {
217                    if let Some(shaped) = shaped {
218                        let _ =
219                            shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
220                    }
221                },
222            )
223            .size_full(),
224        )
225}