BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / switcher.rs

switcher.rs

switcher.rs 26.7 KiB Download Raw
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{
3 h_flex,
4 input::{Input, InputEvent, InputState},
5 v_flex,
6};
7use std::collections::{HashMap, HashSet};
8use std::ops::Range;
9use std::time::Duration;
10
11use chrono::{Local, Offset};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14use store::SearchHit;
15use teams_core::substrate_search::{SearchSession, Suggestions};
16use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
17
18use super::avatar::{person_avatar, spec_avatar, team_avatar};
19use super::switcher_server::{
20 PersonResult, merge_messages, people_results, server_message_results,
21};
22use super::widgets::icon;
23use crate::app_state::{AppState, Selection, chat_title};
24use crate::data::{Directory, is_one_on_one};
25use crate::format;
26use crate::fuzzy;
27use crate::runtime;
28use crate::sidebar_model::{AvatarSpec, avatar_for};
29use crate::theme::{self, ElevatedSurface as _};
30
31const MAX_RESULTS: usize = 9;
32const MAX_RESULTS_WITH_MESSAGES: usize = 5;
33const MAX_MESSAGE_RESULTS: usize = 5;
34const MIN_MESSAGE_QUERY_CHARS: usize = 2;
35const MAX_PEOPLE_RESULTS: usize = 4;
36const MIN_SERVER_QUERY_CHARS: usize = 2;
37const SERVER_DEBOUNCE: Duration = Duration::from_millis(200);
38const MESSAGE_GROUP: &str = "Messages";
39const PEOPLE_GROUP: &str = "People";
40const CARD_WIDTH: f32 = 520.;
41const CARD_TOP: f32 = 6.;
42
43pub enum SwitcherEvent {
44 Pick(Selection),
45 PickMessage {
46 selection: Selection,
47 message_id: String,
48 },
49 PickPerson {
50 user_id: String,
51 },
52 Close,
53}
54
55#[derive(Clone)]
56pub struct MessageResult {
57 pub selection: Selection,
58 pub message_id: String,
59 pub author: String,
60 pub conversation: String,
61 pub date: String,
62 pub snippet: String,
63 pub matches: Vec<Range<usize>>,
64}
65
66pub fn parse_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
67 let mut text = String::with_capacity(snippet.len());
68 let mut matches = Vec::new();
69 let mut start: Option<usize> = None;
70 for character in snippet.chars() {
71 match character {
72 HIGHLIGHT_START => start = Some(text.len()),
73 HIGHLIGHT_END => {
74 if let Some(begin) = start.take().filter(|begin| *begin < text.len()) {
75 matches.push(begin..text.len());
76 }
77 }
78 '\n' | '\r' => text.push(' '),
79 other => text.push(other),
80 }
81 }
82 (text, matches)
83}
84
85pub fn message_results(
86 hits: Vec<SearchHit>,
87 conversations: &HashMap<String, (String, Selection)>,
88 today: chrono::NaiveDate,
89 offset: chrono::FixedOffset,
90) -> Vec<MessageResult> {
91 hits.into_iter()
92 .filter_map(|hit| {
93 let (conversation, selection) = conversations.get(&hit.conversation_id)?.clone();
94 let (snippet, matches) = parse_snippet(&hit.snippet);
95 Some(MessageResult {
96 selection,
97 message_id: hit.message_id,
98 author: hit.sender_name.unwrap_or_else(|| "Unknown".to_owned()),
99 conversation,
100 date: format::list_time_label(hit.created_at, today, offset),
101 snippet,
102 matches,
103 })
104 })
105 .collect()
106}
107
108#[derive(Clone)]
109pub enum CandidateAvatar {
110 Chat(AvatarSpec),
111 Team { name: String, key: String },
112}
113
114#[derive(Clone)]
115pub struct Candidate {
116 pub title: String,
117 pub subtitle: String,
118 pub avatar: CandidateAvatar,
119 pub selection: Selection,
120}
121
122impl Candidate {
123 fn group(&self) -> &'static str {
124 match self.selection {
125 Selection::Chat(_) => "Chats",
126 Selection::Channel(_) => "Channels",
127 }
128 }
129}
130
131pub struct Switcher {
132 app: Entity<AppState>,
133 input: Entity<InputState>,
134 candidates: Vec<(String, Candidate)>,
135 conversations: HashMap<String, (String, Selection)>,
136 results: Vec<Candidate>,
137 people: Vec<PersonResult>,
138 local_messages: Vec<MessageResult>,
139 messages: Vec<MessageResult>,
140 search_session: SearchSession,
141 generation: u64,
142 rows_scroll: ScrollHandle,
143 highlighted: usize,
144 _subscription: Subscription,
145}
146
147impl EventEmitter<SwitcherEvent> for Switcher {}
148
149pub fn candidates_from(state: &AppState) -> Vec<(String, Candidate)> {
150 let me = state.directory.me.as_ref();
151 let chats = state.sidebar.chats.iter().map(|chat| {
152 let title = chat_title(chat);
153 (
154 title.clone(),
155 Candidate {
156 title,
157 subtitle: if is_one_on_one(chat) {
158 "Chat".to_owned()
159 } else {
160 format!("Group chat, {} participants", chat.members.len())
161 },
162 avatar: CandidateAvatar::Chat(avatar_for(chat, me)),
163 selection: Selection::Chat(chat.id.clone()),
164 },
165 )
166 });
167 let channels = state.sidebar.teams.iter().flat_map(|team| {
168 team.channels.iter().map(|channel| {
169 (
170 format!("{} / {}", team.team.name, channel.name),
171 Candidate {
172 title: channel.name.clone(),
173 subtitle: team.team.name.clone(),
174 avatar: CandidateAvatar::Team {
175 name: team.team.name.clone(),
176 key: team.team.id.clone(),
177 },
178 selection: Selection::Channel(channel.id.clone()),
179 },
180 )
181 })
182 });
183 chats.chain(channels).collect()
184}
185
186pub fn candidate_avatar(
187 directory: &Directory,
188 avatar: &CandidateAvatar,
189 size: f32,
190 ring: Hsla,
191) -> AnyElement {
192 match avatar {
193 CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, size, ring),
194 CandidateAvatar::Team { name, key } => {
195 let photo = directory.avatar(&teams_core::team_avatar_key(key));
196 team_avatar(photo, name, key, size, size / 4.)
197 }
198 }
199}
200
201pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {
202 if length == 0 {
203 return 0;
204 }
205 (current as isize + delta).clamp(0, length as isize - 1) as usize
206}
207
208impl Switcher {
209 pub fn new(
210 app: Entity<AppState>,
211 candidates: Vec<(String, Candidate)>,
212 initial_query: &str,
213 window: &mut Window,
214 cx: &mut Context<Self>,
215 ) -> Self {
216 let input = cx.new(|cx| {
217 InputState::new(window, cx).placeholder("Jump to a chat, channel, person or message")
218 });
219 if !initial_query.is_empty() {
220 let query = initial_query.to_owned();
221 input.update(cx, |input, cx| input.set_value(query, window, cx));
222 }
223 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
224 input.update(cx, |input, cx| input.focus(window, cx));
225 let conversations = candidates
226 .iter()
227 .map(|(title, candidate)| {
228 (
229 candidate.selection.conversation_id().to_owned(),
230 (title.clone(), candidate.selection.clone()),
231 )
232 })
233 .collect();
234 let mut switcher = Switcher {
235 app,
236 input,
237 candidates,
238 conversations,
239 results: Vec::new(),
240 people: Vec::new(),
241 local_messages: Vec::new(),
242 messages: Vec::new(),
243 search_session: SearchSession::new(),
244 generation: 0,
245 rows_scroll: ScrollHandle::new(),
246 highlighted: 0,
247 _subscription: subscription,
248 };
249 switcher.refresh(initial_query, cx);
250 switcher
251 }
252
253 fn refresh(&mut self, query: &str, cx: &mut Context<Self>) {
254 let wants_messages = query.trim().chars().count() >= MIN_MESSAGE_QUERY_CHARS;
255 let limit = if wants_messages {
256 MAX_RESULTS_WITH_MESSAGES
257 } else {
258 MAX_RESULTS
259 };
260 self.results = fuzzy::rank(query, &self.candidates, limit);
261 self.results
262 .sort_by_key(|candidate| candidate.group() != "Chats");
263 self.local_messages = if wants_messages {
264 let hits = self
265 .app
266 .read(cx)
267 .store
268 .search_messages(query, None, MAX_MESSAGE_RESULTS)
269 .unwrap_or_default();
270 let now = Local::now();
271 message_results(
272 hits,
273 &self.conversations,
274 now.date_naive(),
275 now.offset().fix(),
276 )
277 } else {
278 Vec::new()
279 };
280 self.messages = self.local_messages.clone();
281 self.people.clear();
282 self.highlighted = 0;
283 self.generation += 1;
284 if query.trim().chars().count() >= MIN_SERVER_QUERY_CHARS {
285 self.schedule_server_search(query.trim().to_owned(), cx);
286 }
287 }
288
289 fn schedule_server_search(&mut self, query: String, cx: &mut Context<Self>) {
290 let Some(engine) = self.app.read(cx).engine.clone() else {
291 return;
292 };
293 let generation = self.generation;
294 let search_session = self.search_session.clone();
295 cx.spawn(async move |this, cx| {
296 cx.background_executor().timer(SERVER_DEBOUNCE).await;
297 let still_current = this
298 .update(cx, |switcher, _| switcher.generation == generation)
299 .unwrap_or(false);
300 if !still_current {
301 return;
302 }
303 let receiver = runtime::spawn(async move {
304 engine.server_suggestions(&search_session, &query).await
305 });
306 let suggestions = match receiver.await {
307 Ok(Ok(suggestions)) => suggestions,
308 _ => return,
309 };
310 this.update(cx, |switcher, cx| {
311 switcher.apply_server(generation, suggestions, cx)
312 })
313 .ok();
314 })
315 .detach();
316 }
317
318 fn apply_server(&mut self, generation: u64, suggestions: Suggestions, cx: &mut Context<Self>) {
319 if generation != self.generation {
320 return;
321 }
322 let shown_titles: HashSet<String> = self
323 .results
324 .iter()
325 .map(|candidate| candidate.title.clone())
326 .collect();
327 let my_user_id = self
328 .app
329 .read(cx)
330 .directory
331 .me
332 .as_ref()
333 .map(|me| me.user_id.clone());
334 self.people = people_results(
335 &suggestions.people,
336 &shown_titles,
337 my_user_id.as_deref(),
338 MAX_PEOPLE_RESULTS,
339 );
340 let now = Local::now();
341 let server = server_message_results(
342 &suggestions.messages,
343 &self.conversations,
344 now.date_naive(),
345 now.offset().fix(),
346 );
347 self.messages = merge_messages(&self.local_messages, server, MAX_MESSAGE_RESULTS);
348 self.highlighted = self.highlighted.min(self.result_count().saturating_sub(1));
349 cx.notify();
350 }
351
352 fn result_count(&self) -> usize {
353 self.results.len() + self.people.len() + self.messages.len()
354 }
355
356 fn on_input_event(
357 &mut self,
358 input: &Entity<InputState>,
359 event: &InputEvent,
360 _: &mut Window,
361 cx: &mut Context<Self>,
362 ) {
363 match event {
364 InputEvent::Change => {
365 let query = input.read(cx).value().to_string();
366 self.refresh(&query, cx);
367 cx.notify();
368 }
369 InputEvent::PressEnter { .. } => self.pick(cx),
370 _ => {}
371 }
372 }
373
374 fn pick(&mut self, cx: &mut Context<Self>) {
375 let person_index = self.highlighted.checked_sub(self.results.len());
376 let message_index = person_index.and_then(|index| index.checked_sub(self.people.len()));
377 if let Some(candidate) = self.results.get(self.highlighted) {
378 cx.emit(SwitcherEvent::Pick(candidate.selection.clone()));
379 } else if let Some(person) = person_index.and_then(|index| self.people.get(index)) {
380 cx.emit(SwitcherEvent::PickPerson {
381 user_id: person.user_id.clone(),
382 });
383 } else if let Some(message) = message_index.and_then(|index| self.messages.get(index))
384 {
385 cx.emit(SwitcherEvent::PickMessage {
386 selection: message.selection.clone(),
387 message_id: message.message_id.clone(),
388 });
389 } else {
390 cx.emit(SwitcherEvent::Close);
391 }
392 }
393
394 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
395 match event.keystroke.key.as_str() {
396 "down" => self.highlighted = clamp_highlight(self.highlighted, 1, self.result_count()),
397 "up" => self.highlighted = clamp_highlight(self.highlighted, -1, self.result_count()),
398 "escape" => cx.emit(SwitcherEvent::Close),
399 _ => return,
400 }
401 self.rows_scroll.scroll_to_item(row_position(
402 &self.results,
403 self.people.len(),
404 self.highlighted,
405 ));
406 cx.notify();
407 }
408}
409
410fn row_position(results: &[Candidate], people: usize, highlighted: usize) -> usize {
411 let groups = |candidates: &[Candidate]| {
412 candidates
413 .iter()
414 .enumerate()
415 .filter(|(index, candidate)| {
416 *index == 0 || candidates[index - 1].group() != candidate.group()
417 })
418 .count()
419 };
420 if highlighted < results.len() {
421 return groups(&results[..=highlighted]) + highlighted;
422 }
423 let before_people = groups(results) + results.len();
424 let person = highlighted - results.len();
425 if person < people {
426 return before_people + 1 + person;
427 }
428 let before_messages = before_people + if people > 0 { 1 + people } else { 0 };
429 before_messages + 1 + (person - people)
430}
431
432fn group_header(label: &'static str) -> AnyElement {
433 div()
434 .px(px(12.))
435 .pt(px(8.))
436 .pb(px(4.))
437 .text_size(px(11.))
438 .font_weight(FontWeight::SEMIBOLD)
439 .text_color(theme::text_muted())
440 .child(label)
441 .into_any_element()
442}
443
444impl Render for Switcher {
445 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
446 let highlighted = self.highlighted;
447 let directory = &self.app.read(cx).directory;
448 let mut rows: Vec<AnyElement> = Vec::new();
449 let mut last_group = "";
450 for (index, candidate) in self.results.iter().enumerate() {
451 if candidate.group() != last_group {
452 last_group = candidate.group();
453 rows.push(group_header(last_group));
454 }
455 let selection = candidate.selection.clone();
456 let avatar = candidate_avatar(directory, &candidate.avatar, 28., theme::popup());
457 let kind_icon = match candidate.selection {
458 Selection::Chat(_) => IconName::MessageCircle,
459 Selection::Channel(_) => IconName::Hash,
460 };
461 rows.push(
462 h_flex()
463 .id(ElementId::Name(format!("switch-{index}").into()))
464 .mx(px(6.))
465 .px(px(6.))
466 .h(px(44.))
467 .gap(px(10.))
468 .items_center()
469 .rounded(px(6.))
470 .cursor_pointer()
471 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
472 .hover(|row| row.bg(theme::popup_hover()))
473 .child(avatar)
474 .child(
475 v_flex()
476 .flex_1()
477 .min_w_0()
478 .child(
479 div()
480 .truncate()
481 .text_size(px(14.))
482 .text_color(theme::text())
483 .child(candidate.title.clone()),
484 )
485 .child(
486 div()
487 .truncate()
488 .text_size(px(12.))
489 .text_color(theme::text_muted())
490 .child(candidate.subtitle.clone()),
491 ),
492 )
493 .child(icon(kind_icon, 14., theme::text_muted()))
494 .on_click(cx.listener(move |_, _, _, cx| {
495 cx.emit(SwitcherEvent::Pick(selection.clone()));
496 }))
497 .into_any_element(),
498 );
499 }
500 if !self.people.is_empty() {
501 rows.push(group_header(PEOPLE_GROUP));
502 }
503 for (offset, person) in self.people.iter().enumerate() {
504 let index = self.results.len() + offset;
505 let user_id = person.user_id.clone();
506 rows.push(
507 h_flex()
508 .id(ElementId::Name(format!("switch-person-{index}").into()))
509 .mx(px(6.))
510 .px(px(6.))
511 .h(px(44.))
512 .gap(px(10.))
513 .items_center()
514 .rounded(px(6.))
515 .cursor_pointer()
516 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
517 .hover(|row| row.bg(theme::popup_hover()))
518 .child(person_avatar(
519 directory,
520 Some(&person.user_id),
521 &person.name,
522 28.,
523 ))
524 .child(
525 v_flex()
526 .flex_1()
527 .min_w_0()
528 .child(
529 div()
530 .truncate()
531 .text_size(px(14.))
532 .text_color(theme::text())
533 .child(person.name.clone()),
534 )
535 .when(!person.subtitle.is_empty(), |column| {
536 column.child(
537 div()
538 .truncate()
539 .text_size(px(12.))
540 .text_color(theme::text_muted())
541 .child(person.subtitle.clone()),
542 )
543 }),
544 )
545 .child(icon(IconName::User, 14., theme::text_muted()))
546 .on_click(cx.listener(move |_, _, _, cx| {
547 cx.emit(SwitcherEvent::PickPerson {
548 user_id: user_id.clone(),
549 });
550 }))
551 .into_any_element(),
552 );
553 }
554 if !self.messages.is_empty() {
555 rows.push(group_header(MESSAGE_GROUP));
556 }
557 for (offset, message) in self.messages.iter().enumerate() {
558 let index = self.results.len() + self.people.len() + offset;
559 let (selection, message_id) = (message.selection.clone(), message.message_id.clone());
560 let marks = message
561 .matches
562 .iter()
563 .map(|range| {
564 (
565 range.clone(),
566 HighlightStyle {
567 color: Some(theme::text()),
568 font_weight: Some(FontWeight::BOLD),
569 ..Default::default()
570 },
571 )
572 })
573 .collect::<Vec<_>>();
574 rows.push(
575 h_flex()
576 .id(ElementId::Name(format!("switch-message-{index}").into()))
577 .mx(px(6.))
578 .px(px(6.))
579 .h(px(52.))
580 .gap(px(10.))
581 .items_center()
582 .rounded(px(6.))
583 .cursor_pointer()
584 .when(index == highlighted, |row| row.bg(theme::popup_hover()))
585 .hover(|row| row.bg(theme::popup_hover()))
586 .child(person_avatar(directory, None, &message.author, 28.))
587 .child(
588 v_flex()
589 .flex_1()
590 .min_w_0()
591 .gap(px(1.))
592 .child(
593 h_flex()
594 .gap(px(6.))
595 .items_baseline()
596 .child(
597 div()
598 .flex_none()
599 .text_size(px(13.))
600 .font_weight(FontWeight::SEMIBOLD)
601 .text_color(theme::text())
602 .child(message.author.clone()),
603 )
604 .child(
605 div()
606 .min_w_0()
607 .truncate()
608 .text_size(px(12.))
609 .text_color(theme::text_muted())
610 .child(format!("in {}", message.conversation)),
611 )
612 .child(div().flex_1())
613 .child(
614 div()
615 .flex_none()
616 .text_size(px(11.))
617 .text_color(theme::text_muted())
618 .child(message.date.clone()),
619 ),
620 )
621 .child(
622 div()
623 .truncate()
624 .text_size(px(12.5))
625 .text_color(theme::text_soft())
626 .child(
627 StyledText::new(message.snippet.clone())
628 .with_highlights(marks),
629 ),
630 ),
631 )
632 .on_click(cx.listener(move |_, _, _, cx| {
633 cx.emit(SwitcherEvent::PickMessage {
634 selection: selection.clone(),
635 message_id: message_id.clone(),
636 });
637 }))
638 .into_any_element(),
639 );
640 }
641 let footer = h_flex()
642 .h(px(32.))
643 .px(px(12.))
644 .gap(px(16.))
645 .items_center()
646 .text_size(px(11.))
647 .text_color(theme::text_muted())
648 .child("Enter to open")
649 .child("Arrows to select")
650 .child("Esc to close");
651 div()
652 .id("switcher-backdrop")
653 .absolute()
654 .size_full()
655 .top_0()
656 .left_0()
657 .flex()
658 .justify_center()
659 .items_start()
660 .pt(px(CARD_TOP))
661 .on_click(cx.listener(|_, _, _, cx| cx.emit(SwitcherEvent::Close)))
662 .child(
663 v_flex()
664 .id("switcher-card")
665 .w(px(CARD_WIDTH))
666 .max_h(px(640.))
667 .rounded(px(10.))
668 .flyout_surface()
669 .overflow_hidden()
670 .on_click(|_, _, cx| cx.stop_propagation())
671 .on_key_down(cx.listener(Self::on_key_down))
672 .child(
673 h_flex()
674 .p(px(8.))
675 .pl(px(12.))
676 .gap(px(8.))
677 .items_center()
678 .child(icon(IconName::Search, 14., theme::text_muted()))
679 .child(
680 div()
681 .flex_1()
682 .min_w_0()
683 .child(Input::new(&self.input).appearance(false).bordered(false)),
684 ),
685 )
686 .child(
687 v_flex()
688 .id("switcher-rows")
689 .track_scroll(&self.rows_scroll)
690 .w_full()
691 .flex_1()
692 .min_h_0()
693 .overflow_y_scroll()
694 .py_1()
695 .children(rows),
696 )
697 .child(footer),
698 )
699 }
700}
701
702#[cfg(test)]
703mod tests {
704 use super::{Candidate, CandidateAvatar, clamp_highlight, parse_snippet, row_position};
705 use crate::app_state::Selection;
706 use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
707
708 #[test]
709 fn snippet_markers_become_ranges() {
710 let raw = format!("a {HIGHLIGHT_START}Build{HIGHLIGHT_END} 42\nok");
711 let (text, matches) = parse_snippet(&raw);
712 assert_eq!(text, "a Build 42 ok");
713 assert_eq!(matches, vec![2..7]);
714 }
715
716 #[test]
717 fn unterminated_or_empty_markers_are_ignored() {
718 let raw = format!("{HIGHLIGHT_START}{HIGHLIGHT_END}x{HIGHLIGHT_START}y");
719 assert_eq!(parse_snippet(&raw), ("xy".to_owned(), Vec::new()));
720 }
721
722 #[test]
723 fn highlight_stays_inside_the_list() {
724 assert_eq!(clamp_highlight(0, -1, 3), 0);
725 assert_eq!(clamp_highlight(2, 1, 3), 2);
726 assert_eq!(clamp_highlight(1, 1, 3), 2);
727 assert_eq!(clamp_highlight(0, 1, 0), 0);
728 }
729
730 fn candidate(selection: Selection) -> Candidate {
731 Candidate {
732 title: String::new(),
733 subtitle: String::new(),
734 avatar: CandidateAvatar::Team {
735 name: String::new(),
736 key: String::new(),
737 },
738 selection,
739 }
740 }
741
742 #[test]
743 fn row_positions_count_the_group_headers() {
744 let results = [
745 candidate(Selection::Chat("a".into())),
746 candidate(Selection::Chat("b".into())),
747 candidate(Selection::Channel("c".into())),
748 ];
749 assert_eq!(row_position(&results, 2, 0), 1);
750 assert_eq!(row_position(&results, 2, 2), 4);
751 assert_eq!(row_position(&results, 2, 3), 6);
752 assert_eq!(row_position(&results, 2, 5), 9);
753 assert_eq!(row_position(&results, 0, 3), 6);
754 }
755}