BlueGit

ict rusty-teams

Files

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

new_chat.rs

89933010 History
new_chat.rs 33.5 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 match result {
383 Ok(Ok(users)) => self.remote = users.into_iter().filter_map(pick_from_user).collect(),
384 _ => self.search_failed = true,
385 }
386 self.highlighted = 0;
387 cx.notify();
388 }
389
390 fn add(&mut self, pick: Pick, window: &mut Window, cx: &mut Context<Self>) {
391 if self.chips.iter().all(|chip| chip.user_id != pick.user_id) {
392 self.chips.push(pick);
393 }
394 self.query
395 .update(cx, |input, cx| input.set_value("", window, cx));
396 self.on_query_changed(cx);
397 cx.emit(NewChatEvent::Changed);
398 }
399
400 fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
401 if index < self.chips.len() {
402 self.chips.remove(index);
403 self.highlighted = 0;
404 cx.emit(NewChatEvent::Changed);
405 cx.notify();
406 }
407 }
408
409 fn move_highlight(&mut self, delta: isize, cx: &mut Context<Self>) {
410 let length = self.results(cx).len();
411 self.highlighted = clamp_highlight(self.highlighted, delta, length);
412 cx.notify();
413 }
414
415 fn accept(&mut self, window: &mut Window, cx: &mut Context<Self>) {
416 let highlighted = self
417 .popup_open
418 .then(|| self.results(cx).into_iter().nth(self.highlighted))
419 .flatten();
420 let action = enter_action(
421 self.query_text(cx).is_empty(),
422 self.chips.len(),
423 highlighted.is_some(),
424 );
425 match (action, highlighted) {
426 (EnterAction::Add, Some(pick)) => self.add(pick, window, cx),
427 (EnterAction::Advance, _) if self.chips.len() >= 2 && !self.form_field => {
428 self.popup_open = false;
429 self.name.update(cx, |input, cx| input.focus(window, cx));
430 cx.notify();
431 }
432 (EnterAction::Advance, _) => {
433 self.popup_open = false;
434 cx.emit(NewChatEvent::FocusComposer);
435 cx.notify();
436 }
437 _ => {}
438 }
439 }
440
441 fn backspace(&mut self, cx: &mut Context<Self>) -> bool {
442 if !self.query_text(cx).is_empty() || self.chips.is_empty() {
443 return false;
444 }
445 self.remove(self.chips.len() - 1, cx);
446 true
447 }
448
449 fn render_chip(&self, index: usize, chip: &Pick, cx: &mut Context<Self>) -> impl IntoElement {
450 let directory = &self.app.read(cx).directory;
451 h_flex()
452 .id(ElementId::Name(format!("new-chat-chip-{index}").into()))
453 .h(px(26.))
454 .pl(px(3.))
455 .pr(px(4.))
456 .gap(px(6.))
457 .items_center()
458 .rounded(px(13.))
459 .bg(theme::surface_raised())
460 .child(person_avatar(
461 directory,
462 Some(&chip.user_id),
463 &chip.name,
464 20.,
465 ))
466 .child(
467 div()
468 .max_w(px(CHIP_NAME_MAX_WIDTH))
469 .truncate()
470 .text_size(px(13.))
471 .text_color(theme::text())
472 .child(chip.name.clone()),
473 )
474 .child(
475 div()
476 .id(ElementId::Name(
477 format!("new-chat-chip-remove-{index}").into(),
478 ))
479 .size(px(18.))
480 .flex()
481 .items_center()
482 .justify_center()
483 .rounded_full()
484 .cursor_pointer()
485 .hover(|button| button.bg(theme::row_hover()))
486 .child(icon(IconName::Close, 12., theme::text_muted()))
487 .on_click(cx.listener(move |this, _, _, cx| this.remove(index, cx))),
488 )
489 }
490
491 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
492 if !self.popup_visible(cx) {
493 return None;
494 }
495 let results = self.results(cx);
496 let query = self.query_text(cx);
497 let directory = &self.app.read(cx).directory;
498 let label = if query.is_empty() {
499 "Suggested"
500 } else {
501 "People"
502 };
503 let rows = results.into_iter().enumerate().map(|(index, pick)| {
504 let detail = pick.mail.clone().unwrap_or_default();
505 let chosen = pick.clone();
506 h_flex()
507 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
508 .px(px(6.))
509 .h(px(POPUP_ROW_HEIGHT))
510 .flex_none()
511 .gap(px(8.))
512 .items_center()
513 .rounded(px(6.))
514 .cursor_pointer()
515 .when(index == self.highlighted, |row| {
516 row.bg(theme::popup_hover())
517 })
518 .hover(|row| row.bg(theme::popup_hover()))
519 .child(person_avatar(
520 directory,
521 Some(&pick.user_id),
522 &pick.name,
523 28.,
524 ))
525 .child(
526 v_flex()
527 .flex_1()
528 .min_w_0()
529 .child(
530 div()
531 .truncate()
532 .text_size(px(13.))
533 .text_color(theme::text())
534 .child(pick.name.clone()),
535 )
536 .when(!detail.is_empty(), |column| {
537 column.child(
538 div()
539 .truncate()
540 .text_size(px(11.5))
541 .text_color(theme::text_muted())
542 .child(detail),
543 )
544 }),
545 )
546 .on_click(cx.listener(move |this, _, window, cx| {
547 this.add(chosen.clone(), window, cx);
548 }))
549 });
550 let note = |text: String, color: Hsla| {
551 div()
552 .px(px(6.))
553 .py(px(8.))
554 .text_size(px(12.))
555 .text_color(color)
556 .child(text)
557 };
558 let results_empty = self.results(cx).is_empty();
559 let panel = v_flex()
560 .id("new-chat-popup")
561 .mt(px(4.))
562 .p(px(6.))
563 .rounded(px(10.))
564 .flyout_surface()
565 .occlude()
566 .when(!results_empty, |popup| {
567 popup.child(
568 div()
569 .px(px(6.))
570 .pb(px(4.))
571 .text_size(px(11.))
572 .font_weight(FontWeight::SEMIBOLD)
573 .text_color(theme::text_muted())
574 .child(label),
575 )
576 })
577 .children(rows)
578 .when(self.search_failed, |popup| {
579 popup.child(note("Search failed".to_owned(), theme::red_soft()))
580 })
581 .when(self.searching && results_empty, |popup| {
582 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
583 })
584 .when(
585 !self.searching && !self.search_failed && results_empty,
586 |popup| {
587 popup.child(note(
588 format!("No people found for \"{query}\""),
589 theme::text_muted(),
590 ))
591 },
592 );
593 if self.form_field {
594 return Some(panel.w_full().into_any_element());
595 }
596 Some(
597 deferred(
598 panel
599 .absolute()
600 .top(relative(1.))
601 .left(px(20.))
602 .w(px(POPUP_WIDTH)),
603 )
604 .with_priority(1)
605 .into_any_element(),
606 )
607 }
608
609 fn render_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
610 let chips: Vec<AnyElement> = self
611 .chips
612 .iter()
613 .enumerate()
614 .map(|(index, chip)| self.render_chip(index, chip, cx).into_any_element())
615 .collect();
616 h_flex()
617 .relative()
618 .w_full()
619 .min_h(px(if self.form_field {
620 FIELD_MIN_HEIGHT
621 } else {
622 60.
623 }))
624 .flex_none()
625 .px(px(if self.form_field { FIELD_PADDING } else { 20. }))
626 .py(px(if self.form_field { 4. } else { 8. }))
627 .gap(px(8.))
628 .flex_wrap()
629 .items_center()
630 .child(
631 div()
632 .text_size(px(14.))
633 .text_color(theme::text_muted())
634 .child("To:"),
635 )
636 .children(chips)
637 .child(
638 div()
639 .flex_1()
640 .min_w(px(160.))
641 .child(Input::new(&self.query).appearance(false).bordered(false)),
642 )
643 .children(if self.form_field {
644 None
645 } else {
646 self.render_popup(cx)
647 })
648 }
649
650 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
651 if self.chips.len() < 2 || self.form_field {
652 return None;
653 }
654 let focused = self.name.focus_handle(cx).is_focused(window);
655 Some(
656 h_flex()
657 .w_full()
658 .flex_none()
659 .px(px(20.))
660 .py(px(8.))
661 .gap(px(8.))
662 .items_center()
663 .child(
664 div()
665 .text_size(px(14.))
666 .text_color(theme::text_muted())
667 .child("Name"),
668 )
669 .child(
670 div()
671 .flex_1()
672 .h(px(32.))
673 .px(px(12.))
674 .flex()
675 .items_center()
676 .rounded(px(8.))
677 .bg(theme::surface_raised())
678 .border_1()
679 .border_color(if focused {
680 theme::accent()
681 } else {
682 transparent_black()
683 })
684 .child(
685 div()
686 .w_full()
687 .child(Input::new(&self.name).appearance(false).bordered(false)),
688 ),
689 ),
690 )
691 }
692
693 pub fn render_empty(&self, directory: &Directory, group_name: &str) -> AnyElement {
694 let column = v_flex()
695 .size_full()
696 .items_center()
697 .justify_center()
698 .gap(px(8.));
699 match self.chips.as_slice() {
700 [] => column
701 .child(
702 div()
703 .size(px(EMPTY_ICON_SIZE))
704 .flex()
705 .items_center()
706 .justify_center()
707 .rounded_full()
708 .bg(theme::surface_raised())
709 .child(icon(IconName::MessageSquare, 32., theme::accent_text())),
710 )
711 .child(
712 div()
713 .pt(px(8.))
714 .text_size(px(15.))
715 .font_weight(FontWeight::SEMIBOLD)
716 .text_color(theme::text())
717 .child(NEW_CONVERSATION_TITLE),
718 )
719 .child(
720 div()
721 .text_size(px(13.))
722 .text_color(theme::text_muted())
723 .child(NEW_CONVERSATION_HINT),
724 )
725 .into_any_element(),
726 [chip] => column
727 .child(person_avatar(
728 directory,
729 Some(&chip.user_id),
730 &chip.name,
731 56.,
732 ))
733 .child(
734 div()
735 .text_size(px(16.))
736 .font_weight(FontWeight::SEMIBOLD)
737 .text_color(theme::text())
738 .child(chip.name.clone()),
739 )
740 .child(
741 div()
742 .text_size(px(12.))
743 .text_color(theme::text_muted())
744 .child("No messages yet. Say hi."),
745 )
746 .into_any_element(),
747 chips => {
748 let title = group_name.trim();
749 column
750 .when(!title.is_empty(), |column| {
751 column.child(
752 div()
753 .text_size(px(16.))
754 .font_weight(FontWeight::SEMIBOLD)
755 .text_color(theme::text())
756 .child(title.to_owned()),
757 )
758 })
759 .child(
760 div()
761 .text_size(px(13.))
762 .text_color(theme::text_muted())
763 .child(format!(
764 "New group chat with you and {} people",
765 chips.len()
766 )),
767 )
768 .into_any_element()
769 }
770 }
771 }
772}
773
774impl Render for NewChatDraft {
775 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
776 let faces: Vec<String> = self
777 .chips
778 .iter()
779 .map(|chip| chip.user_id.clone())
780 .chain(self.results(cx).into_iter().map(|pick| pick.user_id))
781 .collect();
782 let app = self.app.clone();
783 cx.defer(move |cx| {
784 app.update(cx, |state, cx| state.request_avatars(faces, cx));
785 });
786 v_flex()
787 .w_full()
788 .flex_none()
789 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
790 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
791 this.move_highlight(-1, cx);
792 cx.stop_propagation();
793 }
794 }))
795 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
796 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
797 this.move_highlight(1, cx);
798 cx.stop_propagation();
799 }
800 }))
801 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
802 if this.query.focus_handle(cx).is_focused(window) {
803 this.accept(window, cx);
804 cx.stop_propagation();
805 }
806 }))
807 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
808 if this.query.focus_handle(cx).is_focused(window) && this.backspace(cx) {
809 cx.stop_propagation();
810 }
811 }))
812 .child(self.render_bar(cx))
813 .children(if self.form_field {
814 self.render_popup(cx)
815 } else {
816 None
817 })
818 .children(self.render_name_row(window, cx))
819 }
820}
821
822#[cfg(test)]
823mod tests {
824 use chrono::{TimeZone, Utc};
825 use store::{ChatRecord, MemberRecord};
826
827 use super::{
828 EnterAction, Pick, composer_placeholder, enter_action, search_results, suggested_people,
829 };
830 use crate::data::{Person, existing_one_on_one};
831
832 fn me() -> Person {
833 Person {
834 user_id: "me".into(),
835 display_name: "Me".into(),
836 }
837 }
838
839 fn pick(user_id: &str, name: &str, mail: Option<&str>) -> Pick {
840 Pick {
841 user_id: user_id.into(),
842 name: name.into(),
843 mail: mail.map(str::to_owned),
844 }
845 }
846
847 fn chat(id: &str, kind: &str, members: &[(&str, &str)], day: u32) -> ChatRecord {
848 ChatRecord {
849 id: id.into(),
850 kind: kind.into(),
851 members: members
852 .iter()
853 .map(|(user_id, name)| MemberRecord {
854 user_id: Some((*user_id).into()),
855 display_name: (*name).into(),
856 })
857 .collect(),
858 last_message_at: Some(Utc.with_ymd_and_hms(2026, 1, day, 9, 0, 0).unwrap()),
859 ..Default::default()
860 }
861 }
862
863 fn chats() -> Vec<ChatRecord> {
864 vec![
865 chat("old", "oneOnOne", &[("me", "Me"), ("ann", "Ann")], 1),
866 chat("new", "oneOnOne", &[("me", "Me"), ("bob", "Bob")], 5),
867 chat(
868 "group",
869 "group",
870 &[("me", "Me"), ("cid", "Cid"), ("ann", "Ann")],
871 9,
872 ),
873 ]
874 }
875
876 #[test]
877 fn suggestions_are_recent_one_on_one_partners() {
878 let found = suggested_people(&chats(), Some(&me()), &[], 6);
879 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
880 assert_eq!(ids, ["bob", "ann"]);
881 }
882
883 #[test]
884 fn suggestions_skip_chosen_people_and_respect_the_limit() {
885 let chosen = [pick("bob", "Bob", None)];
886 let found = suggested_people(&chats(), Some(&me()), &chosen, 6);
887 assert_eq!(found.len(), 1);
888 assert_eq!(found[0].user_id, "ann");
889 assert_eq!(suggested_people(&chats(), Some(&me()), &[], 1).len(), 1);
890 }
891
892 #[test]
893 fn search_puts_local_matches_first_and_dedupes() {
894 let known = vec![pick("ann", "Ann Local", None), pick("cid", "Cid", None)];
895 let remote = vec![
896 pick("ann", "Ann Remote", Some("ann@example.com")),
897 pick("anna", "Anna", Some("anna@example.com")),
898 pick("me", "Me Anna", None),
899 ];
900 let found = search_results(known, remote, "ann", Some(&me()), &[], 8);
901 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
902 assert_eq!(ids, ["ann", "anna"]);
903 assert_eq!(found[0].name, "Ann Local");
904 }
905
906 #[test]
907 fn search_excludes_chosen_people_and_caps_the_list() {
908 let remote: Vec<Pick> = (0..12)
909 .map(|index| pick(&format!("u{index}"), &format!("User {index}"), None))
910 .collect();
911 let chosen = [pick("u0", "User 0", None)];
912 let found = search_results(Vec::new(), remote, "user", None, &chosen, 8);
913 assert_eq!(found.len(), 8);
914 assert!(found.iter().all(|pick| pick.user_id != "u0"));
915 }
916
917 #[test]
918 fn local_search_matches_the_mail_address() {
919 let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];
920 let found = search_results(known, Vec::new(), "nowak", None, &[], 8);
921 assert_eq!(found.len(), 1);
922 }
923
924 #[test]
925 fn existing_chat_is_found_only_for_one_on_one() {
926 let chats = chats();
927 let found = existing_one_on_one(&chats, Some(&me()), "ann").map(|chat| chat.id.as_str());
928 assert_eq!(found, Some("old"));
929 assert!(existing_one_on_one(&chats, Some(&me()), "cid").is_none());
930 }
931
932 #[test]
933 fn placeholder_follows_the_recipients() {
934 let one = [pick("ann", "Ann", None)];
935 let two = [pick("ann", "Ann", None), pick("bob", "Bob", None)];
936 assert_eq!(composer_placeholder(&[], ""), "Type a message");
937 assert_eq!(composer_placeholder(&one, "ignored"), "Message Ann");
938 assert_eq!(composer_placeholder(&two, " "), "Type a message");
939 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
940 }
941
942 #[test]
943 fn excluded_people_are_filtered_out() {
944 let picks = vec![pick("ann", "Ann", None), pick("bob", "Bob", None)];
945 let kept = super::without_excluded(picks, &["ann".to_owned()]);
946 assert_eq!(kept, [pick("bob", "Bob", None)]);
947 }
948
949 #[test]
950 fn enter_adds_the_highlight_or_moves_on() {
951 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
952 assert_eq!(enter_action(true, 0, true), EnterAction::Add);
953 assert_eq!(enter_action(true, 1, true), EnterAction::Advance);
954 assert_eq!(enter_action(false, 2, false), EnterAction::Nothing);
955 assert_eq!(enter_action(true, 0, false), EnterAction::Nothing);
956 }
957
958 mod keys {
959 use std::sync::Arc;
960
961 use gpui_kit::test::TestWindowExt as _;
962 use gpui_kit::{AppContext as _, Entity, TestAppContext, WindowOptions};
963 use store::Store;
964
965 use super::super::NewChatDraft;
966 use crate::app_state::{AppState, Mode};
967
968 fn open(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<NewChatDraft>) {
969 cx.update(gpui_kit::init);
970 let store = Arc::new(Store::open_in_memory().unwrap());
971 crate::demo::seed(&store);
972 let mode = Mode {
973 demo: true,
974 read_only: false,
975 demo_sync: None,
976 };
977 cx.update(|cx| {
978 let app = cx.new(|_| {
979 let mut state = AppState::new(store, mode);
980 crate::demo::seed_directory(&mut state);
981 state
982 });
983 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
984 cx.new(|cx| NewChatDraft::new(app, window, cx))
985 })
986 .unwrap()
987 })
988 }
989
990 #[gpui_kit::test]
991 fn enter_adds_a_chip_and_backspace_removes_it(cx: &mut TestAppContext) {
992 let (handle, draft) = open(cx);
993 let names = cx
994 .update_window(handle, |_, window, cx| {
995 draft.update(cx, |draft, cx| draft.focus_query(window, cx));
996 window.render_frame(cx);
997 window.input("mara", cx);
998 window.render_frame(cx);
999 window.press("enter", cx);
1000 window.render_frame(cx);
1001 let added: Vec<String> = draft
1002 .read(cx)
1003 .chips()
1004 .iter()
1005 .map(|chip| chip.name.clone())
1006 .collect();
1007 window.press("backspace", cx);
1008 window.render_frame(cx);
1009 (added, draft.read(cx).chips().len())
1010 })
1011 .unwrap();
1012 assert_eq!(names.0, ["Mara Lindqvist"]);
1013 assert_eq!(names.1, 0);
1014 }
1015 }
1016}