BlueGit

ict rusty-teams

Files

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

switcher.rs

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