Skip to main content

gpui_component/
label.rs

1use std::{ops::Range, panic::Location};
2
3use gpui::{
4    App, ElementId, HighlightStyle, InteractiveElement as _, IntoElement, ParentElement,
5    RenderOnce, SharedString, StatefulInteractiveElement as _, StyleRefinement, Styled, StyledText,
6    Window, div, prelude::FluentBuilder, rems,
7};
8
9use gpui_base::{LayoutDirection, LogicalStyledExt as _};
10use gpui_base::{TestSupportExt as _, TestTextExt as _};
11
12use crate::{ActiveTheme, StyledExt};
13
14const MASKED: &'static str = "•";
15
16/// Represents the type of match for highlighting text in a label.
17#[derive(Clone)]
18pub enum HighlightsMatch {
19    Prefix(SharedString),
20    Full(SharedString),
21}
22
23impl HighlightsMatch {
24    pub fn as_str(&self) -> &str {
25        match self {
26            Self::Prefix(s) => s.as_str(),
27            Self::Full(s) => s.as_str(),
28        }
29    }
30
31    #[inline]
32    pub fn is_prefix(&self) -> bool {
33        matches!(self, Self::Prefix(_))
34    }
35}
36
37impl From<&str> for HighlightsMatch {
38    fn from(value: &str) -> Self {
39        Self::Full(value.to_string().into())
40    }
41}
42
43impl From<String> for HighlightsMatch {
44    fn from(value: String) -> Self {
45        Self::Full(value.into())
46    }
47}
48
49impl From<SharedString> for HighlightsMatch {
50    fn from(value: SharedString) -> Self {
51        Self::Full(value)
52    }
53}
54
55/// A text label element with optional secondary text, masking, and highlighting capabilities.
56///
57/// A label is exposed to assistive technology as a `Label` node whose value is
58/// its text, so a screen reader can read it. A masked or empty label has no
59/// node.
60#[derive(IntoElement)]
61pub struct Label {
62    id: ElementId,
63    style: StyleRefinement,
64    label: SharedString,
65    secondary: Option<SharedString>,
66    masked: bool,
67    highlights_text: Option<HighlightsMatch>,
68}
69
70impl Label {
71    /// Create a new label with the main label.
72    ///
73    /// The label's id defaults to this call site, which is unique wherever one
74    /// line builds one label. See [`Label::id`] for labels built in a loop.
75    #[track_caller]
76    pub fn new(label: impl Into<SharedString>) -> Self {
77        let label: SharedString = label.into();
78        Self {
79            id: ElementId::CodeLocation(*Location::caller()),
80            style: Default::default(),
81            label,
82            secondary: None,
83            masked: false,
84            highlights_text: None,
85        }
86    }
87
88    /// Set the label's element id, replacing the default taken from where
89    /// [`Label::new`] was called.
90    ///
91    /// Pass one where a single `Label::new` renders several labels as
92    /// siblings, such as in a loop: they share the default id, so assistive
93    /// technology gets only the first of them, and GPUI's debug builds panic
94    /// on the duplicate while it is connected. The id must be unique among
95    /// those siblings. Labels under parents that have their own ids, like the
96    /// rows of a `List`, are already distinct.
97    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
98        self.id = id.into();
99        self
100    }
101
102    /// Set the secondary text for the label,
103    /// the secondary text will be displayed after the label text with `muted` color.
104    pub fn secondary(mut self, secondary: impl Into<SharedString>) -> Self {
105        self.secondary = Some(secondary.into());
106        self
107    }
108
109    /// Set whether to mask the label text.
110    pub fn masked(mut self, masked: bool) -> Self {
111        self.masked = masked;
112        self
113    }
114
115    /// Set for matching text to highlight in the label.
116    pub fn highlights(mut self, text: impl Into<HighlightsMatch>) -> Self {
117        self.highlights_text = Some(text.into());
118        self
119    }
120
121    fn full_text(&self) -> SharedString {
122        match &self.secondary {
123            Some(secondary) => format!("{} {}", self.label, secondary).into(),
124            None => self.label.clone(),
125        }
126    }
127
128    fn highlight_ranges(&self, total_length: usize) -> Vec<Range<usize>> {
129        let mut ranges = Vec::new();
130        let full_text = self.full_text();
131
132        if self.secondary.is_some() {
133            ranges.push(0..self.label.len());
134            ranges.push(self.label.len()..total_length);
135        }
136
137        if let Some(matched) = &self.highlights_text {
138            let matched_str = matched.as_str();
139            if !matched_str.is_empty() {
140                let search_lower = matched_str.to_lowercase();
141                let full_text_lower = full_text.to_lowercase();
142
143                if matched.is_prefix() {
144                    // For prefix matching, only check if the text starts with the search term
145                    if full_text_lower.starts_with(&search_lower) {
146                        ranges.push(0..matched_str.len());
147                    }
148                } else {
149                    // For full matching, find all occurrences
150                    let mut search_start = 0;
151                    while let Some(pos) = full_text_lower[search_start..].find(&search_lower) {
152                        let match_start = search_start + pos;
153                        let match_end = match_start + matched_str.len();
154
155                        if match_end <= full_text.len() {
156                            ranges.push(match_start..match_end);
157                        }
158
159                        search_start = match_start + 1;
160                        while !full_text.is_char_boundary(search_start)
161                            && search_start < full_text.len()
162                        {
163                            search_start += 1;
164                        }
165
166                        if search_start >= full_text.len() {
167                            break;
168                        }
169                    }
170                }
171            }
172        }
173
174        ranges
175    }
176
177    fn measure_highlights(
178        &self,
179        length: usize,
180        cx: &mut App,
181    ) -> Option<Vec<(Range<usize>, HighlightStyle)>> {
182        if self.masked {
183            return None;
184        }
185
186        let ranges = self.highlight_ranges(length);
187        if ranges.is_empty() {
188            return None;
189        }
190
191        let mut highlights = Vec::new();
192        let mut highlight_ranges_added = 0;
193
194        if self.secondary.is_some() {
195            highlights.push((ranges[0].clone(), HighlightStyle::default()));
196            highlights.push((
197                ranges[1].clone(),
198                HighlightStyle {
199                    color: Some(cx.theme().muted_foreground),
200                    ..Default::default()
201                },
202            ));
203            highlight_ranges_added = 2;
204        }
205
206        for range in ranges.iter().skip(highlight_ranges_added) {
207            highlights.push((
208                range.clone(),
209                HighlightStyle {
210                    color: Some(cx.theme().blue),
211                    ..Default::default()
212                },
213            ));
214        }
215
216        Some(gpui::combine_highlights(vec![], highlights).collect())
217    }
218}
219
220impl Styled for Label {
221    fn style(&mut self) -> &mut gpui::StyleRefinement {
222        &mut self.style
223    }
224}
225
226impl RenderOnce for Label {
227    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
228        let mut text = self.full_text();
229        let chars_count = text.chars().count();
230
231        if self.masked {
232            text = SharedString::from(MASKED.repeat(chars_count))
233        };
234
235        let highlights = self.measure_highlights(text.len(), cx);
236        // Plain text is not in the accessibility tree, so the label carries
237        // it. A masked label keeps its text out of the tree.
238        let accessible_text = (!self.masked && !text.is_empty()).then(|| text.clone());
239
240        div()
241            .id(self.id)
242            .test_support()
243            .when_some(accessible_text, |this, text| {
244                // A `Label` node is named by its value, not its label.
245                this.role(gpui::Role::Label).aria_value(text)
246            })
247            .line_height(rems(1.25))
248            .text_color(cx.theme().foreground)
249            // Start-aligned in RTL; LTR keeps the inherited alignment.
250            .when(LayoutDirection::global(cx).is_rtl(), |this| {
251                this.text_start(cx)
252            })
253            .refine_style(&self.style)
254            .child(
255                StyledText::new(&text).when_some(highlights, |this, hl| this.with_highlights(hl)),
256            )
257            .test_text(text)
258    }
259}
260
261/// `text` with every occurrence of the search `query` drawn in the theme's
262/// `list_highlight_foreground` color, matched the way searchable lists filter:
263/// by case-insensitive substring.
264pub(crate) fn highlight_matches(text: SharedString, query: &str, cx: &App) -> StyledText {
265    let style = HighlightStyle {
266        color: Some(cx.theme().list_highlight_foreground),
267        ..Default::default()
268    };
269    let highlights = match_ranges(&text, query)
270        .into_iter()
271        .map(|range| (range, style))
272        .collect::<Vec<_>>();
273
274    StyledText::new(text).with_highlights(highlights)
275}
276
277/// The byte ranges of `text` that case-insensitively equal `query`, without
278/// overlaps.
279fn match_ranges(text: &str, query: &str) -> Vec<Range<usize>> {
280    let query = query
281        .chars()
282        .flat_map(char::to_lowercase)
283        .collect::<Vec<_>>();
284    let mut ranges = Vec::new();
285    if query.is_empty() {
286        return ranges;
287    }
288
289    let mut next_start = 0;
290    for (start, _) in text.char_indices() {
291        if start < next_start {
292            continue;
293        }
294        if let Some(len) = match_len(&text[start..], &query) {
295            ranges.push(start..start + len);
296            next_start = start + len;
297        }
298    }
299
300    ranges
301}
302
303/// The byte length of the start of `text` whose lowercase form is `query`.
304fn match_len(text: &str, query: &[char]) -> Option<usize> {
305    let mut rest = query;
306    for (offset, ch) in text.char_indices() {
307        for lower in ch.to_lowercase() {
308            let (first, tail) = rest.split_first()?;
309            if *first != lower {
310                return None;
311            }
312            rest = tail;
313        }
314        if rest.is_empty() {
315            return Some(offset + ch.len_utf8());
316        }
317    }
318
319    None
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325
326    #[test]
327    fn match_ranges_find_every_case_insensitive_occurrence() {
328        assert_eq!(match_ranges("Rust", "ru"), vec![0..2]);
329        assert_eq!(match_ranges("Banana", "AN"), vec![1..3, 3..5]);
330        assert_eq!(match_ranges("aaaa", "aa"), vec![0..2, 2..4]);
331        assert_eq!(match_ranges("Rust", "go"), Vec::<Range<usize>>::new());
332        assert_eq!(match_ranges("Rust", ""), Vec::<Range<usize>>::new());
333        assert_eq!(match_ranges("Café Crème", "CRÈ"), vec![6..10]);
334        assert_eq!(match_ranges("İstanbul", "i̇s"), vec![0..3]);
335        assert_eq!(match_ranges("İstanbul", "i"), Vec::<Range<usize>>::new());
336    }
337
338    struct MaskedLabels;
339
340    impl gpui::Render for MaskedLabels {
341        fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
342            div()
343                .child(Label::new("Hello").secondary("World").masked(true))
344                .child(Label::new("Hello").highlights("ell").masked(true))
345                .child(
346                    Label::new("é🙂")
347                        .secondary("世界")
348                        .highlights("🙂 世")
349                        .masked(true),
350                )
351        }
352    }
353
354    #[gpui::test]
355    fn masked_secondary_text_and_highlights_render(cx: &mut gpui::TestAppContext) {
356        cx.update(crate::init);
357        cx.update(|cx| {
358            let label = Label::new("é🙂")
359                .secondary("世界")
360                .highlights("🙂 世")
361                .masked(true);
362            assert!(
363                label
364                    .measure_highlights(label.full_text().len(), cx)
365                    .is_none()
366            );
367        });
368        let (_, cx) = cx.add_window_view(|_, _| MaskedLabels);
369        cx.update(|window, cx| crate::test_redraw(window, cx));
370    }
371
372    #[cfg(feature = "test-support")]
373    #[gpui::test]
374    fn records_displayed_text_under_its_identified_parent(cx: &mut gpui::TestAppContext) {
375        use gpui::InteractiveElement as _;
376
377        struct Labels;
378        impl gpui::Render for Labels {
379            fn render(&mut self, _: &mut Window, _: &mut gpui::Context<Self>) -> impl IntoElement {
380                div()
381                    .id("box")
382                    .child(Label::new("Hello"))
383                    .child(Label::new("secret").masked(true))
384            }
385        }
386        cx.update(crate::init);
387        let (_, cx) = cx.add_window_view(|_, _| Labels);
388        // Root starts each frame; this window has none.
389        cx.update(|window, cx| {
390            gpui_base::test_support::begin_frame(window);
391            crate::test_redraw(window, cx)
392        });
393        cx.update(|window, _| {
394            let texts: Vec<_> = gpui_base::test_support::texts(window)
395                .iter()
396                .map(|text| {
397                    assert!(text.path().contains(&"box".into()), "{:?}", text.path());
398                    text.text().to_owned()
399                })
400                .collect();
401            assert_eq!(texts, ["Hello", "••••••"]);
402        });
403    }
404
405    #[test]
406    fn test_highlight_ranges() {
407        // Basic functionality
408
409        // No highlights
410        let label = Label::new("Hello World");
411        let result = label.highlight_ranges("Hello World".len());
412        assert_eq!(result, Vec::<Range<usize>>::new());
413
414        // Secondary text ranges only
415        let label = Label::new("Hello").secondary("World");
416        let total_length = "Hello World".len();
417        let result = label.highlight_ranges(total_length);
418        assert_eq!(result.len(), 2);
419        assert_eq!(result[0], 0..5); // "Hello"
420        assert_eq!(result[1], 5..11); // " World"
421
422        // Text highlighting
423
424        // Single match with case insensitive
425        let label = Label::new("Hello World").highlights("WORLD");
426        let result = label.highlight_ranges("Hello World".len());
427        assert_eq!(result.len(), 1);
428        assert_eq!(result[0], 6..11); // "World"
429
430        // Multiple matches
431        let label = Label::new("Hello Hello Hello").highlights("Hello");
432        let result = label.highlight_ranges("Hello Hello Hello".len());
433        assert_eq!(result.len(), 3);
434        assert_eq!(result[0], 0..5); // First "Hello"
435        assert_eq!(result[1], 6..11); // Second "Hello"
436        assert_eq!(result[2], 12..17); // Third "Hello"
437
438        // No match and empty search
439        let label = Label::new("Hello World").highlights("xyz");
440        let result = label.highlight_ranges("Hello World".len());
441        assert_eq!(result, Vec::<Range<usize>>::new());
442
443        let label = Label::new("Hello World").highlights("");
444        let result = label.highlight_ranges("Hello World".len());
445        assert_eq!(result, Vec::<Range<usize>>::new());
446
447        // Combined functionality
448
449        // Secondary + highlights in main text
450        let label = Label::new("Hello").secondary("World").highlights("llo");
451        let total_length = "Hello World".len();
452        let result = label.highlight_ranges(total_length);
453        assert_eq!(result.len(), 3);
454        assert_eq!(result[0], 0..5); // Main text range
455        assert_eq!(result[1], 5..11); // Secondary text range
456        assert_eq!(result[2], 2..5); // "llo" in main text
457
458        // Highlight in secondary text
459        let label = Label::new("Hello").secondary("World").highlights("World");
460        let total_length = "Hello World".len();
461        let result = label.highlight_ranges(total_length);
462        assert_eq!(result.len(), 3);
463        assert_eq!(result[0], 0..5); // Main text range
464        assert_eq!(result[1], 5..11); // Secondary text range
465        assert_eq!(result[2], 6..11); // "World" in secondary text
466
467        // Cross-boundary highlight
468        let label = Label::new("Hello").secondary("World").highlights("o W");
469        let total_length = "Hello World".len();
470        let result = label.highlight_ranges(total_length);
471        assert_eq!(result.len(), 3);
472        assert_eq!(result[0], 0..5); // Main text range
473        assert_eq!(result[1], 5..11); // Secondary text range
474        assert_eq!(result[2], 4..7); // "o W" across boundary
475
476        // Edge cases
477
478        // Overlapping matches
479        let label = Label::new("aaaa").highlights("aa");
480        let result = label.highlight_ranges("aaaa".len());
481        assert!(result.len() >= 2);
482        assert_eq!(result[0], 0..2); // First "aa"
483        assert_eq!(result[1], 1..3); // Overlapping "aa"
484
485        // Unicode text
486        let label = Label::new("你好世界,Hello World").highlights("世界");
487        let result = label.highlight_ranges("你好世界,Hello World".len());
488        assert_eq!(result.len(), 1);
489        let text = "你好世界,Hello World";
490        let start = text.find("世界").unwrap();
491        let end = start + "世界".len();
492        assert_eq!(result[0], start..end);
493    }
494
495    #[test]
496    fn test_highlight_ranges_prefix() {
497        // Test prefix match - should only match the first occurrence
498        let label = Label::new("aaaa").highlights(HighlightsMatch::Prefix("aa".into()));
499        let result = label.highlight_ranges("aaaa".len());
500        assert_eq!(result.len(), 1);
501        assert_eq!(result[0], 0..2); // Only first "aa"
502
503        // Test prefix vs full match behavior
504        let label_full =
505            Label::new("Hello Hello").highlights(HighlightsMatch::Full("Hello".into()));
506        let result_full = label_full.highlight_ranges("Hello Hello".len());
507        assert_eq!(result_full.len(), 2); // Both "Hello" matches
508
509        let label_prefix =
510            Label::new("Hello Hello").highlights(HighlightsMatch::Prefix("Hello".into()));
511        let result_prefix = label_prefix.highlight_ranges("Hello Hello".len());
512        assert_eq!(result_prefix.len(), 1); // Only first "Hello"
513        assert_eq!(result_prefix[0], 0..5);
514
515        // Test prefix with case insensitive matching
516        let label =
517            Label::new("Hello hello HELLO").highlights(HighlightsMatch::Prefix("hello".into()));
518        let result = label.highlight_ranges("Hello hello HELLO".len());
519        assert_eq!(result.len(), 1);
520        assert_eq!(result[0], 0..5); // First "Hello" (case insensitive)
521
522        // Test prefix with no match
523        let label = Label::new("Hello World").highlights(HighlightsMatch::Prefix("xyz".into()));
524        let result = label.highlight_ranges("Hello World".len());
525        assert_eq!(result.len(), 0);
526
527        // Test prefix with empty string
528        let label = Label::new("Hello World").highlights(HighlightsMatch::Prefix("".into()));
529        let result = label.highlight_ranges("Hello World".len());
530        assert_eq!(result.len(), 0);
531
532        // Test prefix with secondary text - match in main text
533        let label = Label::new("Hello")
534            .secondary("Hello World")
535            .highlights(HighlightsMatch::Prefix("Hello".into()));
536        let total_length = "Hello Hello World".len();
537        let result = label.highlight_ranges(total_length);
538        assert_eq!(result.len(), 3); // 2 for secondary + 1 for prefix match
539        assert_eq!(result[0], 0..5); // Main text range
540        assert_eq!(result[1], 5..17); // Secondary text range
541        assert_eq!(result[2], 0..5); // First "Hello" prefix match in main text
542
543        // Test prefix with secondary text - match spans boundary (now no match since "abc" is not at start of full text)
544        let label = Label::new("abc")
545            .secondary("def abc def")
546            .highlights(HighlightsMatch::Prefix("abc".into()));
547        let total_length = "abc def abc def".len();
548        let result = label.highlight_ranges(total_length);
549        assert_eq!(result.len(), 3); // 2 for secondary + 1 for prefix match
550        assert_eq!(result[0], 0..3); // Main text range
551        assert_eq!(result[1], 3..15); // Secondary text range
552        assert_eq!(result[2], 0..3); // "abc" matches at start of full text
553
554        // Test prefix with Unicode characters
555        let label = Label::new("你好世界你好").highlights(HighlightsMatch::Prefix("你好".into()));
556        let result = label.highlight_ranges("你好世界你好".len());
557        assert_eq!(result.len(), 1);
558        assert_eq!(result[0], 0..6); // First "你好" (6 bytes in UTF-8)
559
560        // Test prefix with overlapping pattern
561        let label = Label::new("abababab").highlights(HighlightsMatch::Prefix("abab".into()));
562        let result = label.highlight_ranges("abababab".len());
563        assert_eq!(result.len(), 1);
564        assert_eq!(result[0], 0..4); // First "abab" only
565
566        // Test prefix match at different positions (now no match since "Hello" is not at start)
567        let label =
568            Label::new("xyz Hello abc Hello").highlights(HighlightsMatch::Prefix("Hello".into()));
569        let result = label.highlight_ranges("xyz Hello abc Hello".len());
570        assert_eq!(result.len(), 0); // No match since "Hello" is not at the beginning
571
572        // Test is_prefix method
573        let prefix_match = HighlightsMatch::Prefix("test".into());
574        let full_match = HighlightsMatch::Full("test".into());
575        assert!(prefix_match.is_prefix());
576        assert!(!full_match.is_prefix());
577
578        // Test as_str method for prefix
579        let prefix_match = HighlightsMatch::Prefix("test".into());
580        assert_eq!(prefix_match.as_str(), "test");
581    }
582}