BlueGit

ict rusty-teams

Files

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

new_chat.rs

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