BlueGit

ict rusty-teams

Files

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

new_chat.rs

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