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, prelude::FluentBuilder, px,
11};
12use gpui_base::TestSupportExt;
13use gpui_material_foundation::{
14    ShapedText, color, current_material_theme, font_cache_revision, shape_text, 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    color_override: Option<Hsla>,
92    align: Option<TextAlign>,
93    max_lines: Option<usize>,
94    max_width: Option<gpui::Pixels>,
95    wrap: bool,
96}
97
98impl Text {
99    /// Creates text with the default [`TypeRole::BodyLarge`] typography role.
100    pub fn new(value: impl Into<SharedString>) -> Self {
101        Self {
102            value: value.into(),
103            id: None,
104            role: TypeRole::BodyLarge,
105            emphasis: TypographyEmphasis::Baseline,
106            font_scale: 1.,
107            color: None,
108            color_override: None,
109            align: None,
110            max_lines: None,
111            max_width: None,
112            wrap: false,
113        }
114    }
115
116    /// Creates text styled with [`TypeRole::DisplayLarge`].
117    pub fn display_large(value: impl Into<SharedString>) -> Self {
118        Self::new(value).role(TypeRole::DisplayLarge)
119    }
120
121    /// Creates text styled with [`TypeRole::DisplayMedium`].
122    pub fn display_medium(value: impl Into<SharedString>) -> Self {
123        Self::new(value).role(TypeRole::DisplayMedium)
124    }
125
126    /// Creates text styled with [`TypeRole::DisplaySmall`].
127    pub fn display_small(value: impl Into<SharedString>) -> Self {
128        Self::new(value).role(TypeRole::DisplaySmall)
129    }
130
131    /// Creates text styled with [`TypeRole::HeadlineLarge`].
132    pub fn headline_large(value: impl Into<SharedString>) -> Self {
133        Self::new(value).role(TypeRole::HeadlineLarge)
134    }
135
136    /// Creates text styled with [`TypeRole::HeadlineMedium`].
137    pub fn headline_medium(value: impl Into<SharedString>) -> Self {
138        Self::new(value).role(TypeRole::HeadlineMedium)
139    }
140
141    /// Creates text styled with [`TypeRole::HeadlineSmall`].
142    pub fn headline_small(value: impl Into<SharedString>) -> Self {
143        Self::new(value).role(TypeRole::HeadlineSmall)
144    }
145
146    /// Creates text styled with [`TypeRole::TitleLarge`].
147    pub fn title_large(value: impl Into<SharedString>) -> Self {
148        Self::new(value).role(TypeRole::TitleLarge)
149    }
150
151    /// Creates text styled with [`TypeRole::TitleMedium`].
152    pub fn title_medium(value: impl Into<SharedString>) -> Self {
153        Self::new(value).role(TypeRole::TitleMedium)
154    }
155
156    /// Creates text styled with [`TypeRole::TitleSmall`].
157    pub fn title_small(value: impl Into<SharedString>) -> Self {
158        Self::new(value).role(TypeRole::TitleSmall)
159    }
160
161    /// Creates text styled with [`TypeRole::BodyLarge`].
162    pub fn body_large(value: impl Into<SharedString>) -> Self {
163        Self::new(value).role(TypeRole::BodyLarge)
164    }
165
166    /// Creates text styled with [`TypeRole::BodyMedium`].
167    pub fn body_medium(value: impl Into<SharedString>) -> Self {
168        Self::new(value).role(TypeRole::BodyMedium)
169    }
170
171    /// Creates text styled with [`TypeRole::BodySmall`].
172    pub fn body_small(value: impl Into<SharedString>) -> Self {
173        Self::new(value).role(TypeRole::BodySmall)
174    }
175
176    /// Creates text styled with [`TypeRole::LabelLarge`].
177    pub fn label_large(value: impl Into<SharedString>) -> Self {
178        Self::new(value).role(TypeRole::LabelLarge)
179    }
180
181    /// Creates text styled with [`TypeRole::LabelMedium`].
182    pub fn label_medium(value: impl Into<SharedString>) -> Self {
183        Self::new(value).role(TypeRole::LabelMedium)
184    }
185
186    /// Creates text styled with [`TypeRole::LabelSmall`].
187    pub fn label_small(value: impl Into<SharedString>) -> Self {
188        Self::new(value).role(TypeRole::LabelSmall)
189    }
190
191    /// Supplies a stable ID for this label within its parent.
192    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
193        self.id = Some(id.into());
194        self
195    }
196
197    /// Sets the Material typography scale role. Defaults to [`TypeRole::BodyLarge`].
198    pub fn role(mut self, role: TypeRole) -> Self {
199        self.role = role;
200        self
201    }
202
203    /// Selects emphasized typography weight when `true`, or baseline weight when `false`.
204    pub fn emphasized(mut self, emphasized: bool) -> Self {
205        self.emphasis = if emphasized {
206            TypographyEmphasis::Emphasized
207        } else {
208            TypographyEmphasis::Baseline
209        };
210        self
211    }
212
213    /// Applies an additional font-size multiplier on top of the window theme's typography scale. Defaults to `1.0`.
214    pub fn font_scale(mut self, scale: f32) -> Self {
215        self.font_scale = scale;
216        self
217    }
218
219    /// Resolves the text color from the window theme's semantic color role.
220    pub fn color(mut self, role: ColorRole) -> Self {
221        self.color = Some(role);
222        self.color_override = None;
223        self
224    }
225
226    /// Sets a literal text color. A later call to [`Self::color`] restores theme-role lookup.
227    pub fn color_override(mut self, color: impl Into<Hsla>) -> Self {
228        self.color_override = Some(color.into());
229        self
230    }
231
232    /// Sets the text color to [`ColorRole::OnSurfaceVariant`].
233    pub fn muted(self) -> Self {
234        self.color(ColorRole::OnSurfaceVariant)
235    }
236
237    /// Sets explicit horizontal text alignment. Defaults to the window's logical start edge.
238    pub fn align(mut self, align: TextAlign) -> Self {
239        self.align = Some(align);
240        self
241    }
242
243    /// Clamps wrapped text to at most `lines` lines (minimum 1) when `.wrap()` is enabled.
244    pub fn max_lines(mut self, lines: usize) -> Self {
245        self.max_lines = Some(lines.max(1));
246        self
247    }
248
249    /// Limits single-line text to `max_width` logical pixels, ellipsizing overflow and disabling wrapping.
250    pub fn truncate(mut self, max_width: gpui::Pixels) -> Self {
251        self.max_width = Some(max_width.max(px(0.)));
252        self.wrap = false;
253        self
254    }
255
256    /// Wraps at the available width and preserves explicit line breaks.
257    /// This uses GPUI's native Unicode layout, whose pinned version does not
258    /// expose custom tracking for wrapped text. Single-line text retains tracking.
259    pub fn wrap(mut self) -> Self {
260        self.wrap = true;
261        self.max_width = None;
262        self
263    }
264}
265
266impl RenderOnce for Text {
267    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
268        let tint = self.color_override.unwrap_or_else(|| {
269            self.color.map_or_else(
270                || window.text_style().color,
271                |role| color(current_material_theme(window, cx).colors.color(role)),
272            )
273        });
274        let text = if self.wrap {
275            wrapped_text(
276                self.value.clone(),
277                self.role.style(self.emphasis),
278                self.font_scale,
279                tint,
280                window,
281                cx,
282            )
283            .when_some(self.align, |text, align| text.w_full().text_align(align))
284            .when_some(self.max_lines, |text, lines| {
285                text.line_clamp(lines).text_ellipsis()
286            })
287        } else {
288            single_line_aligned(
289                self.value.clone(),
290                self.role.style(self.emphasis),
291                self.font_scale,
292                tint,
293                (self.max_width, 1., 1.),
294                self.align,
295                window,
296                cx,
297            )
298        };
299        text.id(self.id.unwrap_or_else(|| "material-text".into()))
300            .test_support()
301            .role(Role::Label)
302            .aria_label(self.value)
303    }
304}
305
306fn clean_line(value: SharedString) -> SharedString {
307    if value.contains(['\r', '\n']) {
308        value.replace(['\r', '\n'], " ").into()
309    } else {
310        value
311    }
312}
313
314pub(crate) fn shape_single_line(
315    value: SharedString,
316    style: TypeStyle,
317    font_scale: f32,
318    tint: Hsla,
319    window: &Window,
320    cx: &App,
321) -> (SharedString, ShapedText) {
322    let clean = clean_line(value);
323    let theme = current_material_theme(window, cx);
324    let shaped = shape_text(
325        clean.clone(),
326        style,
327        &theme.typography,
328        font_scale,
329        tint,
330        window,
331        cx,
332    )
333    .expect("single-line text");
334    (clean, shaped)
335}
336
337#[allow(clippy::too_many_arguments)]
338fn single_line_aligned(
339    value: SharedString,
340    style: TypeStyle,
341    font_scale: f32,
342    tint: Hsla,
343    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
344    align_override: Option<TextAlign>,
345    window: &Window,
346    cx: &App,
347) -> gpui::Div {
348    let shaped = shape_single_line(value, style, font_scale, tint, window, cx);
349    single_line_with_shaped_and_align(
350        shaped,
351        style,
352        font_scale,
353        tint,
354        (max_width, expansion, opacity),
355        align_override,
356        window,
357        cx,
358    )
359}
360
361pub(crate) fn single_line(
362    value: SharedString,
363    style: TypeStyle,
364    font_scale: f32,
365    tint: Hsla,
366    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
367    window: &Window,
368    cx: &App,
369) -> gpui::Div {
370    single_line_aligned(
371        value,
372        style,
373        font_scale,
374        tint,
375        (max_width, expansion, opacity),
376        None,
377        window,
378        cx,
379    )
380}
381
382pub(crate) fn single_line_with_shaped(
383    shaped: (SharedString, ShapedText),
384    style: TypeStyle,
385    font_scale: f32,
386    tint: Hsla,
387    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
388    window: &Window,
389    cx: &App,
390) -> gpui::Div {
391    single_line_with_shaped_and_align(
392        shaped,
393        style,
394        font_scale,
395        tint,
396        (max_width, expansion, opacity),
397        None,
398        window,
399        cx,
400    )
401}
402
403#[allow(clippy::too_many_arguments)]
404fn single_line_with_shaped_and_align(
405    (clean, shaped): (SharedString, ShapedText),
406    style: TypeStyle,
407    font_scale: f32,
408    tint: Hsla,
409    (max_width, expansion, opacity): (Option<Pixels>, f32, f32),
410    align_override: Option<TextAlign>,
411    window: &Window,
412    cx: &App,
413) -> gpui::Div {
414    let theme = current_material_theme(window, cx);
415    let typography = theme.typography.clone();
416    let align = align_override.unwrap_or(if theme.layout.direction == Direction::Rtl {
417        TextAlign::Right
418    } else {
419        TextAlign::Left
420    });
421    let width = shaped.line().width.ceil();
422    let height = shaped.line_height();
423    let container = div().min_w_0();
424    let container = if align_override.is_some() {
425        match max_width {
426            Some(max) => container.w(max * expansion),
427            None => container.w_full(),
428        }
429    } else {
430        container.w(max_width.map_or(width, |max| width.min(max)) * expansion)
431    };
432    container
433        .max_w_full()
434        .h(height)
435        .overflow_hidden()
436        .opacity(opacity)
437        .child(
438            canvas(
439                move |bounds, window, cx| {
440                    let maximum = bounds.size.width;
441                    if shaped.line().width <= maximum || expansion < 1. {
442                        return Some(Ok(shaped));
443                    }
444                    let key = EllipsisKey {
445                        text: clean,
446                        width: maximum,
447                        style,
448                        typography,
449                        font_scale,
450                        scale_factor: window.scale_factor(),
451                        font_revision: font_cache_revision(cx),
452                        tint,
453                    };
454                    if cx.try_global::<EllipsisCache>().is_none() {
455                        cx.set_global(EllipsisCache::default());
456                    }
457                    cx.global::<EllipsisCache>()
458                        .get_or_shape(key, |key| ellipsize(&shaped, key, window, cx))
459                        .map(Err)
460                },
461                move |bounds, shaped, window, cx| {
462                    if let Some(shaped) = shaped {
463                        let shaped = match &shaped {
464                            Ok(line) => line,
465                            Err(line) => line.as_ref(),
466                        };
467                        let _ =
468                            shaped.paint(bounds.origin, align, Some(bounds.size.width), window, cx);
469                    }
470                },
471            )
472            .size_full(),
473        )
474}
475
476fn find_ellipsis_fit<T>(ends: &[usize], mut try_fit: impl FnMut(usize) -> Option<T>) -> Option<T> {
477    let mut last_fitting: Option<(usize, T)> = None;
478    let cut = ends.partition_point(|&end| {
479        if let Some(fitted) = try_fit(end) {
480            last_fitting = Some((end, fitted));
481            true
482        } else {
483            false
484        }
485    });
486    if cut == 0 {
487        return None;
488    }
489    let target = ends[cut - 1];
490    if let Some((end, fitted)) = last_fitting
491        && end == target
492    {
493        Some(fitted)
494    } else {
495        try_fit(target)
496    }
497}
498
499fn ellipsize(
500    shaped: &ShapedText,
501    key: &EllipsisKey,
502    window: &Window,
503    cx: &App,
504) -> Option<ShapedText> {
505    let shape = |value: SharedString| {
506        shape_text(
507            value,
508            key.style,
509            &key.typography,
510            key.font_scale,
511            key.tint,
512            window,
513            cx,
514        )
515        .expect("single-line text")
516    };
517    let ellipsis = shape("…".into());
518    if ellipsis.line().width > key.width {
519        return None;
520    }
521    let mut ends = shaped
522        .line()
523        .runs
524        .iter()
525        .flat_map(|run| &run.glyphs)
526        .map(|glyph| glyph.index)
527        .filter(|&index| index > 0 && key.text.is_char_boundary(index))
528        .collect::<Vec<_>>();
529    ends.sort_unstable();
530    ends.dedup();
531    find_ellipsis_fit(&ends, |end| {
532        let line = shape(format!("{}…", &key.text[..end]).into());
533        (line.line().width <= key.width).then_some(line)
534    })
535    .or(Some(ellipsis))
536}
537
538#[cfg(test)]
539mod tests {
540    use super::*;
541
542    #[test]
543    fn ellipsis_cache_reuses_results_and_misses_on_layout_changes() {
544        let cache = EllipsisCache::default();
545        let key = || EllipsisKey {
546            text: "office 中文 العربية e\u{301} 👨‍👩‍👧‍👦".into(),
547            width: px(120.),
548            style: TypeRole::BodyLarge.style(TypographyEmphasis::Baseline),
549            typography: Typography::default(),
550            font_scale: 1.,
551            scale_factor: 1.,
552            font_revision: 0,
553            tint: gpui::white(),
554        };
555        assert!(cache.get_or_shape(key(), |_| None).is_none());
556        assert!(
557            cache
558                .get_or_shape(key(), |_| panic!("same layout must be reused"))
559                .is_none()
560        );
561
562        for changed in [
563            EllipsisKey {
564                width: px(121.),
565                ..key()
566            },
567            EllipsisKey {
568                font_scale: 1.25,
569                ..key()
570            },
571            EllipsisKey {
572                scale_factor: 2.,
573                ..key()
574            },
575            EllipsisKey {
576                font_revision: 1,
577                ..key()
578            },
579            EllipsisKey {
580                tint: gpui::black(),
581                ..key()
582            },
583        ] {
584            let mut missed = false;
585            cache.get_or_shape(changed, |_| {
586                missed = true;
587                None
588            });
589            assert!(missed);
590        }
591    }
592
593    #[test]
594    fn binary_search_ellipsis_fit_matches_linear_reverse_truncation() {
595        let text =
596            "Material 3 Expressive 中文排版与省略号测试 — longer sample for logarithmic search";
597        let ends: Vec<usize> = text
598            .char_indices()
599            .map(|(ix, _)| ix)
600            .filter(|&ix| ix > 0)
601            .collect();
602        let max_probes = (usize::BITS - ends.len().leading_zeros()) as usize + 1;
603        assert_eq!(find_ellipsis_fit(&[], Some), None);
604        for max_bytes in 0..=text.len() + 5 {
605            let linear = ends.iter().copied().rev().find(|&end| end <= max_bytes);
606            let mut probes = 0usize;
607            let binary = find_ellipsis_fit(&ends, |end| {
608                probes += 1;
609                (end <= max_bytes).then_some(end)
610            });
611            assert_eq!(binary, linear, "mismatch for max_bytes={max_bytes}");
612            assert!(
613                probes <= max_probes,
614                "expected O(log N) probes <= {max_probes}, got {probes}"
615            );
616        }
617    }
618
619    #[test]
620    fn text_shorthands_and_muted_set_expected_role_and_color() {
621        let cases = [
622            (Text::display_large("a"), TypeRole::DisplayLarge),
623            (Text::display_medium("a"), TypeRole::DisplayMedium),
624            (Text::display_small("a"), TypeRole::DisplaySmall),
625            (Text::headline_large("a"), TypeRole::HeadlineLarge),
626            (Text::headline_medium("a"), TypeRole::HeadlineMedium),
627            (Text::headline_small("a"), TypeRole::HeadlineSmall),
628            (Text::title_large("a"), TypeRole::TitleLarge),
629            (Text::title_medium("a"), TypeRole::TitleMedium),
630            (Text::title_small("a"), TypeRole::TitleSmall),
631            (Text::body_large("a"), TypeRole::BodyLarge),
632            (Text::body_medium("a"), TypeRole::BodyMedium),
633            (Text::body_small("a"), TypeRole::BodySmall),
634            (Text::label_large("a"), TypeRole::LabelLarge),
635            (Text::label_medium("a"), TypeRole::LabelMedium),
636            (Text::label_small("a"), TypeRole::LabelSmall),
637        ];
638        for (text, expected_role) in cases {
639            assert_eq!(text.role, expected_role);
640            assert_eq!(text.color, None);
641        }
642        let muted = Text::body_medium("hint").muted();
643        assert_eq!(muted.role, TypeRole::BodyMedium);
644        assert_eq!(muted.color, Some(ColorRole::OnSurfaceVariant));
645    }
646}