BlueGit

ict rusty-teams

Files

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

new_chat.rs

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