BlueGit

ict rusty-teams

Files

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

new_chat.rs

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