BlueGit

ict rusty-teams

Files

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

new_chat.rs

new_chat.rs 33.8 KiB Download Raw
1use std::collections::HashSet;
2use std::time::Duration;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 h_flex,
7 input::{Backspace, Enter, Input, InputEvent, InputState, MoveDown, MoveUp},
8 v_flex,
9};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use store::ChatRecord;
13use teams_core::MentionCandidate;
14
15use super::avatar::person_avatar;
16use super::switcher::clamp_highlight;
17use super::widgets::icon;
18use crate::app_state::AppState;
19use crate::data::{self, Directory, Person};
20use crate::runtime;
21use crate::theme::{self, ElevatedSurface as _};
22
23const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
24const SUGGESTED_LIMIT: usize = 6;
25const RESULT_LIMIT: usize = 8;
26const POPUP_WIDTH: f32 = 300.;
27const POPUP_ROW_HEIGHT: f32 = 44.;
28const CHIP_NAME_MAX_WIDTH: f32 = 180.;
29const FIELD_MIN_HEIGHT: f32 = 36.;
30const FIELD_PADDING: f32 = 8.;
31const EMPTY_ICON_SIZE: f32 = 72.;
32const NEW_CONVERSATION_TITLE: &str = "You're starting a new conversation";
33const NEW_CONVERSATION_HINT: &str = "Type your first message below.";
34const TO_PLACEHOLDER: &str = "Enter name or email";
35const DEFAULT_PLACEHOLDER: &str = "Type a message";
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct Pick {
39 pub user_id: String,
40 pub name: String,
41 pub mail: Option<String>,
42}
43
44pub enum NewChatEvent {
45 Changed,
46 FocusComposer,
47 Close,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51enum EnterAction {
52 Add,
53 Advance,
54 Nothing,
55}
56
57fn enter_action(query_is_empty: bool, chip_count: usize, has_highlighted: bool) -> EnterAction {
58 match (query_is_empty, chip_count, has_highlighted) {
59 (true, 1.., _) => EnterAction::Advance,
60 (_, _, true) => EnterAction::Add,
61 _ => EnterAction::Nothing,
62 }
63}
64
65fn people_in(chats: &[ChatRecord], me: Option<&Person>, one_on_one_only: bool) -> Vec<Pick> {
66 let mut ordered: Vec<&ChatRecord> = chats
67 .iter()
68 .filter(|chat| !one_on_one_only || data::is_one_on_one(chat))
69 .collect();
70 ordered.sort_by_key(|chat| std::cmp::Reverse(chat.last_message_at));
71 let mut seen = HashSet::new();
72 ordered
73 .into_iter()
74 .flat_map(|chat| data::others(chat, me))
75 .filter_map(|(user_id, name)| {
76 let user_id = user_id.filter(|user_id| seen.insert(user_id.clone()))?;
77 Some(Pick {
78 user_id,
79 name,
80 mail: None,
81 })
82 })
83 .collect()
84}
85
86fn not_chosen(pick: &Pick, me: Option<&Person>, chosen: &[Pick]) -> bool {
87 me.is_none_or(|me| me.user_id != pick.user_id)
88 && chosen.iter().all(|chip| chip.user_id != pick.user_id)
89}
90
91fn without_excluded(picks: Vec<Pick>, excluded: &[String]) -> Vec<Pick> {
92 picks
93 .into_iter()
94 .filter(|pick| !excluded.contains(&pick.user_id))
95 .collect()
96}
97
98pub fn suggested_people(
99 chats: &[ChatRecord],
100 me: Option<&Person>,
101 chosen: &[Pick],
102 limit: usize,
103) -> Vec<Pick> {
104 people_in(chats, me, true)
105 .into_iter()
106 .filter(|pick| not_chosen(pick, me, chosen))
107 .take(limit)
108 .collect()
109}
110
111fn matches_query(pick: &Pick, query: &str) -> bool {
112 let needle = query.trim().to_lowercase();
113 pick.name.to_lowercase().contains(&needle)
114 || pick
115 .mail
116 .as_ref()
117 .is_some_and(|mail| mail.to_lowercase().contains(&needle))
118}
119
120pub fn search_results(
121 known: Vec<Pick>,
122 remote: Vec<Pick>,
123 query: &str,
124 me: Option<&Person>,
125 chosen: &[Pick],
126 limit: usize,
127) -> Vec<Pick> {
128 let mut seen = HashSet::new();
129 known
130 .into_iter()
131 .filter(|pick| matches_query(pick, query))
132 .chain(remote)
133 .filter(|pick| not_chosen(pick, me, chosen) && seen.insert(pick.user_id.clone()))
134 .take(limit)
135 .collect()
136}
137
138pub fn composer_placeholder(chips: &[Pick], group_name: &str) -> String {
139 match chips {
140 [chip] => format!("Message {}", chip.name),
141 [_, _, ..] if !group_name.trim().is_empty() => format!("Message {}", group_name.trim()),
142 _ => DEFAULT_PLACEHOLDER.to_owned(),
143 }
144}
145
146fn pick_from_user(user: graph::User) -> Option<Pick> {
147 let mail = user.mail.or(user.user_principal_name);
148 let name = user.display_name.or_else(|| mail.clone())?;
149 Some(Pick {
150 user_id: user.id,
151 name,
152 mail,
153 })
154}
155
156fn pick_from_candidate(candidate: MentionCandidate) -> Option<Pick> {
157 match candidate {
158 MentionCandidate::Person(person) => Some(Pick {
159 user_id: person.user_id,
160 name: person.display_name,
161 mail: person.mail,
162 }),
163 _ => None,
164 }
165}
166
167pub struct NewChatDraft {
168 app: Entity<AppState>,
169 query: Entity<InputState>,
170 name: Entity<InputState>,
171 chips: Vec<Pick>,
172 excluded: Vec<String>,
173 form_field: bool,
174 remote: Vec<Pick>,
175 highlighted: usize,
176 popup_open: bool,
177 searching: bool,
178 search_failed: bool,
179 generation: u64,
180 search: Option<Task<()>>,
181 _subscriptions: Vec<Subscription>,
182}
183
184impl EventEmitter<NewChatEvent> for NewChatDraft {}
185
186impl NewChatDraft {
187 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
188 let query = cx.new(|cx| InputState::new(window, cx).placeholder(TO_PLACEHOLDER));
189 let name = cx.new(|cx| InputState::new(window, cx).placeholder("Group name (optional)"));
190 let subscriptions = vec![
191 cx.subscribe_in(&query, window, Self::on_query_event),
192 cx.subscribe_in(&name, window, Self::on_name_event),
193 ];
194 NewChatDraft {
195 app,
196 query,
197 name,
198 chips: Vec::new(),
199 excluded: Vec::new(),
200 form_field: false,
201 remote: Vec::new(),
202 highlighted: 0,
203 popup_open: true,
204 searching: false,
205 search_failed: false,
206 generation: 0,
207 search: None,
208 _subscriptions: subscriptions,
209 }
210 }
211
212 pub fn compact(mut self) -> Self {
213 self.form_field = true;
214 self.popup_open = false;
215 self
216 }
217
218 pub fn excluding(mut self, user_ids: Vec<String>) -> Self {
219 self.excluded = user_ids;
220 self
221 }
222
223 pub fn chips(&self) -> &[Pick] {
224 &self.chips
225 }
226
227 pub fn set_chips(&mut self, chips: Vec<Pick>, cx: &mut Context<Self>) {
228 self.chips = chips;
229 self.highlighted = 0;
230 cx.emit(NewChatEvent::Changed);
231 cx.notify();
232 }
233
234 pub fn group_name(&self, cx: &App) -> String {
235 self.name.read(cx).value().trim().to_owned()
236 }
237
238 pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
239 self.chips.clear();
240 self.query
241 .update(cx, |input, cx| input.set_value("", window, cx));
242 self.name
243 .update(cx, |input, cx| input.set_value("", window, cx));
244 self.on_query_changed(cx);
245 }
246
247 pub fn focus_query(&self, window: &mut Window, cx: &mut Context<Self>) {
248 self.query.update(cx, |input, cx| input.focus(window, cx));
249 }
250
251 pub fn has_focus(&self, window: &Window, cx: &App) -> bool {
252 self.query.focus_handle(cx).is_focused(window)
253 || self.name.focus_handle(cx).is_focused(window)
254 }
255
256 pub fn escape(&mut self, cx: &mut Context<Self>) {
257 if self.popup_visible(cx) {
258 self.popup_open = false;
259 cx.notify();
260 } else {
261 cx.emit(NewChatEvent::Close);
262 }
263 }
264
265 fn query_text(&self, cx: &App) -> String {
266 self.query.read(cx).value().trim().to_owned()
267 }
268
269 fn results(&self, cx: &App) -> Vec<Pick> {
270 let state = self.app.read(cx);
271 let me = state.directory.me.as_ref();
272 let query = self.query_text(cx);
273 if query.is_empty() {
274 let suggested = suggested_people(
275 &state.sidebar.chats,
276 me,
277 &self.chips,
278 SUGGESTED_LIMIT + self.excluded.len(),
279 );
280 let mut suggested = without_excluded(suggested, &self.excluded);
281 suggested.truncate(SUGGESTED_LIMIT);
282 return suggested;
283 }
284 search_results(
285 without_excluded(people_in(&state.sidebar.chats, me, false), &self.excluded),
286 without_excluded(self.remote.clone(), &self.excluded),
287 &query,
288 me,
289 &self.chips,
290 RESULT_LIMIT,
291 )
292 }
293
294 fn popup_visible(&self, cx: &App) -> bool {
295 self.popup_open && (!self.results(cx).is_empty() || !self.query_text(cx).is_empty())
296 }
297
298 fn on_query_event(
299 &mut self,
300 _: &Entity<InputState>,
301 event: &InputEvent,
302 _: &mut Window,
303 cx: &mut Context<Self>,
304 ) {
305 match event {
306 InputEvent::Change => self.on_query_changed(cx),
307 InputEvent::Focus => {
308 self.popup_open = true;
309 cx.notify();
310 }
311 InputEvent::Blur => {
312 self.popup_open = false;
313 cx.notify();
314 }
315 InputEvent::PressEnter { .. } => {}
316 }
317 }
318
319 fn on_name_event(
320 &mut self,
321 _: &Entity<InputState>,
322 event: &InputEvent,
323 _: &mut Window,
324 cx: &mut Context<Self>,
325 ) {
326 match event {
327 InputEvent::Change => cx.emit(NewChatEvent::Changed),
328 InputEvent::PressEnter { .. } => cx.emit(NewChatEvent::FocusComposer),
329 InputEvent::Focus | InputEvent::Blur => {}
330 }
331 cx.notify();
332 }
333
334 fn on_query_changed(&mut self, cx: &mut Context<Self>) {
335 self.popup_open = true;
336 self.highlighted = 0;
337 self.generation += 1;
338 self.search = None;
339 self.searching = false;
340 self.search_failed = false;
341 self.remote.clear();
342 let query = self.query_text(cx);
343 let (demo, engine) = {
344 let state = self.app.read(cx);
345 (state.mode.demo, state.engine.clone())
346 };
347 if !query.is_empty() {
348 if demo {
349 self.remote = crate::demo::mention_candidates("", &query)
350 .into_iter()
351 .filter_map(pick_from_candidate)
352 .collect();
353 } else if let Some(engine) = engine {
354 self.searching = true;
355 let generation = self.generation;
356 self.search = Some(cx.spawn(async move |this, cx| {
357 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
358 let receiver =
359 runtime::spawn(async move { engine.search_people(&query).await });
360 let result = receiver.await;
361 this.update(cx, |this, cx| this.apply_search(generation, result, cx))
362 .ok();
363 }));
364 }
365 }
366 cx.notify();
367 }
368
369 fn apply_search(
370 &mut self,
371 generation: u64,
372 result: Result<
373 teams_core::Result<Vec<graph::User>>,
374 tokio::sync::oneshot::error::RecvError,
375 >,
376 cx: &mut Context<Self>,
377 ) {
378 if generation != self.generation {
379 return;
380 }
381 self.searching = false;
382 let held = self
383 .results(cx)
384 .into_iter()
385 .nth(self.highlighted)
386 .map(|pick| pick.user_id);
387 match result {
388 Ok(Ok(users)) => self.remote = users.into_iter().filter_map(pick_from_user).collect(),
389 _ => self.search_failed = true,
390 }
391 self.highlighted = held
392 .and_then(|user_id| {
393 self.results(cx)
394 .iter()
395 .position(|pick| pick.user_id == user_id)
396 })
397 .unwrap_or(0);
398 cx.notify();
399 }
400
401 fn add(&mut self, pick: Pick, window: &mut Window, cx: &mut Context<Self>) {
402 if self.chips.iter().all(|chip| chip.user_id != pick.user_id) {
403 self.chips.push(pick);
404 }
405 self.query
406 .update(cx, |input, cx| input.set_value("", window, cx));
407 self.on_query_changed(cx);
408 cx.emit(NewChatEvent::Changed);
409 }
410
411 fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
412 if index < self.chips.len() {
413 self.chips.remove(index);
414 self.highlighted = 0;
415 cx.emit(NewChatEvent::Changed);
416 cx.notify();
417 }
418 }
419
420 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
421 let length = self.results(cx).len();
422 self.highlighted = clamp_highlight(self.highlighted, delta, length);
423 cx.notify();
424 }
425
426 fn accept(&mut self, window: &mut Window, cx: &mut Context<Self>) {
427 let highlighted = self
428 .popup_open
429 .then(|| self.results(cx).into_iter().nth(self.highlighted))
430 .flatten();
431 let action = enter_action(
432 self.query_text(cx).is_empty(),
433 self.chips.len(),
434 highlighted.is_some(),
435 );
436 match (action, highlighted) {
437 (EnterAction::Add, Some(pick)) => self.add(pick, window, cx),
438 (EnterAction::Advance, _) if self.chips.len() >= 2 && !self.form_field => {
439 self.popup_open = false;
440 self.name.update(cx, |input, cx| input.focus(window, cx));
441 cx.notify();
442 }
443 (EnterAction::Advance, _) => {
444 self.popup_open = false;
445 cx.emit(NewChatEvent::FocusComposer);
446 cx.notify();
447 }
448 _ => {}
449 }
450 }
451
452 fn backspace(&mut self, cx: &mut Context<Self>) -> bool {
453 if !self.query_text(cx).is_empty() || self.chips.is_empty() {
454 return false;
455 }
456 self.remove(self.chips.len() - 1, cx);
457 true
458 }
459
460 fn render_chip(&self, index: usize, chip: &Pick, cx: &mut Context<Self>) -> impl IntoElement {
461 let directory = &self.app.read(cx).directory;
462 h_flex()
463 .id(ElementId::Name(format!("new-chat-chip-{index}").into()))
464 .h(px(26.))
465 .pl(px(3.))
466 .pr(px(4.))
467 .gap(px(6.))
468 .items_center()
469 .rounded(px(13.))
470 .bg(theme::surface_raised())
471 .child(person_avatar(
472 directory,
473 Some(&chip.user_id),
474 &chip.name,
475 20.,
476 ))
477 .child(
478 div()
479 .max_w(px(CHIP_NAME_MAX_WIDTH))
480 .truncate()
481 .text_size(px(13.))
482 .text_color(theme::text())
483 .child(chip.name.clone()),
484 )
485 .child(
486 div()
487 .id(ElementId::Name(
488 format!("new-chat-chip-remove-{index}").into(),
489 ))
490 .size(px(18.))
491 .flex()
492 .items_center()
493 .justify_center()
494 .rounded_full()
495 .cursor_pointer()
496 .hover(|button| button.bg(theme::row_hover()))
497 .child(icon(IconName::Close, 12., theme::text_muted()))
498 .on_click(cx.listener(move |this, _, _, cx| this.remove(index, cx))),
499 )
500 }
501
502 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
503 if !self.popup_visible(cx) {
504 return None;
505 }
506 let results = self.results(cx);
507 let query = self.query_text(cx);
508 let directory = &self.app.read(cx).directory;
509 let label = if query.is_empty() {
510 "Suggested"
511 } else {
512 "People"
513 };
514 let rows = results.into_iter().enumerate().map(|(index, pick)| {
515 let detail = pick.mail.clone().unwrap_or_default();
516 let chosen = pick.clone();
517 h_flex()
518 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
519 .px(px(6.))
520 .h(px(POPUP_ROW_HEIGHT))
521 .flex_none()
522 .gap(px(8.))
523 .items_center()
524 .rounded(px(6.))
525 .cursor_pointer()
526 .when(index == self.highlighted, |row| {
527 row.bg(theme::popup_hover())
528 })
529 .hover(|row| row.bg(theme::popup_hover()))
530 .child(person_avatar(
531 directory,
532 Some(&pick.user_id),
533 &pick.name,
534 28.,
535 ))
536 .child(
537 v_flex()
538 .flex_1()
539 .min_w_0()
540 .child(
541 div()
542 .truncate()
543 .text_size(px(13.))
544 .text_color(theme::text())
545 .child(pick.name.clone()),
546 )
547 .when(!detail.is_empty(), |column| {
548 column.child(
549 div()
550 .truncate()
551 .text_size(px(11.5))
552 .text_color(theme::text_muted())
553 .child(detail),
554 )
555 }),
556 )
557 .on_click(cx.listener(move |this, _, window, cx| {
558 this.add(chosen.clone(), window, cx);
559 }))
560 });
561 let note = |text: String, color: Hsla| {
562 div()
563 .px(px(6.))
564 .py(px(8.))
565 .text_size(px(12.))
566 .text_color(color)
567 .child(text)
568 };
569 let results_empty = self.results(cx).is_empty();
570 let panel = v_flex()
571 .id("new-chat-popup")
572 .mt(px(4.))
573 .p(px(6.))
574 .rounded(px(10.))
575 .flyout_surface()
576 .occlude()
577 .when(!results_empty, |popup| {
578 popup.child(
579 div()
580 .px(px(6.))
581 .pb(px(4.))
582 .text_size(px(11.))
583 .font_weight(FontWeight::SEMIBOLD)
584 .text_color(theme::text_muted())
585 .child(label),
586 )
587 })
588 .children(rows)
589 .when(self.search_failed, |popup| {
590 popup.child(note("Search failed".to_owned(), theme::red_soft()))
591 })
592 .when(self.searching && results_empty, |popup| {
593 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
594 })
595 .when(
596 !self.searching && !self.search_failed && results_empty,
597 |popup| {
598 popup.child(note(
599 format!("No people found for \"{query}\""),
600 theme::text_muted(),
601 ))
602 },
603 );
604 if self.form_field {
605 return Some(panel.w_full().into_any_element());
606 }
607 Some(
608 deferred(
609 panel
610 .absolute()
611 .top(relative(1.))
612 .left(px(20.))
613 .w(px(POPUP_WIDTH)),
614 )
615 .with_priority(1)
616 .into_any_element(),
617 )
618 }
619
620 fn render_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
621 let chips: Vec<AnyElement> = self
622 .chips
623 .iter()
624 .enumerate()
625 .map(|(index, chip)| self.render_chip(index, chip, cx).into_any_element())
626 .collect();
627 h_flex()
628 .relative()
629 .w_full()
630 .min_h(px(if self.form_field {
631 FIELD_MIN_HEIGHT
632 } else {
633 60.
634 }))
635 .flex_none()
636 .px(px(if self.form_field { FIELD_PADDING } else { 20. }))
637 .py(px(if self.form_field { 4. } else { 8. }))
638 .gap(px(8.))
639 .flex_wrap()
640 .items_center()
641 .child(
642 div()
643 .text_size(px(14.))
644 .text_color(theme::text_muted())
645 .child("To:"),
646 )
647 .children(chips)
648 .child(
649 div()
650 .flex_1()
651 .min_w(px(160.))
652 .child(Input::new(&self.query).appearance(false).bordered(false)),
653 )
654 .children(if self.form_field {
655 None
656 } else {
657 self.render_popup(cx)
658 })
659 }
660
661 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
662 if self.chips.len() < 2 || self.form_field {
663 return None;
664 }
665 let focused = self.name.focus_handle(cx).is_focused(window);
666 Some(
667 h_flex()
668 .w_full()
669 .flex_none()
670 .px(px(20.))
671 .py(px(8.))
672 .gap(px(8.))
673 .items_center()
674 .child(
675 div()
676 .text_size(px(14.))
677 .text_color(theme::text_muted())
678 .child("Name"),
679 )
680 .child(
681 div()
682 .flex_1()
683 .h(px(32.))
684 .px(px(12.))
685 .flex()
686 .items_center()
687 .rounded(px(8.))
688 .bg(theme::surface_raised())
689 .border_1()
690 .border_color(if focused {
691 theme::accent()
692 } else {
693 transparent_black()
694 })
695 .child(
696 div()
697 .w_full()
698 .child(Input::new(&self.name).appearance(false).bordered(false)),
699 ),
700 ),
701 )
702 }
703
704 pub fn render_empty(&self, directory: &Directory, group_name: &str) -> AnyElement {
705 let column = v_flex()
706 .size_full()
707 .items_center()
708 .justify_center()
709 .gap(px(8.));
710 match self.chips.as_slice() {
711 [] => column
712 .child(
713 div()
714 .size(px(EMPTY_ICON_SIZE))
715 .flex()
716 .items_center()
717 .justify_center()
718 .rounded_full()
719 .bg(theme::surface_raised())
720 .child(icon(IconName::MessageSquare, 32., theme::accent_text())),
721 )
722 .child(
723 div()
724 .pt(px(8.))
725 .text_size(px(15.))
726 .font_weight(FontWeight::SEMIBOLD)
727 .text_color(theme::text())
728 .child(NEW_CONVERSATION_TITLE),
729 )
730 .child(
731 div()
732 .text_size(px(13.))
733 .text_color(theme::text_muted())
734 .child(NEW_CONVERSATION_HINT),
735 )
736 .into_any_element(),
737 [chip] => column
738 .child(person_avatar(
739 directory,
740 Some(&chip.user_id),
741 &chip.name,
742 56.,
743 ))
744 .child(
745 div()
746 .text_size(px(16.))
747 .font_weight(FontWeight::SEMIBOLD)
748 .text_color(theme::text())
749 .child(chip.name.clone()),
750 )
751 .child(
752 div()
753 .text_size(px(12.))
754 .text_color(theme::text_muted())
755 .child("No messages yet. Say hi."),
756 )
757 .into_any_element(),
758 chips => {
759 let title = group_name.trim();
760 column
761 .when(!title.is_empty(), |column| {
762 column.child(
763 div()
764 .text_size(px(16.))
765 .font_weight(FontWeight::SEMIBOLD)
766 .text_color(theme::text())
767 .child(title.to_owned()),
768 )
769 })
770 .child(
771 div()
772 .text_size(px(13.))
773 .text_color(theme::text_muted())
774 .child(format!(
775 "New group chat with you and {} people",
776 chips.len()
777 )),
778 )
779 .into_any_element()
780 }
781 }
782 }
783}
784
785impl Render for NewChatDraft {
786 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
787 let faces: Vec<String> = self
788 .chips
789 .iter()
790 .map(|chip| chip.user_id.clone())
791 .chain(self.results(cx).into_iter().map(|pick| pick.user_id))
792 .collect();
793 let app = self.app.clone();
794 cx.defer(move |cx| {
795 app.update(cx, |state, cx| state.request_avatars(faces, cx));
796 });
797 v_flex()
798 .w_full()
799 .flex_none()
800 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
801 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
802 this.move_highlight(-1, cx);
803 cx.stop_propagation();
804 }
805 }))
806 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
807 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
808 this.move_highlight(1, cx);
809 cx.stop_propagation();
810 }
811 }))
812 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
813 if this.query.focus_handle(cx).is_focused(window) {
814 this.accept(window, cx);
815 cx.stop_propagation();
816 }
817 }))
818 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
819 if this.query.focus_handle(cx).is_focused(window) && this.backspace(cx) {
820 cx.stop_propagation();
821 }
822 }))
823 .child(self.render_bar(cx))
824 .children(if self.form_field {
825 self.render_popup(cx)
826 } else {
827 None
828 })
829 .children(self.render_name_row(window, cx))
830 }
831}
832
833#[cfg(test)]
834mod tests {
835 use chrono::{TimeZone, Utc};
836 use store::{ChatRecord, MemberRecord};
837
838 use super::{
839 EnterAction, Pick, composer_placeholder, enter_action, search_results, suggested_people,
840 };
841 use crate::data::{Person, existing_one_on_one};
842
843 fn me() -> Person {
844 Person {
845 user_id: "me".into(),
846 display_name: "Me".into(),
847 }
848 }
849
850 fn pick(user_id: &str, name: &str, mail: Option<&str>) -> Pick {
851 Pick {
852 user_id: user_id.into(),
853 name: name.into(),
854 mail: mail.map(str::to_owned),
855 }
856 }
857
858 fn chat(id: &str, kind: &str, members: &[(&str, &str)], day: u32) -> ChatRecord {
859 ChatRecord {
860 id: id.into(),
861 kind: kind.into(),
862 members: members
863 .iter()
864 .map(|(user_id, name)| MemberRecord {
865 user_id: Some((*user_id).into()),
866 display_name: (*name).into(),
867 })
868 .collect(),
869 last_message_at: Some(Utc.with_ymd_and_hms(2026, 1, day, 9, 0, 0).unwrap()),
870 ..Default::default()
871 }
872 }
873
874 fn chats() -> Vec<ChatRecord> {
875 vec![
876 chat("old", "oneOnOne", &[("me", "Me"), ("ann", "Ann")], 1),
877 chat("new", "oneOnOne", &[("me", "Me"), ("bob", "Bob")], 5),
878 chat(
879 "group",
880 "group",
881 &[("me", "Me"), ("cid", "Cid"), ("ann", "Ann")],
882 9,
883 ),
884 ]
885 }
886
887 #[test]
888 fn suggestions_are_recent_one_on_one_partners() {
889 let found = suggested_people(&chats(), Some(&me()), &[], 6);
890 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
891 assert_eq!(ids, ["bob", "ann"]);
892 }
893
894 #[test]
895 fn suggestions_skip_chosen_people_and_respect_the_limit() {
896 let chosen = [pick("bob", "Bob", None)];
897 let found = suggested_people(&chats(), Some(&me()), &chosen, 6);
898 assert_eq!(found.len(), 1);
899 assert_eq!(found[0].user_id, "ann");
900 assert_eq!(suggested_people(&chats(), Some(&me()), &[], 1).len(), 1);
901 }
902
903 #[test]
904 fn search_puts_local_matches_first_and_dedupes() {
905 let known = vec![pick("ann", "Ann Local", None), pick("cid", "Cid", None)];
906 let remote = vec![
907 pick("ann", "Ann Remote", Some("ann@example.com")),
908 pick("anna", "Anna", Some("anna@example.com")),
909 pick("me", "Me Anna", None),
910 ];
911 let found = search_results(known, remote, "ann", Some(&me()), &[], 8);
912 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
913 assert_eq!(ids, ["ann", "anna"]);
914 assert_eq!(found[0].name, "Ann Local");
915 }
916
917 #[test]
918 fn search_excludes_chosen_people_and_caps_the_list() {
919 let remote: Vec<Pick> = (0..12)
920 .map(|index| pick(&format!("u{index}"), &format!("User {index}"), None))
921 .collect();
922 let chosen = [pick("u0", "User 0", None)];
923 let found = search_results(Vec::new(), remote, "user", None, &chosen, 8);
924 assert_eq!(found.len(), 8);
925 assert!(found.iter().all(|pick| pick.user_id != "u0"));
926 }
927
928 #[test]
929 fn local_search_matches_the_mail_address() {
930 let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];
931 let found = search_results(known, Vec::new(), "nowak", None, &[], 8);
932 assert_eq!(found.len(), 1);
933 }
934
935 #[test]
936 fn existing_chat_is_found_only_for_one_on_one() {
937 let chats = chats();
938 let found = existing_one_on_one(&chats, Some(&me()), "ann").map(|chat| chat.id.as_str());
939 assert_eq!(found, Some("old"));
940 assert!(existing_one_on_one(&chats, Some(&me()), "cid").is_none());
941 }
942
943 #[test]
944 fn placeholder_follows_the_recipients() {
945 let one = [pick("ann", "Ann", None)];
946 let two = [pick("ann", "Ann", None), pick("bob", "Bob", None)];
947 assert_eq!(composer_placeholder(&[], ""), "Type a message");
948 assert_eq!(composer_placeholder(&one, "ignored"), "Message Ann");
949 assert_eq!(composer_placeholder(&two, " "), "Type a message");
950 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
951 }
952
953 #[test]
954 fn excluded_people_are_filtered_out() {
955 let picks = vec![pick("ann", "Ann", None), pick("bob", "Bob", None)];
956 let kept = super::without_excluded(picks, &["ann".to_owned()]);
957 assert_eq!(kept, [pick("bob", "Bob", None)]);
958 }
959
960 #[test]
961 fn enter_adds_the_highlight_or_moves_on() {
962 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
963 assert_eq!(enter_action(true, 0, true), EnterAction::Add);
964 assert_eq!(enter_action(true, 1, true), EnterAction::Advance);
965 assert_eq!(enter_action(false, 2, false), EnterAction::Nothing);
966 assert_eq!(enter_action(true, 0, false), EnterAction::Nothing);
967 }
968
969 mod keys {
970 use std::sync::Arc;
971
972 use gpui_kit::test::TestWindowExt as _;
973 use gpui_kit::{AppContext as _, Entity, TestAppContext, WindowOptions};
974 use store::Store;
975
976 use super::super::NewChatDraft;
977 use crate::app_state::{AppState, Mode};
978
979 fn open(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<NewChatDraft>) {
980 cx.update(gpui_kit::init);
981 let store = Arc::new(Store::open_in_memory().unwrap());
982 crate::demo::seed(&store);
983 let mode = Mode {
984 demo: true,
985 read_only: false,
986 demo_sync: None,
987 };
988 cx.update(|cx| {
989 let app = cx.new(|_| {
990 let mut state = AppState::new(store, mode);
991 crate::demo::seed_directory(&mut state);
992 state
993 });
994 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
995 cx.new(|cx| NewChatDraft::new(app, window, cx))
996 })
997 .unwrap()
998 })
999 }
1000
1001 #[gpui_kit::test]
1002 fn enter_adds_a_chip_and_backspace_removes_it(cx: &mut TestAppContext) {
1003 let (handle, draft) = open(cx);
1004 let names = cx
1005 .update_window(handle, |_, window, cx| {
1006 draft.update(cx, |draft, cx| draft.focus_query(window, cx));
1007 window.render_frame(cx);
1008 window.input("mara", cx);
1009 window.render_frame(cx);
1010 window.press("enter", cx);
1011 window.render_frame(cx);
1012 let added: Vec<String> = draft
1013 .read(cx)
1014 .chips()
1015 .iter()
1016 .map(|chip| chip.name.clone())
1017 .collect();
1018 window.press("backspace", cx);
1019 window.render_frame(cx);
1020 (added, draft.read(cx).chips().len())
1021 })
1022 .unwrap();
1023 assert_eq!(names.0, ["Mara Lindqvist"]);
1024 assert_eq!(names.1, 0);
1025 }
1026 }
1027}