BlueGit

ict rusty-teams

Files

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

new_chat.rs

271952ed History
new_chat.rs 31.6 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(6.))
439 .gap(px(6.))
440 .items_center()
441 .rounded(px(13.))
442 .bg(theme::surface_raised())
443 .border_1()
444 .border_color(theme::border_strong())
445 .child(person_avatar(
446 directory,
447 Some(&chip.user_id),
448 &chip.name,
449 20.,
450 ))
451 .child(
452 div()
453 .max_w(px(CHIP_NAME_MAX_WIDTH))
454 .truncate()
455 .text_size(px(13.))
456 .text_color(theme::text())
457 .child(chip.name.clone()),
458 )
459 .child(
460 div()
461 .id(ElementId::Name(
462 format!("new-chat-chip-remove-{index}").into(),
463 ))
464 .size(px(16.))
465 .flex()
466 .items_center()
467 .justify_center()
468 .rounded_full()
469 .cursor_pointer()
470 .hover(|button| button.bg(theme::row_hover()))
471 .child(icon(IconName::Close, 12., theme::text_muted()))
472 .on_click(cx.listener(move |this, _, _, cx| this.remove(index, cx))),
473 )
474 }
475
476 fn render_popup(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
477 if !self.popup_visible(cx) {
478 return None;
479 }
480 let results = self.results(cx);
481 let query = self.query_text(cx);
482 let directory = &self.app.read(cx).directory;
483 let label = if query.is_empty() {
484 "Suggested"
485 } else {
486 "People"
487 };
488 let rows = results.into_iter().enumerate().map(|(index, pick)| {
489 let detail = pick.mail.clone().unwrap_or_default();
490 let chosen = pick.clone();
491 h_flex()
492 .id(ElementId::Name(format!("new-chat-result-{index}").into()))
493 .px(px(6.))
494 .h(px(POPUP_ROW_HEIGHT))
495 .gap(px(10.))
496 .items_center()
497 .rounded(px(6.))
498 .cursor_pointer()
499 .when(index == self.highlighted, |row| {
500 row.bg(theme::border_strong())
501 })
502 .hover(|row| row.bg(theme::row_hover()))
503 .child(person_avatar(
504 directory,
505 Some(&pick.user_id),
506 &pick.name,
507 28.,
508 ))
509 .child(
510 v_flex()
511 .flex_1()
512 .min_w_0()
513 .child(
514 div()
515 .truncate()
516 .text_size(px(13.))
517 .text_color(theme::text())
518 .child(pick.name.clone()),
519 )
520 .when(!detail.is_empty(), |column| {
521 column.child(
522 div()
523 .truncate()
524 .text_size(px(11.5))
525 .text_color(theme::text_muted())
526 .child(detail),
527 )
528 }),
529 )
530 .on_click(cx.listener(move |this, _, window, cx| {
531 this.add(chosen.clone(), window, cx);
532 }))
533 });
534 let note = |text: String, color: Hsla| {
535 div()
536 .px(px(6.))
537 .py(px(8.))
538 .text_size(px(12.))
539 .text_color(color)
540 .child(text)
541 };
542 let results_empty = self.results(cx).is_empty();
543 Some(
544 deferred(
545 v_flex()
546 .id("new-chat-popup")
547 .absolute()
548 .top(relative(1.))
549 .left(px(20.))
550 .mt(px(4.))
551 .w(px(POPUP_WIDTH))
552 .p(px(6.))
553 .rounded(px(10.))
554 .border_1()
555 .border_color(theme::border_strong())
556 .bg(theme::surface_raised())
557 .shadow_lg()
558 .occlude()
559 .when(!results_empty, |popup| {
560 popup.child(
561 div()
562 .px(px(6.))
563 .pb(px(4.))
564 .text_size(px(11.))
565 .font_weight(FontWeight::SEMIBOLD)
566 .text_color(theme::text_muted())
567 .child(label),
568 )
569 })
570 .children(rows)
571 .when(self.search_failed, |popup| {
572 popup.child(note("Search failed".to_owned(), theme::red_soft()))
573 })
574 .when(self.searching && results_empty, |popup| {
575 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
576 })
577 .when(
578 !self.searching && !self.search_failed && results_empty,
579 |popup| {
580 popup.child(note(
581 format!("No people found for \"{query}\""),
582 theme::text_muted(),
583 ))
584 },
585 ),
586 )
587 .with_priority(1)
588 .into_any_element(),
589 )
590 }
591
592 fn render_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
593 let chips: Vec<AnyElement> = self
594 .chips
595 .iter()
596 .enumerate()
597 .map(|(index, chip)| self.render_chip(index, chip, cx).into_any_element())
598 .collect();
599 h_flex()
600 .relative()
601 .w_full()
602 .min_h(px(60.))
603 .flex_none()
604 .px(px(20.))
605 .py(px(8.))
606 .gap(px(8.))
607 .flex_wrap()
608 .items_center()
609 .border_b_1()
610 .border_color(theme::border())
611 .child(
612 div()
613 .text_size(px(14.))
614 .text_color(theme::text_muted())
615 .child("To:"),
616 )
617 .children(chips)
618 .child(
619 div()
620 .flex_1()
621 .min_w(px(160.))
622 .child(Input::new(&self.query).appearance(false).bordered(false)),
623 )
624 .children(self.render_popup(cx))
625 }
626
627 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
628 if self.chips.len() < 2 {
629 return None;
630 }
631 let focused = self.name.focus_handle(cx).is_focused(window);
632 Some(
633 h_flex()
634 .w_full()
635 .flex_none()
636 .px(px(20.))
637 .py(px(8.))
638 .gap(px(10.))
639 .items_center()
640 .border_b_1()
641 .border_color(theme::border())
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(10.))
653 .flex()
654 .items_center()
655 .rounded(px(8.))
656 .bg(theme::surface())
657 .border_1()
658 .border_color(if focused {
659 theme::accent()
660 } else {
661 theme::border_strong()
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(self.render_name_row(window, cx))
768 }
769}
770
771#[cfg(test)]
772mod tests {
773 use chrono::{TimeZone, Utc};
774 use store::{ChatRecord, MemberRecord};
775
776 use super::{
777 EnterAction, Pick, composer_placeholder, enter_action, existing_one_on_one, group_label,
778 search_results, suggested_people,
779 };
780 use crate::data::Person;
781
782 fn me() -> Person {
783 Person {
784 user_id: "me".into(),
785 display_name: "Me".into(),
786 }
787 }
788
789 fn pick(user_id: &str, name: &str, mail: Option<&str>) -> Pick {
790 Pick {
791 user_id: user_id.into(),
792 name: name.into(),
793 mail: mail.map(str::to_owned),
794 }
795 }
796
797 fn chat(id: &str, kind: &str, members: &[(&str, &str)], day: u32) -> ChatRecord {
798 ChatRecord {
799 id: id.into(),
800 kind: kind.into(),
801 members: members
802 .iter()
803 .map(|(user_id, name)| MemberRecord {
804 user_id: Some((*user_id).into()),
805 display_name: (*name).into(),
806 })
807 .collect(),
808 last_message_at: Some(Utc.with_ymd_and_hms(2026, 1, day, 9, 0, 0).unwrap()),
809 ..Default::default()
810 }
811 }
812
813 fn chats() -> Vec<ChatRecord> {
814 vec![
815 chat("old", "oneOnOne", &[("me", "Me"), ("ann", "Ann")], 1),
816 chat("new", "oneOnOne", &[("me", "Me"), ("bob", "Bob")], 5),
817 chat(
818 "group",
819 "group",
820 &[("me", "Me"), ("cid", "Cid"), ("ann", "Ann")],
821 9,
822 ),
823 ]
824 }
825
826 #[test]
827 fn suggestions_are_recent_one_on_one_partners() {
828 let found = suggested_people(&chats(), Some(&me()), &[], 6);
829 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
830 assert_eq!(ids, ["bob", "ann"]);
831 }
832
833 #[test]
834 fn suggestions_skip_chosen_people_and_respect_the_limit() {
835 let chosen = [pick("bob", "Bob", None)];
836 let found = suggested_people(&chats(), Some(&me()), &chosen, 6);
837 assert_eq!(found.len(), 1);
838 assert_eq!(found[0].user_id, "ann");
839 assert_eq!(suggested_people(&chats(), Some(&me()), &[], 1).len(), 1);
840 }
841
842 #[test]
843 fn search_puts_local_matches_first_and_dedupes() {
844 let known = vec![pick("ann", "Ann Local", None), pick("cid", "Cid", None)];
845 let remote = vec![
846 pick("ann", "Ann Remote", Some("ann@example.com")),
847 pick("anna", "Anna", Some("anna@example.com")),
848 pick("me", "Me Anna", None),
849 ];
850 let found = search_results(known, remote, "ann", Some(&me()), &[], 8);
851 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
852 assert_eq!(ids, ["ann", "anna"]);
853 assert_eq!(found[0].name, "Ann Local");
854 }
855
856 #[test]
857 fn search_excludes_chosen_people_and_caps_the_list() {
858 let remote: Vec<Pick> = (0..12)
859 .map(|index| pick(&format!("u{index}"), &format!("User {index}"), None))
860 .collect();
861 let chosen = [pick("u0", "User 0", None)];
862 let found = search_results(Vec::new(), remote, "user", None, &chosen, 8);
863 assert_eq!(found.len(), 8);
864 assert!(found.iter().all(|pick| pick.user_id != "u0"));
865 }
866
867 #[test]
868 fn local_search_matches_the_mail_address() {
869 let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];
870 let found = search_results(known, Vec::new(), "nowak", None, &[], 8);
871 assert_eq!(found.len(), 1);
872 }
873
874 #[test]
875 fn existing_chat_is_found_only_for_one_on_one() {
876 let chats = chats();
877 let found = existing_one_on_one(&chats, Some(&me()), "ann").map(|chat| chat.id.as_str());
878 assert_eq!(found, Some("old"));
879 assert!(existing_one_on_one(&chats, Some(&me()), "cid").is_none());
880 }
881
882 #[test]
883 fn placeholder_follows_the_recipients() {
884 let one = [pick("ann", "Ann", None)];
885 let two = [pick("ann", "Ann", None), pick("bob", "Bob", None)];
886 assert_eq!(composer_placeholder(&[], ""), "Type a message");
887 assert_eq!(composer_placeholder(&one, "ignored"), "Message Ann");
888 assert_eq!(composer_placeholder(&two, " "), "Message Ann, Bob");
889 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
890 assert_eq!(group_label(&two, ""), "Ann, Bob");
891 }
892
893 #[test]
894 fn enter_adds_the_highlight_or_moves_on() {
895 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
896 assert_eq!(enter_action(true, 0, true), EnterAction::Add);
897 assert_eq!(enter_action(true, 1, true), EnterAction::Advance);
898 assert_eq!(enter_action(false, 2, false), EnterAction::Nothing);
899 assert_eq!(enter_action(true, 0, false), EnterAction::Nothing);
900 }
901
902 mod keys {
903 use std::sync::Arc;
904
905 use gpui_kit::test::TestWindowExt as _;
906 use gpui_kit::{AppContext as _, Entity, TestAppContext, WindowOptions};
907 use store::Store;
908
909 use super::super::NewChatDraft;
910 use crate::app_state::{AppState, Mode};
911
912 fn open(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<NewChatDraft>) {
913 cx.update(gpui_kit::init);
914 let store = Arc::new(Store::open_in_memory().unwrap());
915 crate::demo::seed(&store);
916 let mode = Mode {
917 demo: true,
918 read_only: false,
919 demo_sync: None,
920 };
921 cx.update(|cx| {
922 let app = cx.new(|_| {
923 let mut state = AppState::new(store, mode);
924 crate::demo::seed_directory(&mut state);
925 state
926 });
927 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
928 cx.new(|cx| NewChatDraft::new(app, window, cx))
929 })
930 .unwrap()
931 })
932 }
933
934 #[gpui_kit::test]
935 fn enter_adds_a_chip_and_backspace_removes_it(cx: &mut TestAppContext) {
936 let (handle, draft) = open(cx);
937 let names = cx
938 .update_window(handle, |_, window, cx| {
939 draft.update(cx, |draft, cx| draft.focus_query(window, cx));
940 window.render_frame(cx);
941 window.input("mara", cx);
942 window.render_frame(cx);
943 window.press("enter", cx);
944 window.render_frame(cx);
945 let added: Vec<String> = draft
946 .read(cx)
947 .chips()
948 .iter()
949 .map(|chip| chip.name.clone())
950 .collect();
951 window.press("backspace", cx);
952 window.render_frame(cx);
953 (added, draft.read(cx).chips().len())
954 })
955 .unwrap();
956 assert_eq!(names.0, ["Mara Lindqvist"]);
957 assert_eq!(names.1, 0);
958 }
959 }
960}