BlueGit

ict rusty-teams

Files

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

new_chat.rs

new_chat.rs 31.1 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 .gap(px(8.))
478 .items_center()
479 .rounded(px(6.))
480 .cursor_pointer()
481 .when(index == self.highlighted, |row| {
482 row.bg(theme::popup_hover())
483 })
484 .hover(|row| row.bg(theme::popup_hover()))
485 .child(person_avatar(
486 directory,
487 Some(&pick.user_id),
488 &pick.name,
489 28.,
490 ))
491 .child(
492 v_flex()
493 .flex_1()
494 .min_w_0()
495 .child(
496 div()
497 .truncate()
498 .text_size(px(13.))
499 .text_color(theme::text())
500 .child(pick.name.clone()),
501 )
502 .when(!detail.is_empty(), |column| {
503 column.child(
504 div()
505 .truncate()
506 .text_size(px(11.5))
507 .text_color(theme::text_muted())
508 .child(detail),
509 )
510 }),
511 )
512 .on_click(cx.listener(move |this, _, window, cx| {
513 this.add(chosen.clone(), window, cx);
514 }))
515 });
516 let note = |text: String, color: Hsla| {
517 div()
518 .px(px(6.))
519 .py(px(8.))
520 .text_size(px(12.))
521 .text_color(color)
522 .child(text)
523 };
524 let results_empty = self.results(cx).is_empty();
525 let panel = v_flex()
526 .id("new-chat-popup")
527 .mt(px(4.))
528 .p(px(6.))
529 .rounded(px(10.))
530 .flyout_surface()
531 .occlude()
532 .when(!results_empty, |popup| {
533 popup.child(
534 div()
535 .px(px(6.))
536 .pb(px(4.))
537 .text_size(px(11.))
538 .font_weight(FontWeight::SEMIBOLD)
539 .text_color(theme::text_muted())
540 .child(label),
541 )
542 })
543 .children(rows)
544 .when(self.search_failed, |popup| {
545 popup.child(note("Search failed".to_owned(), theme::red_soft()))
546 })
547 .when(self.searching && results_empty, |popup| {
548 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
549 })
550 .when(
551 !self.searching && !self.search_failed && results_empty,
552 |popup| {
553 popup.child(note(
554 format!("No people found for \"{query}\""),
555 theme::text_muted(),
556 ))
557 },
558 );
559 if self.form_field {
560 return Some(panel.w_full().into_any_element());
561 }
562 Some(
563 deferred(
564 panel
565 .absolute()
566 .top(relative(1.))
567 .left(px(20.))
568 .w(px(POPUP_WIDTH)),
569 )
570 .with_priority(1)
571 .into_any_element(),
572 )
573 }
574
575 fn render_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
576 let chips: Vec<AnyElement> = self
577 .chips
578 .iter()
579 .enumerate()
580 .map(|(index, chip)| self.render_chip(index, chip, cx).into_any_element())
581 .collect();
582 h_flex()
583 .relative()
584 .w_full()
585 .min_h(px(if self.form_field {
586 FIELD_MIN_HEIGHT
587 } else {
588 60.
589 }))
590 .flex_none()
591 .px(px(if self.form_field { FIELD_PADDING } else { 20. }))
592 .py(px(if self.form_field { 4. } else { 8. }))
593 .gap(px(8.))
594 .flex_wrap()
595 .items_center()
596 .child(
597 div()
598 .text_size(px(14.))
599 .text_color(theme::text_muted())
600 .child("To:"),
601 )
602 .children(chips)
603 .child(
604 div()
605 .flex_1()
606 .min_w(px(160.))
607 .child(Input::new(&self.query).appearance(false).bordered(false)),
608 )
609 .children(if self.form_field {
610 None
611 } else {
612 self.render_popup(cx)
613 })
614 }
615
616 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
617 if self.chips.len() < 2 || self.form_field {
618 return None;
619 }
620 let focused = self.name.focus_handle(cx).is_focused(window);
621 Some(
622 h_flex()
623 .w_full()
624 .flex_none()
625 .px(px(20.))
626 .py(px(8.))
627 .gap(px(8.))
628 .items_center()
629 .child(
630 div()
631 .text_size(px(14.))
632 .text_color(theme::text_muted())
633 .child("Name"),
634 )
635 .child(
636 div()
637 .flex_1()
638 .h(px(32.))
639 .px(px(12.))
640 .flex()
641 .items_center()
642 .rounded(px(8.))
643 .bg(theme::surface_raised())
644 .border_1()
645 .border_color(if focused {
646 theme::accent()
647 } else {
648 transparent_black()
649 })
650 .child(
651 div()
652 .w_full()
653 .child(Input::new(&self.name).appearance(false).bordered(false)),
654 ),
655 ),
656 )
657 }
658
659 pub fn render_empty(&self, directory: &Directory, group_name: &str) -> AnyElement {
660 let column = v_flex()
661 .size_full()
662 .items_center()
663 .justify_center()
664 .gap(px(8.));
665 match self.chips.as_slice() {
666 [] => column.into_any_element(),
667 [chip] => column
668 .child(person_avatar(
669 directory,
670 Some(&chip.user_id),
671 &chip.name,
672 56.,
673 ))
674 .child(
675 div()
676 .text_size(px(16.))
677 .font_weight(FontWeight::SEMIBOLD)
678 .text_color(theme::text())
679 .child(chip.name.clone()),
680 )
681 .child(
682 div()
683 .text_size(px(12.))
684 .text_color(theme::text_muted())
685 .child("No messages yet. Say hi."),
686 )
687 .into_any_element(),
688 chips => {
689 let title = group_name.trim();
690 column
691 .when(!title.is_empty(), |column| {
692 column.child(
693 div()
694 .text_size(px(16.))
695 .font_weight(FontWeight::SEMIBOLD)
696 .text_color(theme::text())
697 .child(title.to_owned()),
698 )
699 })
700 .child(
701 div()
702 .text_size(px(13.))
703 .text_color(theme::text_muted())
704 .child(format!(
705 "New group chat with you and {} people",
706 chips.len()
707 )),
708 )
709 .into_any_element()
710 }
711 }
712 }
713}
714
715impl Render for NewChatDraft {
716 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
717 let faces: Vec<String> = self
718 .chips
719 .iter()
720 .map(|chip| chip.user_id.clone())
721 .chain(self.results(cx).into_iter().map(|pick| pick.user_id))
722 .collect();
723 let app = self.app.clone();
724 cx.defer(move |cx| {
725 app.update(cx, |state, cx| state.request_avatars(faces, cx));
726 });
727 v_flex()
728 .w_full()
729 .flex_none()
730 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
731 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
732 this.move_highlight(-1, cx);
733 cx.stop_propagation();
734 }
735 }))
736 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
737 if this.query.focus_handle(cx).is_focused(window) && this.popup_visible(cx) {
738 this.move_highlight(1, cx);
739 cx.stop_propagation();
740 }
741 }))
742 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
743 if this.query.focus_handle(cx).is_focused(window) {
744 this.accept(window, cx);
745 cx.stop_propagation();
746 }
747 }))
748 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
749 if this.query.focus_handle(cx).is_focused(window) && this.backspace(cx) {
750 cx.stop_propagation();
751 }
752 }))
753 .child(self.render_bar(cx))
754 .children(if self.form_field {
755 self.render_popup(cx)
756 } else {
757 None
758 })
759 .children(self.render_name_row(window, cx))
760 }
761}
762
763#[cfg(test)]
764mod tests {
765 use chrono::{TimeZone, Utc};
766 use store::{ChatRecord, MemberRecord};
767
768 use super::{
769 EnterAction, Pick, composer_placeholder, enter_action, search_results, suggested_people,
770 };
771 use crate::data::{Person, existing_one_on_one};
772
773 fn me() -> Person {
774 Person {
775 user_id: "me".into(),
776 display_name: "Me".into(),
777 }
778 }
779
780 fn pick(user_id: &str, name: &str, mail: Option<&str>) -> Pick {
781 Pick {
782 user_id: user_id.into(),
783 name: name.into(),
784 mail: mail.map(str::to_owned),
785 }
786 }
787
788 fn chat(id: &str, kind: &str, members: &[(&str, &str)], day: u32) -> ChatRecord {
789 ChatRecord {
790 id: id.into(),
791 kind: kind.into(),
792 members: members
793 .iter()
794 .map(|(user_id, name)| MemberRecord {
795 user_id: Some((*user_id).into()),
796 display_name: (*name).into(),
797 })
798 .collect(),
799 last_message_at: Some(Utc.with_ymd_and_hms(2026, 1, day, 9, 0, 0).unwrap()),
800 ..Default::default()
801 }
802 }
803
804 fn chats() -> Vec<ChatRecord> {
805 vec![
806 chat("old", "oneOnOne", &[("me", "Me"), ("ann", "Ann")], 1),
807 chat("new", "oneOnOne", &[("me", "Me"), ("bob", "Bob")], 5),
808 chat(
809 "group",
810 "group",
811 &[("me", "Me"), ("cid", "Cid"), ("ann", "Ann")],
812 9,
813 ),
814 ]
815 }
816
817 #[test]
818 fn suggestions_are_recent_one_on_one_partners() {
819 let found = suggested_people(&chats(), Some(&me()), &[], 6);
820 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
821 assert_eq!(ids, ["bob", "ann"]);
822 }
823
824 #[test]
825 fn suggestions_skip_chosen_people_and_respect_the_limit() {
826 let chosen = [pick("bob", "Bob", None)];
827 let found = suggested_people(&chats(), Some(&me()), &chosen, 6);
828 assert_eq!(found.len(), 1);
829 assert_eq!(found[0].user_id, "ann");
830 assert_eq!(suggested_people(&chats(), Some(&me()), &[], 1).len(), 1);
831 }
832
833 #[test]
834 fn search_puts_local_matches_first_and_dedupes() {
835 let known = vec![pick("ann", "Ann Local", None), pick("cid", "Cid", None)];
836 let remote = vec![
837 pick("ann", "Ann Remote", Some("ann@example.com")),
838 pick("anna", "Anna", Some("anna@example.com")),
839 pick("me", "Me Anna", None),
840 ];
841 let found = search_results(known, remote, "ann", Some(&me()), &[], 8);
842 let ids: Vec<&str> = found.iter().map(|pick| pick.user_id.as_str()).collect();
843 assert_eq!(ids, ["ann", "anna"]);
844 assert_eq!(found[0].name, "Ann Local");
845 }
846
847 #[test]
848 fn search_excludes_chosen_people_and_caps_the_list() {
849 let remote: Vec<Pick> = (0..12)
850 .map(|index| pick(&format!("u{index}"), &format!("User {index}"), None))
851 .collect();
852 let chosen = [pick("u0", "User 0", None)];
853 let found = search_results(Vec::new(), remote, "user", None, &chosen, 8);
854 assert_eq!(found.len(), 8);
855 assert!(found.iter().all(|pick| pick.user_id != "u0"));
856 }
857
858 #[test]
859 fn local_search_matches_the_mail_address() {
860 let known = vec![pick("ann", "Ann", Some("a.nowak@example.com"))];
861 let found = search_results(known, Vec::new(), "nowak", None, &[], 8);
862 assert_eq!(found.len(), 1);
863 }
864
865 #[test]
866 fn existing_chat_is_found_only_for_one_on_one() {
867 let chats = chats();
868 let found = existing_one_on_one(&chats, Some(&me()), "ann").map(|chat| chat.id.as_str());
869 assert_eq!(found, Some("old"));
870 assert!(existing_one_on_one(&chats, Some(&me()), "cid").is_none());
871 }
872
873 #[test]
874 fn placeholder_follows_the_recipients() {
875 let one = [pick("ann", "Ann", None)];
876 let two = [pick("ann", "Ann", None), pick("bob", "Bob", None)];
877 assert_eq!(composer_placeholder(&[], ""), "Type a message");
878 assert_eq!(composer_placeholder(&one, "ignored"), "Message Ann");
879 assert_eq!(composer_placeholder(&two, " "), "Type a message");
880 assert_eq!(composer_placeholder(&two, " Crew "), "Message Crew");
881 }
882
883 #[test]
884 fn enter_adds_the_highlight_or_moves_on() {
885 assert_eq!(enter_action(false, 0, true), EnterAction::Add);
886 assert_eq!(enter_action(true, 0, true), EnterAction::Add);
887 assert_eq!(enter_action(true, 1, true), EnterAction::Advance);
888 assert_eq!(enter_action(false, 2, false), EnterAction::Nothing);
889 assert_eq!(enter_action(true, 0, false), EnterAction::Nothing);
890 }
891
892 mod keys {
893 use std::sync::Arc;
894
895 use gpui_kit::test::TestWindowExt as _;
896 use gpui_kit::{AppContext as _, Entity, TestAppContext, WindowOptions};
897 use store::Store;
898
899 use super::super::NewChatDraft;
900 use crate::app_state::{AppState, Mode};
901
902 fn open(cx: &mut TestAppContext) -> (gpui_kit::AnyWindowHandle, Entity<NewChatDraft>) {
903 cx.update(gpui_kit::init);
904 let store = Arc::new(Store::open_in_memory().unwrap());
905 crate::demo::seed(&store);
906 let mode = Mode {
907 demo: true,
908 read_only: false,
909 demo_sync: None,
910 };
911 cx.update(|cx| {
912 let app = cx.new(|_| {
913 let mut state = AppState::new(store, mode);
914 crate::demo::seed_directory(&mut state);
915 state
916 });
917 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
918 cx.new(|cx| NewChatDraft::new(app, window, cx))
919 })
920 .unwrap()
921 })
922 }
923
924 #[gpui_kit::test]
925 fn enter_adds_a_chip_and_backspace_removes_it(cx: &mut TestAppContext) {
926 let (handle, draft) = open(cx);
927 let names = cx
928 .update_window(handle, |_, window, cx| {
929 draft.update(cx, |draft, cx| draft.focus_query(window, cx));
930 window.render_frame(cx);
931 window.input("mara", cx);
932 window.render_frame(cx);
933 window.press("enter", cx);
934 window.render_frame(cx);
935 let added: Vec<String> = draft
936 .read(cx)
937 .chips()
938 .iter()
939 .map(|chip| chip.name.clone())
940 .collect();
941 window.press("backspace", cx);
942 window.render_frame(cx);
943 (added, draft.read(cx).chips().len())
944 })
945 .unwrap();
946 assert_eq!(names.0, ["Mara Lindqvist"]);
947 assert_eq!(names.1, 0);
948 }
949 }
950}