BlueGit

ict rusty-teams

Files

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

new_chat.rs

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