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#[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#[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 #[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 pub fn id(mut self, id: impl Into<ElementId>) -> Self {
98 self.id = id.into();
99 self
100 }
101
102 pub fn secondary(mut self, secondary: impl Into<SharedString>) -> Self {
105 self.secondary = Some(secondary.into());
106 self
107 }
108
109 pub fn masked(mut self, masked: bool) -> Self {
111 self.masked = masked;
112 self
113 }
114
115 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 if full_text_lower.starts_with(&search_lower) {
146 ranges.push(0..matched_str.len());
147 }
148 } else {
149 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 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 this.role(gpui::Role::Label).aria_value(text)
246 })
247 .line_height(rems(1.25))
248 .text_color(cx.theme().foreground)
249 .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
261pub(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
277fn 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
303fn 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 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 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 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); assert_eq!(result[1], 5..11); 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); 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); assert_eq!(result[1], 6..11); assert_eq!(result[2], 12..17); 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 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); assert_eq!(result[1], 5..11); assert_eq!(result[2], 2..5); 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); assert_eq!(result[1], 5..11); assert_eq!(result[2], 6..11); 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); assert_eq!(result[1], 5..11); assert_eq!(result[2], 4..7); 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); assert_eq!(result[1], 1..3); 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 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); 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); 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); assert_eq!(result_prefix[0], 0..5);
514
515 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); 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 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 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); assert_eq!(result[0], 0..5); assert_eq!(result[1], 5..17); assert_eq!(result[2], 0..5); 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); assert_eq!(result[0], 0..3); assert_eq!(result[1], 3..15); assert_eq!(result[2], 0..3); 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); 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); 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); 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 let prefix_match = HighlightsMatch::Prefix("test".into());
580 assert_eq!(prefix_match.as_str(), "test");
581 }
582}