Skip to main content

gpui_material_components/
text.rs

1use std::{
2    cell::RefCell,
3    hash::{DefaultHasher, Hash, Hasher},
4    rc::Rc,
5};
6
7use gpui::{
8    App, ElementId, Global, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
9    RenderOnce, Role, SharedString, StatefulInteractiveElement, Styled, TextAlign, Window, canvas,
10    div, px,
11};
12use gpui_base::TestSupportExt;
13use gpui_material_foundation::{
14    ShapedText, color, font_cache_revision, shape_text, window_material_theme, wrapped_text,
15};
16use gpui_material_theme::{
17    ColorRole, Direction, TypeRole, TypeStyle, Typography, TypographyEmphasis,
18};
19
20const ELLIPSIS_CACHE_SLOTS: usize = 256;
21const ELLIPSIS_CACHE_MAX_BYTES: usize = 1024;
22
23#[derive(PartialEq)]
24struct EllipsisKey {
25    text: SharedString,
26    width: Pixels,
27    style: TypeStyle,
28    typography: Typography,
29    font_scale: f32,
30    scale_factor: f32,
31    font_revision: u64,
32    tint: Hsla,
33}
34
35impl EllipsisKey {
36    fn slot(&self) -> usize {
37        let mut hasher = DefaultHasher::new();
38        self.text.hash(&mut hasher);
39        f32::from(self.width).to_bits().hash(&mut hasher);
40        hasher.finish() as usize % ELLIPSIS_CACHE_SLOTS
41    }
42}
43
44type EllipsisEntry = (EllipsisKey, Option<Rc<ShapedText>>);
45
46struct EllipsisCache(RefCell<Vec<Option<EllipsisEntry>>>);
47
48impl Global for EllipsisCache {}
49
50impl Default for EllipsisCache {
51    fn default() -> Self {
52        Self(RefCell::new(
53            std::iter::repeat_with(|| None)
54                .take(ELLIPSIS_CACHE_SLOTS)
55                .collect(),
56        ))
57    }
58}
59
60impl EllipsisCache {
61    fn get_or_shape(
62        &self,
63        key: EllipsisKey,
64        shape: impl FnOnce(&EllipsisKey) -> Option<ShapedText>,
65    ) -> Option<Rc<ShapedText>> {
66        if key.text.len() > ELLIPSIS_CACHE_MAX_BYTES {
67            return shape(&key).map(Rc::new);
68        }
69        let slot = key.slot();
70        if let Some((stored, result)) = &self.0.borrow()[slot]
71            && *stored == key
72        {
73            return result.clone();
74        }
75        let result = shape(&key).map(Rc::new);
76        self.0.borrow_mut()[slot] = Some((key, result.clone()));
77        result
78    }
79}
80
81/// Single-line Material text. Measurement and painting share Foundation's
82/// shaped glyphs, including font fallback and letter spacing.
83#[derive(IntoElement)]
84pub struct Text {
85    value: SharedString,
86    id: Option<ElementId>,
87    role: TypeRole,
88    emphasis: TypographyEmphasis,
89    font_scale: f32,
90    color: Option<ColorRole>,
91    max_width: Option<gpui::Pixels>,
92    wrap: bool,
93}
94
95impl Text {
96    pub fn new(value: impl Into<SharedString>) -> Self {
97        Self {
98            value: value.into(),
99            id: None,
100            role: TypeRole::BodyLarge,
101            emphasis: TypographyEmphasis::Baseline,
102            font_scale: 1.,
103            color: None,
104            max_width: None,
105            wrap: false,
106        }
107    }
108
109    /// Supplies a stable ID for this label within its parent.
110    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
111        self.id = Some(id.into());
112        self
113    }
114
115    pub fn role(mut self, role: TypeRole) -> Self {
116        self.role = role;
117        self
118    }
119
120    pub fn emphasized(mut self, emphasized: bool) -> Self {
121        self.emphasis = if emphasized {
122            TypographyEmphasis::Emphasized
123        } else {
124            TypographyEmphasis::Baseline
125        };
126        self
127    }
128
129    pub fn font_scale(mut self, scale: f32) -> Self {
130        self.font_scale = scale;
131        self
132    }
133
134    pub fn color(mut self, role: ColorRole) -> Self {
135        self.color = Some(role);
136        self
137    }
138
139    pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
140        self.max_width = Some(max_width.max(px(0.)));
141        self.wrap = false;
142        self
143    }
144
145    /// Wraps at the available width and preserves explicit line breaks.
146    /// This uses GPUI's native Unicode layout, whose pinned version does not
147    /// expose custom tracking for wrapped text. Single-line text retains tracking.
148    pub fn wrap(mut self) -> Self {
149        self.wrap = true;
150        self.max_width = None;
151        self
152    }
153}
154
155impl RenderOnce for Text {
156    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
157        let tint = self.color.map_or_else(
158            || window.text_style().color,
159            |role| color(window_material_theme(window, cx).colors.color(role)),
160        );
161        let text = if self.wrap {
162            wrapped_text(
163                self.value.clone(),
164                self.role.style(self.emphasis),
165                self.font_scale,
166                tint,
167                window,
168                cx,
169            )
170        } else {
171            single_line(
172                self.value.clone(),
173                self.role.style(self.emphasis),
174                self.font_scale,
175                tint,
176                (self.max_width, 1., 1.),
177                window,
178                cx,
179            )
180        };
181        text.id(self.id.unwrap_or_else(|| "material-text".into()))
182            .test_support()
183            .role(Role::Label)
184            .aria_label(self.value)
185    }
186}
187
188fn clean_line(value: SharedString) -> SharedString {
189    if value.contains(['\r', '\n']) {
190        value.replace(['\r', '\n'], " ").into()
191    } else {
192        value
193    }
194}
195
196pub(crate) fn single_line_width(
197    value: &SharedString,
198    style: TypeStyle,
199    tint: Hsla,
200    window: &Window,
201    cx: &App,
202) -> Pixels {
203    let theme = window_material_theme(window, cx);
204    shape_text(
205        clean_line(value.clone()),
206        style,
207        &theme.typography,
208        1.,
209        tint,
210        window,
211        cx,
212    )
213    .expect("single-line text")
214    .line()
215    .width
216    .ceil()
217}
218
219pub(crate) fn single_line(
220    value: SharedString,
221    style: TypeStyle,
222    font_scale: f32,
223    tint: Hsla,
224    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
225    window: &Window,
226    cx: &App,
227) -> gpui::Div {
228    let clean = clean_line(value);
229    let theme = window_material_theme(window, cx);
230    let typography = theme.typography.clone();
231    let align = if theme.layout.direction == Direction::Rtl {
232        TextAlign::Right
233    } else {
234        TextAlign::Left
235    };
236    let shaped = shape_text(
237        clean.clone(),
238        style,
239        &typography,
240        font_scale,
241        tint,
242        window,
243        cx,
244    )
245    .expect("single-line text");
246    let width = shaped.line().width.ceil();
247    let height = shaped.line_height();
248    div()
249        .min_w_0()
250        .w(max_width.map_or(width, |max| width.min(max)) * expansion)
251        .max_w_full()
252        .h(height)
253        .overflow_hidden()
254        .opacity(opacity)
255        .child(
256            canvas(
257                move |bounds, window, cx| {
258                    let maximum = bounds.size.width;
259                    if shaped.line().width <= maximum || expansion < 1. {
260                        return Some(Ok(shaped));
261                    }
262                    let key = EllipsisKey {
263                        text: clean,
264                        width: maximum,
265                        style,
266                        typography,
267                        font_scale,
268                        scale_factor: window.scale_factor(),
269                        font_revision: font_cache_revision(cx),
270                        tint,
271                    };
272                    if cx.try_global::<EllipsisCache>().is_none() {
273                        cx.set_global(EllipsisCache::default());
274                    }
275                    cx.global::<EllipsisCache>()
276                        .get_or_shape(key, |key| ellipsize(&shaped, key, window, cx))
277                        .map(Err)
278                },
279                move |bounds, shaped, window, cx| {
280                    if let Some(shaped) = shaped {
281                        let shaped = match &shaped {
282                            Ok(line) => line,
283                            Err(line) => line.as_ref(),
284                        };
285                        let _ =
286                            shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
287                    }
288                },
289            )
290            .size_full(),
291        )
292}
293
294fn ellipsize(
295    shaped: &ShapedText,
296    key: &EllipsisKey,
297    window: &Window,
298    cx: &App,
299) -> Option<ShapedText> {
300    let shape = |value: SharedString| {
301        shape_text(
302            value,
303            key.style,
304            &key.typography,
305            key.font_scale,
306            key.tint,
307            window,
308            cx,
309        )
310        .expect("single-line text")
311    };
312    let ellipsis = shape("…".into());
313    if ellipsis.line().width > key.width {
314        return None;
315    }
316    let mut ends = shaped
317        .line()
318        .runs
319        .iter()
320        .flat_map(|run| &run.glyphs)
321        .map(|glyph| glyph.index)
322        .filter(|&index| key.text.is_char_boundary(index))
323        .collect::<Vec<_>>();
324    ends.sort_unstable();
325    ends.dedup();
326    ends.into_iter()
327        .rev()
328        .filter(|&end| end > 0)
329        .map(|end| shape(format!("{}…", &key.text[..end]).into()))
330        .find(|line| line.line().width <= key.width)
331        .or(Some(ellipsis))
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn ellipsis_cache_reuses_results_and_misses_on_layout_changes() {
340        let cache = EllipsisCache::default();
341        let key = || EllipsisKey {
342            text: "office 中文 العربية e\u{301} 👨‍👩‍👧‍👦".into(),
343            width: px(120.),
344            style: TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
345            typography: Typography::default(),
346            font_scale: 1.,
347            scale_factor: 1.,
348            font_revision: 0,
349            tint: gpui::white(),
350        };
351        assert!(cache.get_or_shape(key(), |_| None).is_none());
352        assert!(
353            cache
354                .get_or_shape(key(), |_| panic!("same layout must be reused"))
355                .is_none()
356        );
357
358        for changed in [
359            EllipsisKey {
360                width: px(121.),
361                ..key()
362            },
363            EllipsisKey {
364                font_scale: 1.25,
365                ..key()
366            },
367            EllipsisKey {
368                scale_factor: 2.,
369                ..key()
370            },
371            EllipsisKey {
372                font_revision: 1,
373                ..key()
374            },
375            EllipsisKey {
376                tint: gpui::black(),
377                ..key()
378            },
379        ] {
380            let mut missed = false;
381            cache.get_or_shape(changed, |_| {
382                missed = true;
383                None
384            });
385            assert!(missed);
386        }
387    }
388}