BlueGit

ict rusty-teams

Files

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

new_chat.rs

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