BlueGit

ict rusty-teams

feat(app): new chat with people picker

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-08 · 7 weeks ago

Hash
271952edd17f8e456baf514109a8ad62dcc7d3e6
Parent
17f687f4
9 files changed +1726 −86
ROADMAP.md +11 −12
@@ -2,14 +2,14 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 55 %** (42 done, 5 partial, 34 missing of 81). Partial counts half.
5 **Parity: 56 %** (43 done, 4 partial, 34 missing of 81). Partial counts half.
6 6
7 7 ## By area
8 8
9 9 | Area | Parity | Done | Partial | Missing |
10 10 |---|---|---|---|---|
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 | [Chat list](#chat-list) | 55 % | 5 | 1 | 4 |
12 | [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13 13 | [Reading](#reading) | 70 % | 10 | 1 | 4 |
14 14 | [Writing](#writing) | 61 % | 8 | 1 | 5 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
@@ -24,15 +24,14 @@ Feature parity with the Microsoft Teams desktop client.
24 24
25 25 | # | Feature | Note |
26 26 |---|---|---|
27 | 1 | New chat: 1:1 and group with title | Backend is done |
28 | 2 | Attach a file, paste or drag an image | |
29 | 3 | Channel: new post with subject, post cards | |
30 | 4 | Sign in on Linux without Chrome on a debug port | |
31 | 5 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
32 | 6 | Emoji picker in the composer | Reaction picker exists |
33 | 7 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
34 | 8 | Typing indicator | |
35 | 9 | Unsent messages survive a restart | |
27 | 1 | Attach a file, paste or drag an image | |
28 | 2 | Channel: new post with subject, post cards | |
29 | 3 | Sign in on Linux without Chrome on a debug port | |
30 | 4 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
31 | 5 | Emoji picker in the composer | Reaction picker exists |
32 | 6 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
33 | 7 | Typing indicator | |
34 | 8 | Unsent messages survive a restart | |
36 35
37 36 ## Sign-in and app
38 37
@@ -54,7 +53,7 @@ Feature parity with the Microsoft Teams desktop client.
54 53 | Chat folders (custom sections), move by menu or drag | Done | |
55 54 | Hidden teams | Done | |
56 55 | Unread bold, unread count, mention marker | Done | |
57 | New chat: 1:1 and group with title | Partial | Backend done, no UI |
56 | New chat: 1:1 and group with title | Done | |
58 57 | Mark as unread | Missing | |
59 58 | Mute chat | Missing | |
60 59 | Hide chat, leave chat | Missing | |
@@ -2,14 +2,14 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 55 %** (42 done, 5 partial, 34 missing of 81). Partial counts half.
5**Parity: 56 %** (43 done, 4 partial, 34 missing of 81). Partial counts half.
6
6
7## By area
7## By area
8
8
9| Area | Parity | Done | Partial | Missing |
9| Area | Parity | Done | Partial | Missing |
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12| [Chat list](#chat-list) | 55 % | 5 | 1 | 4 |
12| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13| [Reading](#reading) | 70 % | 10 | 1 | 4 |
13| [Reading](#reading) | 70 % | 10 | 1 | 4 |
14| [Writing](#writing) | 61 % | 8 | 1 | 5 |
14| [Writing](#writing) | 61 % | 8 | 1 | 5 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
@@ -24,15 +24,14 @@ Feature parity with the Microsoft Teams desktop client.
24
24
25| # | Feature | Note |
25| # | Feature | Note |
26|---|---|---|
26|---|---|---|
27| 1 | New chat: 1:1 and group with title | Backend is done |
27| 1 | Attach a file, paste or drag an image | |
28| 2 | Attach a file, paste or drag an image | |
28| 2 | Channel: new post with subject, post cards | |
29| 3 | Channel: new post with subject, post cards | |
29| 3 | Sign in on Linux without Chrome on a debug port | |
30| 4 | Sign in on Linux without Chrome on a debug port | |
30| 4 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
31| 5 | Chat menu: mark as unread, mute, hide, leave | Unlocks quiet muted chats and the Muted section |
31| 5 | Emoji picker in the composer | Reaction picker exists |
32| 6 | Emoji picker in the composer | Reaction picker exists |
32| 6 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
33| 7 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
33| 7 | Typing indicator | |
34| 8 | Typing indicator | |
34| 8 | Unsent messages survive a restart | |
35| 9 | Unsent messages survive a restart | |
36
35
37## Sign-in and app
36## Sign-in and app
38
37
@@ -54,7 +53,7 @@ Feature parity with the Microsoft Teams desktop client.
54| Chat folders (custom sections), move by menu or drag | Done | |
53| Chat folders (custom sections), move by menu or drag | Done | |
55| Hidden teams | Done | |
54| Hidden teams | Done | |
56| Unread bold, unread count, mention marker | Done | |
55| Unread bold, unread count, mention marker | Done | |
57| New chat: 1:1 and group with title | Partial | Backend done, no UI |
56| New chat: 1:1 and group with title | Done | |
58| Mark as unread | Missing | |
57| Mark as unread | Missing | |
59| Mute chat | Missing | |
58| Mute chat | Missing | |
60| Hide chat, leave chat | Missing | |
59| Hide chat, leave chat | Missing | |
crates/app/src/app_state.rs +22 −2
@@ -49,6 +49,7 @@ pub struct AppState {
49 49 pub sidebar: Sidebar,
50 50 pub favorite_ids: Vec<String>,
51 51 pub selection: Option<Selection>,
52 pub new_chat: bool,
52 53 pub connection: ConnectionState,
53 54 pub live: LiveState,
54 55 pub last_sync: Option<DateTime<Utc>>,
@@ -101,6 +102,7 @@ impl AppState {
101 102 sidebar,
102 103 favorite_ids: Vec::new(),
103 104 selection: None,
105 new_chat: false,
104 106 connection: if mode.demo {
105 107 ConnectionState::Online
106 108 } else {
@@ -362,7 +364,9 @@ impl AppState {
362 364 return;
363 365 }
364 366 if let Some(engine) = self.engine.clone() {
365 let _ = self.store.mark_chat_read(conversation_id, chrono::Utc::now());
367 let _ = self
368 .store
369 .mark_chat_read(conversation_id, chrono::Utc::now());
366 370 self.reload_sidebar(cx);
367 371 let conversation_id = conversation_id.to_owned();
368 372 drop(crate::runtime::spawn(async move {
@@ -371,8 +375,24 @@ impl AppState {
371 375 }
372 376 }
373 377
378 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
379 self.new_chat = true;
380 cx.emit(AppEvent::Selection);
381 cx.notify();
382 }
383
384 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
385 if !self.new_chat {
386 return;
387 }
388 self.new_chat = false;
389 cx.emit(AppEvent::Selection);
390 cx.notify();
391 }
392
374 393 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
375 if self.selection.as_ref() == Some(&selection) {
394 let was_drafting = std::mem::take(&mut self.new_chat);
395 if !was_drafting && self.selection.as_ref() == Some(&selection) {
376 396 return;
377 397 }
378 398 self.selection = Some(selection);
@@ -49,6 +49,7 @@ pub struct AppState {
49 pub sidebar: Sidebar,
49 pub sidebar: Sidebar,
50 pub favorite_ids: Vec<String>,
50 pub favorite_ids: Vec<String>,
51 pub selection: Option<Selection>,
51 pub selection: Option<Selection>,
52 pub new_chat: bool,
52 pub connection: ConnectionState,
53 pub connection: ConnectionState,
53 pub live: LiveState,
54 pub live: LiveState,
54 pub last_sync: Option<DateTime<Utc>>,
55 pub last_sync: Option<DateTime<Utc>>,
@@ -101,6 +102,7 @@ impl AppState {
101 sidebar,
102 sidebar,
102 favorite_ids: Vec::new(),
103 favorite_ids: Vec::new(),
103 selection: None,
104 selection: None,
105 new_chat: false,
104 connection: if mode.demo {
106 connection: if mode.demo {
105 ConnectionState::Online
107 ConnectionState::Online
106 } else {
108 } else {
@@ -362,7 +364,9 @@ impl AppState {
362 return;
364 return;
363 }
365 }
364 if let Some(engine) = self.engine.clone() {
366 if let Some(engine) = self.engine.clone() {
365 let _ = self.store.mark_chat_read(conversation_id, chrono::Utc::now());
367 let _ = self
368 .store
369 .mark_chat_read(conversation_id, chrono::Utc::now());
366 self.reload_sidebar(cx);
370 self.reload_sidebar(cx);
367 let conversation_id = conversation_id.to_owned();
371 let conversation_id = conversation_id.to_owned();
368 drop(crate::runtime::spawn(async move {
372 drop(crate::runtime::spawn(async move {
@@ -371,8 +375,24 @@ impl AppState {
371 }
375 }
372 }
376 }
373
377
378 pub fn start_new_chat(&mut self, cx: &mut Context<Self>) {
379 self.new_chat = true;
380 cx.emit(AppEvent::Selection);
381 cx.notify();
382 }
383
384 pub fn close_new_chat(&mut self, cx: &mut Context<Self>) {
385 if !self.new_chat {
386 return;
387 }
388 self.new_chat = false;
389 cx.emit(AppEvent::Selection);
390 cx.notify();
391 }
392
374 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
393 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
375 if self.selection.as_ref() == Some(&selection) {
394 let was_drafting = std::mem::take(&mut self.new_chat);
395 if !was_drafting && self.selection.as_ref() == Some(&selection) {
376 return;
396 return;
377 }
397 }
378 self.selection = Some(selection);
398 self.selection = Some(selection);
crates/app/src/demo.rs +105 −0
@@ -19,6 +19,7 @@ const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
19 19 const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
20 20 const STAGING_SIZE: (usize, usize) = (960, 540);
21 21 const PRIORITY_CHAT: &str = "demo-chat-priya";
22 const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
22 23 const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
23 24 (
24 25 MARA_ID,
@@ -330,6 +331,66 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
330 331 people.chain(scope).collect()
331 332 }
332 333
334 pub fn send_in_chat(
335 chat: &ChatRecord,
336 text: &str,
337 now: DateTime<Utc>,
338 ) -> (ChatRecord, MessageRecord) {
339 let mut chat = chat.clone();
340 chat.last_message_at = Some(now);
341 chat.last_message_preview = Some(text.to_owned());
342 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
343 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
344 chat.last_message_deleted = false;
345 chat.unread = false;
346 let record = message(
347 &chat.id,
348 &format!("demo-sent-{}", now.timestamp_millis()),
349 None,
350 (DEMO_USER_ID, DEMO_USER_NAME),
351 now,
352 &teams_core::markdown_to_html(text),
353 "[]",
354 false,
355 );
356 (chat, record)
357 }
358
359 pub fn new_chat(
360 existing: &[ChatRecord],
361 people: &[(String, String)],
362 topic: Option<&str>,
363 text: &str,
364 now: DateTime<Utc>,
365 ) -> (ChatRecord, MessageRecord) {
366 let number = existing
367 .iter()
368 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
369 .count()
370 + 1;
371 let one_on_one = people.len() == 1;
372 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
373 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
374 .collect();
375 let chat = ChatRecord {
376 id: format!("{NEW_CHAT_PREFIX}{number}"),
377 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
378 title: if one_on_one {
379 String::new()
380 } else {
381 topic.unwrap_or_default().to_owned()
382 },
383 member_summary: people
384 .iter()
385 .map(|(_, name)| name.as_str())
386 .collect::<Vec<_>>()
387 .join(", "),
388 members,
389 ..Default::default()
390 };
391 send_in_chat(&chat, text, now)
392 }
393
333 394 fn image_directory() -> PathBuf {
334 395 std::env::temp_dir().join("rusty-teams-demo")
335 396 }
@@ -940,6 +1001,50 @@ mod tests {
940 1001 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
941 1002 }
942 1003
1004 #[test]
1005 fn new_group_chat_gets_a_title_and_the_first_message() {
1006 let people = vec![
1007 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1008 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1009 ];
1010 let now = Utc::now();
1011 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1012 assert_eq!(chat.id, "demo-chat-new-1");
1013 assert_eq!(chat.kind, "group");
1014 assert_eq!(chat.title, "Crew");
1015 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1016 assert_eq!(chat.members.len(), 3);
1017 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1018 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1019 assert_eq!(chat.last_message_at, Some(now));
1020 assert_eq!(record.conversation_id, chat.id);
1021 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1022 assert!(record.body_html.contains("Hello"));
1023 }
1024
1025 #[test]
1026 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1027 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1028 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1029 assert_eq!(first.kind, "oneOnOne");
1030 assert!(first.title.is_empty());
1031 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1032 assert_eq!(second.id, "demo-chat-new-2");
1033 }
1034
1035 #[test]
1036 fn sending_into_a_chat_refreshes_its_preview() {
1037 let base = ChatRecord {
1038 id: "demo-chat-x".to_owned(),
1039 unread: true,
1040 ..Default::default()
1041 };
1042 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1043 assert!(!chat.unread);
1044 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1045 assert_eq!(record.conversation_id, "demo-chat-x");
1046 }
1047
943 1048 #[test]
944 1049 fn demo_covers_the_sidebar_edge_cases() {
945 1050 let chats = demo_chats();
@@ -19,6 +19,7 @@ const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
19const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
19const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
20const STAGING_SIZE: (usize, usize) = (960, 540);
20const STAGING_SIZE: (usize, usize) = (960, 540);
21const PRIORITY_CHAT: &str = "demo-chat-priya";
21const PRIORITY_CHAT: &str = "demo-chat-priya";
22const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
22const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
23const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
23 (
24 (
24 MARA_ID,
25 MARA_ID,
@@ -330,6 +331,66 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
330 people.chain(scope).collect()
331 people.chain(scope).collect()
331}
332}
332
333
334pub fn send_in_chat(
335 chat: &ChatRecord,
336 text: &str,
337 now: DateTime<Utc>,
338) -> (ChatRecord, MessageRecord) {
339 let mut chat = chat.clone();
340 chat.last_message_at = Some(now);
341 chat.last_message_preview = Some(text.to_owned());
342 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
343 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
344 chat.last_message_deleted = false;
345 chat.unread = false;
346 let record = message(
347 &chat.id,
348 &format!("demo-sent-{}", now.timestamp_millis()),
349 None,
350 (DEMO_USER_ID, DEMO_USER_NAME),
351 now,
352 &teams_core::markdown_to_html(text),
353 "[]",
354 false,
355 );
356 (chat, record)
357}
358
359pub fn new_chat(
360 existing: &[ChatRecord],
361 people: &[(String, String)],
362 topic: Option<&str>,
363 text: &str,
364 now: DateTime<Utc>,
365) -> (ChatRecord, MessageRecord) {
366 let number = existing
367 .iter()
368 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
369 .count()
370 + 1;
371 let one_on_one = people.len() == 1;
372 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
373 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
374 .collect();
375 let chat = ChatRecord {
376 id: format!("{NEW_CHAT_PREFIX}{number}"),
377 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
378 title: if one_on_one {
379 String::new()
380 } else {
381 topic.unwrap_or_default().to_owned()
382 },
383 member_summary: people
384 .iter()
385 .map(|(_, name)| name.as_str())
386 .collect::<Vec<_>>()
387 .join(", "),
388 members,
389 ..Default::default()
390 };
391 send_in_chat(&chat, text, now)
392}
393
333fn image_directory() -> PathBuf {
394fn image_directory() -> PathBuf {
334 std::env::temp_dir().join("rusty-teams-demo")
395 std::env::temp_dir().join("rusty-teams-demo")
335}
396}
@@ -940,6 +1001,50 @@ mod tests {
940 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1001 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
941 }
1002 }
942
1003
1004 #[test]
1005 fn new_group_chat_gets_a_title_and_the_first_message() {
1006 let people = vec![
1007 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1008 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1009 ];
1010 let now = Utc::now();
1011 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1012 assert_eq!(chat.id, "demo-chat-new-1");
1013 assert_eq!(chat.kind, "group");
1014 assert_eq!(chat.title, "Crew");
1015 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1016 assert_eq!(chat.members.len(), 3);
1017 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1018 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1019 assert_eq!(chat.last_message_at, Some(now));
1020 assert_eq!(record.conversation_id, chat.id);
1021 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1022 assert!(record.body_html.contains("Hello"));
1023 }
1024
1025 #[test]
1026 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1027 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1028 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1029 assert_eq!(first.kind, "oneOnOne");
1030 assert!(first.title.is_empty());
1031 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1032 assert_eq!(second.id, "demo-chat-new-2");
1033 }
1034
1035 #[test]
1036 fn sending_into_a_chat_refreshes_its_preview() {
1037 let base = ChatRecord {
1038 id: "demo-chat-x".to_owned(),
1039 unread: true,
1040 ..Default::default()
1041 };
1042 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1043 assert!(!chat.unread);
1044 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1045 assert_eq!(record.conversation_id, "demo-chat-x");
1046 }
1047
943 #[test]
1048 #[test]
944 fn demo_covers_the_sidebar_edge_cases() {
1049 fn demo_covers_the_sidebar_edge_cases() {
945 let chats = demo_chats();
1050 let chats = demo_chats();
crates/app/src/views/composer.rs +7 −4
@@ -443,6 +443,12 @@ impl Composer {
443 443 cx.notify();
444 444 }
445 445
446 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
447 let text = text.to_owned();
448 self.input
449 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
450 }
451
446 452 pub fn set_conversation(
447 453 &mut self,
448 454 conversation_id: &str,
@@ -450,10 +456,7 @@ impl Composer {
450 456 window: &mut Window,
451 457 cx: &mut Context<Self>,
452 458 ) {
453 let placeholder = format!("Message {name}");
454 self.input.update(cx, |state, cx| {
455 state.set_placeholder(placeholder, window, cx)
456 });
459 self.set_placeholder(&format!("Message {name}"), window, cx);
457 460 if self.conversation_id.as_deref() != Some(conversation_id) {
458 461 self.conversation_id = Some(conversation_id.to_owned());
459 462 self.reply = None;
@@ -443,6 +443,12 @@ impl Composer {
443 cx.notify();
443 cx.notify();
444 }
444 }
445
445
446 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
447 let text = text.to_owned();
448 self.input
449 .update(cx, |state, cx| state.set_placeholder(text, window, cx));
450 }
451
446 pub fn set_conversation(
452 pub fn set_conversation(
447 &mut self,
453 &mut self,
448 conversation_id: &str,
454 conversation_id: &str,
@@ -450,10 +456,7 @@ impl Composer {
450 window: &mut Window,
456 window: &mut Window,
451 cx: &mut Context<Self>,
457 cx: &mut Context<Self>,
452 ) {
458 ) {
453 let placeholder = format!("Message {name}");
459 self.set_placeholder(&format!("Message {name}"), window, cx);
454 self.input.update(cx, |state, cx| {
455 state.set_placeholder(placeholder, window, cx)
456 });
457 if self.conversation_id.as_deref() != Some(conversation_id) {
460 if self.conversation_id.as_deref() != Some(conversation_id) {
458 self.conversation_id = Some(conversation_id.to_owned());
461 self.conversation_id = Some(conversation_id.to_owned());
459 self.reply = None;
462 self.reply = None;
crates/app/src/views/conversation.rs +510 −51
@@ -8,6 +8,7 @@ use gpui_kit::assets::IconName;
8 8 use gpui_kit::component::{
9 9 button::{Button, ButtonVariants as _},
10 10 h_flex,
11 input::Escape,
11 12 message_scroller::{MessageScroller, MessageScrollerState},
12 13 v_flex,
13 14 };
@@ -20,6 +21,7 @@ use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, wit
20 21 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21 22 use super::message_actions::{Action, MessageMenu};
22 23 use super::message_row::{RowActions, render_message_row, render_skeleton_row};
24 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
23 25 use super::reaction_picker::{PickHandler, ReactionPicker};
24 26 use super::widgets::icon;
25 27 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
@@ -103,6 +105,10 @@ pub struct ConversationView {
103 105 app: Entity<AppState>,
104 106 scroller: Entity<MessageScrollerState>,
105 107 composer: Entity<Composer>,
108 draft: Entity<NewChatDraft>,
109 draft_active: bool,
110 draft_created: Option<(Vec<String>, String)>,
111 draft_error: Option<String>,
106 112 rows: Rc<RefCell<Vec<Row>>>,
107 113 current: Option<Current>,
108 114 pending: Vec<MessageRow>,
@@ -135,15 +141,21 @@ impl ConversationView {
135 141 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
136 142 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
137 143 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
144 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
138 145 let subscriptions = vec![
139 146 cx.subscribe_in(&app, window, Self::on_app_event),
140 147 cx.subscribe_in(&composer, window, Self::on_composer_event),
148 cx.subscribe_in(&draft, window, Self::on_draft_event),
141 149 cx.observe_window_activation(window, Self::on_window_activation),
142 150 ];
143 151 let mut view = ConversationView {
144 152 app,
145 153 scroller,
146 154 composer,
155 draft,
156 draft_active: false,
157 draft_created: None,
158 draft_error: None,
147 159 rows: Rc::new(RefCell::new(Vec::new())),
148 160 current: None,
149 161 pending: Vec::new(),
@@ -191,8 +203,23 @@ impl ConversationView {
191 203 ) {
192 204 match event {
193 205 AppEvent::Selection => {
194 if let Some(selection) = self.app.read(cx).selection.clone() {
195 self.open(selection, window, cx);
206 let (new_chat, selection) = {
207 let state = self.app.read(cx);
208 (state.new_chat, state.selection.clone())
209 };
210 if new_chat {
211 self.enter_draft(window, cx);
212 return;
213 }
214 if self.draft_active {
215 self.leave_draft(window, cx);
216 }
217 match selection {
218 Some(selection) => self.open(selection, window, cx),
219 None => {
220 self.current = None;
221 self.rebuild(true, cx);
222 }
196 223 }
197 224 }
198 225 AppEvent::Messages(conversation_id) => {
@@ -218,7 +245,9 @@ impl ConversationView {
218 245 AppEvent::Directory => cx.notify(),
219 246 AppEvent::Sidebar => {
220 247 self.mark_read(ReadTrigger::Incoming, cx);
221 if let Some(current) = self.current.as_mut() {
248 if self.draft_active {
249 self.on_draft_changed(window, cx);
250 } else if let Some(current) = self.current.as_mut() {
222 251 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
223 252 if current.title != title {
224 253 current.title = title.clone();
@@ -241,6 +270,9 @@ impl ConversationView {
241 270 cx: &mut Context<Self>,
242 271 ) {
243 272 match event {
273 ComposerEvent::Submit(outgoing) if self.draft_active => {
274 self.send_new_chat(outgoing.clone(), window, cx)
275 }
244 276 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
245 277 self.send_edit(outgoing.clone(), window, cx)
246 278 }
@@ -289,12 +321,104 @@ impl ConversationView {
289 321 .unwrap_or_default();
290 322 self.composer.update(cx, |composer, cx| {
291 323 composer.set_conversation(&target.0, &target.1, window, cx);
292 composer.focus(window, cx);
293 324 });
325 if !self.draft_active {
326 self.composer
327 .update(cx, |composer, cx| composer.focus(window, cx));
328 }
294 329 self.hovered_message = None;
295 330 self.apply_pending_jump(cx);
296 331 }
297 332
333 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
334 if !self.draft_active {
335 self.draft_active = true;
336 self.current = None;
337 self.pending.clear();
338 self.pending_outgoing.clear();
339 self.notice = None;
340 self.draft_created = None;
341 self.draft_error = None;
342 self.toolbar_hovered = None;
343 self.toolbar_pinned = None;
344 self.hovered_message = None;
345 self.sync_generation += 1;
346 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
347 self.composer.update(cx, |composer, cx| {
348 composer.set_conversation("", "", window, cx)
349 });
350 self.on_draft_changed(window, cx);
351 self.rebuild(true, cx);
352 }
353 self.draft
354 .update(cx, |draft, cx| draft.focus_query(window, cx));
355 cx.notify();
356 }
357
358 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
359 self.draft_active = false;
360 self.draft_created = None;
361 self.draft_error = None;
362 self.pending.clear();
363 self.pending_outgoing.clear();
364 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
365 }
366
367 fn on_draft_event(
368 &mut self,
369 _: &Entity<NewChatDraft>,
370 event: &NewChatEvent,
371 window: &mut Window,
372 cx: &mut Context<Self>,
373 ) {
374 match event {
375 NewChatEvent::Changed => self.on_draft_changed(window, cx),
376 NewChatEvent::FocusComposer => self
377 .composer
378 .update(cx, |composer, cx| composer.focus(window, cx)),
379 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
380 }
381 }
382
383 fn draft_target_chat(&self, cx: &App) -> Option<String> {
384 let chips = self.draft.read(cx).chips();
385 let [chip] = chips else {
386 return None;
387 };
388 let state = self.app.read(cx);
389 existing_one_on_one(
390 &state.sidebar.chats,
391 state.directory.me.as_ref(),
392 &chip.user_id,
393 )
394 .map(|chat| chat.id.clone())
395 }
396
397 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
398 if !self.draft_active {
399 return;
400 }
401 let target = self.draft_target_chat(cx);
402 if target != self.conversation_id() {
403 match target {
404 Some(chat_id) => self.open(Selection::Chat(chat_id), window, cx),
405 None => {
406 self.current = None;
407 self.sync_generation += 1;
408 self.rebuild(true, cx);
409 }
410 }
411 }
412 let placeholder = {
413 let draft = self.draft.read(cx);
414 composer_placeholder(draft.chips(), &draft.group_name(cx))
415 };
416 self.composer.update(cx, |composer, cx| {
417 composer.set_placeholder(&placeholder, window, cx)
418 });
419 cx.notify();
420 }
421
298 422 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
299 423 let indices: Vec<usize> = self
300 424 .rows
@@ -506,7 +630,14 @@ impl ConversationView {
506 630
507 631 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
508 632 let Some(current) = self.current.as_ref() else {
509 self.apply_rows(Vec::new(), true, cx);
633 let mut rows: Vec<Row> = self
634 .pending
635 .iter()
636 .cloned()
637 .map(|row| Row::Message(Box::new(row)))
638 .collect();
639 assign_series(&mut rows);
640 self.apply_rows(rows, true, cx);
510 641 return;
511 642 };
512 643 let conversation_id = current.selection.conversation_id().to_owned();
@@ -914,6 +1045,9 @@ impl ConversationView {
914 1045 }
915 1046
916 1047 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1048 if self.draft_active {
1049 return;
1050 }
917 1051 let state = self.app.read(cx);
918 1052 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
919 1053 else {
@@ -1019,52 +1153,17 @@ impl ConversationView {
1019 1153 let Some(current) = self.current.as_ref() else {
1020 1154 return;
1021 1155 };
1022 let restore =
1023 |this: &mut Self, message: &str, window: &mut Window, cx: &mut Context<Self>| {
1024 this.notice = Some(message.to_owned());
1025 this.composer
1026 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1027 cx.notify();
1028 };
1029 1156 if mode.read_only || mode.demo {
1030 restore(self, "Read-only mode: nothing was sent", window, cx);
1157 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1031 1158 return;
1032 1159 }
1033 1160 let Some(engine) = engine else {
1034 restore(self, "Not connected yet: nothing was sent", window, cx);
1161 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1035 1162 return;
1036 1163 };
1037 1164 let conversation_id = current.selection.conversation_id().to_owned();
1038 1165 let view_mode = current.mode.clone();
1039 self.pending_counter += 1;
1040 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1041 let my_user_id = self.row_context(cx).my_user_id;
1042 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1043 self.pending.push(MessageRow {
1044 key: key.clone(),
1045 author: "You".to_owned(),
1046 sender_id: my_user_id,
1047 created_at: Utc::now(),
1048 series: Series::default(),
1049 card: false,
1050 time: chrono::Local::now().format("%H:%M").to_string(),
1051 day_header: None,
1052 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1053 edited: false,
1054 deleted: false,
1055 reactions: Vec::new(),
1056 images: Vec::new(),
1057 files: Vec::new(),
1058 reply_count: None,
1059 new_marker: false,
1060 reply_faces: Vec::new(),
1061 last_reply_time: None,
1062 open_thread: None,
1063 is_reply: false,
1064 delivery: Delivery::Sending,
1065 receipt: Receipt::Hidden,
1066 own: true,
1067 });
1166 let key = self.push_pending(&outgoing, cx);
1068 1167 self.notice = None;
1069 1168 self.rebuild(false, cx);
1070 1169 self.scroller
@@ -1112,6 +1211,197 @@ impl ConversationView {
1112 1211 .detach();
1113 1212 }
1114 1213
1214 fn restore_unsent(
1215 &mut self,
1216 message: &str,
1217 outgoing: &Outgoing,
1218 window: &mut Window,
1219 cx: &mut Context<Self>,
1220 ) {
1221 self.notice = Some(message.to_owned());
1222 self.composer
1223 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1224 cx.notify();
1225 }
1226
1227 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1228 self.pending_counter += 1;
1229 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1230 let my_user_id = self.row_context(cx).my_user_id;
1231 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1232 self.pending.push(MessageRow {
1233 key: key.clone(),
1234 author: "You".to_owned(),
1235 sender_id: my_user_id,
1236 created_at: Utc::now(),
1237 series: Series::default(),
1238 card: false,
1239 time: chrono::Local::now().format("%H:%M").to_string(),
1240 day_header: None,
1241 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1242 edited: false,
1243 deleted: false,
1244 reactions: Vec::new(),
1245 images: Vec::new(),
1246 files: Vec::new(),
1247 reply_count: None,
1248 new_marker: false,
1249 reply_faces: Vec::new(),
1250 last_reply_time: None,
1251 open_thread: None,
1252 is_reply: false,
1253 delivery: Delivery::Sending,
1254 receipt: Receipt::Hidden,
1255 own: true,
1256 });
1257 key
1258 }
1259
1260 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1261 let (recipients, topic) = {
1262 let draft = self.draft.read(cx);
1263 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
1264 (draft.chips().to_vec(), topic)
1265 };
1266 if recipients.is_empty() {
1267 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1268 self.draft
1269 .update(cx, |draft, cx| draft.focus_query(window, cx));
1270 return;
1271 }
1272 if self
1273 .pending
1274 .iter()
1275 .any(|row| matches!(row.delivery, Delivery::Sending))
1276 {
1277 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1278 return;
1279 }
1280 let state = self.app.read(cx);
1281 let (mode, engine) = (state.mode, state.engine.clone());
1282 if mode.read_only {
1283 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1284 return;
1285 }
1286 if mode.demo {
1287 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1288 return;
1289 }
1290 let Some(engine) = engine else {
1291 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1292 return;
1293 };
1294 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
1295 let known_chat = self
1296 .draft_created
1297 .as_ref()
1298 .filter(|(created_for, _)| *created_for == user_ids)
1299 .map(|(_, chat_id)| chat_id.clone())
1300 .or_else(|| self.draft_target_chat(cx));
1301 self.pending.clear();
1302 self.pending_outgoing.clear();
1303 self.draft_error = None;
1304 self.notice = None;
1305 let key = self.push_pending(&outgoing, cx);
1306 self.rebuild(true, cx);
1307 let recipients_for_finish = user_ids.clone();
1308 let receiver = runtime::spawn(async move {
1309 let chat_id = match known_chat {
1310 Some(chat_id) => chat_id,
1311 None => {
1312 let created = match user_ids.as_slice() {
1313 [user_id] => engine.create_one_on_one(user_id).await,
1314 _ => engine.create_group(&user_ids, topic.as_deref()).await,
1315 };
1316 match created {
1317 Ok(chat_id) => chat_id,
1318 Err(error) => return (None, Some(short_error(&error))),
1319 }
1320 }
1321 };
1322 let sent = engine
1323 .send_message_with_mentions(&chat_id, &outgoing.text, None, &outgoing.mentions)
1324 .await;
1325 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1326 });
1327 cx.spawn_in(window, async move |this, cx| {
1328 let result = receiver.await;
1329 this.update_in(cx, |this, _, cx| {
1330 this.finish_new_chat(&key, recipients_for_finish, result, cx)
1331 })
1332 .ok();
1333 })
1334 .detach();
1335 }
1336
1337 fn finish_new_chat(
1338 &mut self,
1339 key: &str,
1340 user_ids: Vec<String>,
1341 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
1342 cx: &mut Context<Self>,
1343 ) {
1344 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
1345 return;
1346 }
1347 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
1348 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
1349 match (chat_id, error) {
1350 (Some(chat_id), None) => {
1351 self.app.update(cx, |state, cx| {
1352 state.reload_sidebar(cx);
1353 state.select(Selection::Chat(chat_id), cx);
1354 });
1355 }
1356 (created, error) => {
1357 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1358 row.delivery = Delivery::Failed(error.unwrap_or_default());
1359 }
1360 self.draft_error = Some(
1361 if created.is_some() {
1362 "Couldn't send the message."
1363 } else {
1364 "Couldn't create the chat."
1365 }
1366 .to_owned(),
1367 );
1368 self.rebuild(false, cx);
1369 }
1370 }
1371 }
1372
1373 fn send_demo_new_chat(
1374 &mut self,
1375 outgoing: &Outgoing,
1376 recipients: &[super::new_chat::Pick],
1377 topic: Option<&str>,
1378 cx: &mut Context<Self>,
1379 ) {
1380 let (store, chats) = {
1381 let state = self.app.read(cx);
1382 (state.store.clone(), state.sidebar.chats.clone())
1383 };
1384 let people: Vec<(String, String)> = recipients
1385 .iter()
1386 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
1387 .collect();
1388 let (chat, message) = match self.draft_target_chat(cx) {
1389 Some(chat_id) => {
1390 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1391 return;
1392 };
1393 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1394 }
1395 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1396 };
1397 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1398 let _ = store.upsert_messages(std::slice::from_ref(&message));
1399 self.app.update(cx, |state, cx| {
1400 state.reload_sidebar(cx);
1401 state.select(Selection::Chat(chat.id.clone()), cx);
1402 });
1403 }
1404
1115 1405 fn conversation_id(&self) -> Option<String> {
1116 1406 self.current
1117 1407 .as_ref()
@@ -1252,6 +1542,9 @@ impl ConversationView {
1252 1542 }
1253 1543
1254 1544 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1545 if self.draft_active {
1546 return;
1547 }
1255 1548 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1256 1549 Row::Message(message)
1257 1550 if message.own
@@ -1434,7 +1727,11 @@ impl ConversationView {
1434 1727 return;
1435 1728 };
1436 1729 self.pending.retain(|row| row.key != key);
1437 self.send(outgoing, window, cx);
1730 if self.draft_active {
1731 self.send_new_chat(outgoing, window, cx);
1732 } else {
1733 self.send(outgoing, window, cx);
1734 }
1438 1735 }
1439 1736
1440 1737 fn finish_send(
@@ -1470,6 +1767,36 @@ impl ConversationView {
1470 1767 self.rebuild(false, cx);
1471 1768 }
1472 1769
1770 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1771 let message = self.draft_error.clone()?;
1772 let failed_key = self
1773 .pending
1774 .iter()
1775 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
1776 .map(|row| row.key.clone())?;
1777 Some(
1778 h_flex()
1779 .w_full()
1780 .flex_none()
1781 .px(px(24.))
1782 .py(px(4.))
1783 .gap(px(8.))
1784 .items_center()
1785 .text_size(px(12.))
1786 .text_color(theme::red_soft())
1787 .child(message)
1788 .child(
1789 Button::new("retry-new-chat")
1790 .ghost()
1791 .compact()
1792 .label("Retry")
1793 .on_click(cx.listener(move |this, _, window, cx| {
1794 this.retry(&failed_key, window, cx)
1795 })),
1796 ),
1797 )
1798 }
1799
1473 1800 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
1474 1801 let app = self.app.read(cx);
1475 1802 let directory = &app.directory;
@@ -1597,14 +1924,15 @@ impl Render for ConversationView {
1597 1924 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1598 1925 let background = theme::background();
1599 1926 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
1600 let Some(current) = self.current.as_ref() else {
1927 let drafting = self.draft_active;
1928 if self.current.is_none() && !drafting {
1601 1929 return root
1602 1930 .items_center()
1603 1931 .justify_center()
1604 1932 .text_color(theme::text_muted())
1605 1933 .child("Select a chat or channel")
1606 1934 .into_any_element();
1607 };
1935 }
1608 1936 let rows = self.rows.clone();
1609 1937 let view = cx.weak_entity();
1610 1938 let app = self.app.clone();
@@ -1661,7 +1989,7 @@ impl Render for ConversationView {
1661 1989 });
1662 1990 });
1663 1991 }
1664 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1992 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
1665 1993 let hovered = is_real.then(|| {
1666 1994 let (view, key) = (view.clone(), message.key.clone());
1667 1995 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -1769,7 +2097,14 @@ impl Render for ConversationView {
1769 2097 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
1770 2098 .with_bottom_fade(background);
1771 2099
1772 root = root.child(self.render_header(current, cx));
2100 root = match self.current.as_ref().filter(|_| !drafting) {
2101 Some(current) => root.child(self.render_header(current, cx)),
2102 None => root.child(self.draft.clone()),
2103 };
2104 let sync_failed = self
2105 .current
2106 .as_ref()
2107 .is_some_and(|current| current.sync.failed);
1773 2108 if let Some(notice) = &self.notice {
1774 2109 root = root.child(
1775 2110 h_flex()
@@ -1781,7 +2116,7 @@ impl Render for ConversationView {
1781 2116 .bg(theme::amber().opacity(0.15))
1782 2117 .text_color(theme::amber())
1783 2118 .child(div().flex_1().min_w_0().child(notice.clone()))
1784 .when(current.sync.failed, |bar| {
2119 .when(sync_failed, |bar| {
1785 2120 bar.child(
1786 2121 Button::new("retry-fetch")
1787 2122 .ghost()
@@ -1792,8 +2127,16 @@ impl Render for ConversationView {
1792 2127 }),
1793 2128 );
1794 2129 }
1795 let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();
1796 let body = if empty_channel {
2130 let empty_channel = self
2131 .current
2132 .as_ref()
2133 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2134 && self.rows.borrow().is_empty();
2135 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2136 let draft = self.draft.read(cx);
2137 let group_name = draft.group_name(cx);
2138 draft.render_empty(&self.app.read(cx).directory, &group_name)
2139 } else if empty_channel {
1797 2140 div()
1798 2141 .size_full()
1799 2142 .flex()
@@ -1807,7 +2150,15 @@ impl Render for ConversationView {
1807 2150 scroller.into_any_element()
1808 2151 };
1809 2152 root.child(div().flex_1().min_h_0().child(body))
2153 .children(self.render_draft_error(cx))
1810 2154 .child(self.composer.clone())
2155 .when(drafting, |root| {
2156 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2157 if this.draft.read(cx).has_focus(window, cx) {
2158 this.draft.update(cx, |draft, cx| draft.escape(cx));
2159 }
2160 }))
2161 })
1811 2162 .into_any_element()
1812 2163 }
1813 2164 }
@@ -1841,3 +2192,111 @@ fn progress_bar() -> impl IntoElement {
1841 2192 ),
1842 2193 )
1843 2194 }
2195
2196 #[cfg(test)]
2197 mod tests {
2198 use std::sync::Arc;
2199
2200 use gpui_kit::test::TestWindowExt as _;
2201 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2202 use store::Store;
2203
2204 use super::ConversationView;
2205 use crate::app_state::{AppState, Mode, Selection};
2206
2207 #[gpui_kit::test]
2208 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2209 cx.update(gpui_kit::init);
2210 let store = Arc::new(Store::open_in_memory().unwrap());
2211 crate::demo::seed(&store);
2212 let mode = Mode {
2213 demo: true,
2214 read_only: false,
2215 demo_sync: None,
2216 };
2217 let (handle, app, _view) = cx.update(|cx| {
2218 let app = cx.new(|_| {
2219 let mut state = AppState::new(store, mode);
2220 crate::demo::seed_directory(&mut state);
2221 state.selection = Some(crate::demo::first_selection());
2222 state
2223 });
2224 let shared = app.clone();
2225 let (handle, view) =
2226 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2227 cx.new(|cx| ConversationView::new(shared, window, cx))
2228 })
2229 .unwrap();
2230 (handle, app, view)
2231 });
2232 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2233 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
2234 cx.update_window(handle, move |_, window, cx| {
2235 run(window, cx);
2236 window.render_frame(cx);
2237 })
2238 .unwrap();
2239 };
2240 step(cx, |window, cx| window.render_frame(cx));
2241 step(cx, |window, cx| window.input("lea", cx));
2242 step(cx, |window, cx| window.press("enter", cx));
2243 step(cx, |window, cx| window.press("enter", cx));
2244 step(cx, |window, cx| window.input("Hello Lea", cx));
2245 step(cx, |window, cx| window.press("enter", cx));
2246 cx.update(|cx| {
2247 let state = app.read(cx);
2248 assert!(!state.new_chat);
2249 assert_eq!(
2250 state.selection,
2251 Some(Selection::Chat("demo-chat-new-1".to_owned()))
2252 );
2253 let chat = state
2254 .sidebar
2255 .chats
2256 .iter()
2257 .find(|chat| chat.id == "demo-chat-new-1")
2258 .expect("new chat in the sidebar");
2259 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
2260 });
2261 }
2262
2263 #[gpui_kit::test]
2264 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
2265 cx.update(gpui_kit::init);
2266 let store = Arc::new(Store::open_in_memory().unwrap());
2267 crate::demo::seed(&store);
2268 let mode = Mode {
2269 demo: true,
2270 read_only: false,
2271 demo_sync: None,
2272 };
2273 let (handle, app) = cx.update(|cx| {
2274 let app = cx.new(|_| {
2275 let mut state = AppState::new(store, mode);
2276 crate::demo::seed_directory(&mut state);
2277 state.selection = Some(crate::demo::first_selection());
2278 state
2279 });
2280 let shared = app.clone();
2281 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2282 cx.new(|cx| ConversationView::new(shared, window, cx))
2283 })
2284 .unwrap();
2285 (handle, app)
2286 });
2287 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2288 cx.update_window(handle, |_, window, cx| {
2289 window.render_frame(cx);
2290 window.press("escape", cx);
2291 window.render_frame(cx);
2292 window.press("escape", cx);
2293 window.render_frame(cx);
2294 })
2295 .unwrap();
2296 cx.update(|cx| {
2297 let state = app.read(cx);
2298 assert!(!state.new_chat);
2299 assert_eq!(state.selection, Some(crate::demo::first_selection()));
2300 });
2301 }
2302 }
@@ -8,6 +8,7 @@ use gpui_kit::assets::IconName;
8use gpui_kit::component::{
8use gpui_kit::component::{
9 button::{Button, ButtonVariants as _},
9 button::{Button, ButtonVariants as _},
10 h_flex,
10 h_flex,
11 input::Escape,
11 message_scroller::{MessageScroller, MessageScrollerState},
12 message_scroller::{MessageScroller, MessageScrollerState},
12 v_flex,
13 v_flex,
13};
14};
@@ -20,6 +21,7 @@ use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, wit
20use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
21use super::message_actions::{Action, MessageMenu};
22use super::message_actions::{Action, MessageMenu};
22use super::message_row::{RowActions, render_message_row, render_skeleton_row};
23use super::message_row::{RowActions, render_message_row, render_skeleton_row};
24use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
23use super::reaction_picker::{PickHandler, ReactionPicker};
25use super::reaction_picker::{PickHandler, ReactionPicker};
24use super::widgets::icon;
26use super::widgets::icon;
25use crate::app_state::{AppEvent, AppState, Selection, selection_title};
27use crate::app_state::{AppEvent, AppState, Selection, selection_title};
@@ -103,6 +105,10 @@ pub struct ConversationView {
103 app: Entity<AppState>,
105 app: Entity<AppState>,
104 scroller: Entity<MessageScrollerState>,
106 scroller: Entity<MessageScrollerState>,
105 composer: Entity<Composer>,
107 composer: Entity<Composer>,
108 draft: Entity<NewChatDraft>,
109 draft_active: bool,
110 draft_created: Option<(Vec<String>, String)>,
111 draft_error: Option<String>,
106 rows: Rc<RefCell<Vec<Row>>>,
112 rows: Rc<RefCell<Vec<Row>>>,
107 current: Option<Current>,
113 current: Option<Current>,
108 pending: Vec<MessageRow>,
114 pending: Vec<MessageRow>,
@@ -135,15 +141,21 @@ impl ConversationView {
135 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
141 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
136 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
142 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
137 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
143 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), window, cx));
144 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
138 let subscriptions = vec![
145 let subscriptions = vec![
139 cx.subscribe_in(&app, window, Self::on_app_event),
146 cx.subscribe_in(&app, window, Self::on_app_event),
140 cx.subscribe_in(&composer, window, Self::on_composer_event),
147 cx.subscribe_in(&composer, window, Self::on_composer_event),
148 cx.subscribe_in(&draft, window, Self::on_draft_event),
141 cx.observe_window_activation(window, Self::on_window_activation),
149 cx.observe_window_activation(window, Self::on_window_activation),
142 ];
150 ];
143 let mut view = ConversationView {
151 let mut view = ConversationView {
144 app,
152 app,
145 scroller,
153 scroller,
146 composer,
154 composer,
155 draft,
156 draft_active: false,
157 draft_created: None,
158 draft_error: None,
147 rows: Rc::new(RefCell::new(Vec::new())),
159 rows: Rc::new(RefCell::new(Vec::new())),
148 current: None,
160 current: None,
149 pending: Vec::new(),
161 pending: Vec::new(),
@@ -191,8 +203,23 @@ impl ConversationView {
191 ) {
203 ) {
192 match event {
204 match event {
193 AppEvent::Selection => {
205 AppEvent::Selection => {
194 if let Some(selection) = self.app.read(cx).selection.clone() {
206 let (new_chat, selection) = {
195 self.open(selection, window, cx);
207 let state = self.app.read(cx);
208 (state.new_chat, state.selection.clone())
209 };
210 if new_chat {
211 self.enter_draft(window, cx);
212 return;
213 }
214 if self.draft_active {
215 self.leave_draft(window, cx);
216 }
217 match selection {
218 Some(selection) => self.open(selection, window, cx),
219 None => {
220 self.current = None;
221 self.rebuild(true, cx);
222 }
196 }
223 }
197 }
224 }
198 AppEvent::Messages(conversation_id) => {
225 AppEvent::Messages(conversation_id) => {
@@ -218,7 +245,9 @@ impl ConversationView {
218 AppEvent::Directory => cx.notify(),
245 AppEvent::Directory => cx.notify(),
219 AppEvent::Sidebar => {
246 AppEvent::Sidebar => {
220 self.mark_read(ReadTrigger::Incoming, cx);
247 self.mark_read(ReadTrigger::Incoming, cx);
221 if let Some(current) = self.current.as_mut() {
248 if self.draft_active {
249 self.on_draft_changed(window, cx);
250 } else if let Some(current) = self.current.as_mut() {
222 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
251 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
223 if current.title != title {
252 if current.title != title {
224 current.title = title.clone();
253 current.title = title.clone();
@@ -241,6 +270,9 @@ impl ConversationView {
241 cx: &mut Context<Self>,
270 cx: &mut Context<Self>,
242 ) {
271 ) {
243 match event {
272 match event {
273 ComposerEvent::Submit(outgoing) if self.draft_active => {
274 self.send_new_chat(outgoing.clone(), window, cx)
275 }
244 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
276 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
245 self.send_edit(outgoing.clone(), window, cx)
277 self.send_edit(outgoing.clone(), window, cx)
246 }
278 }
@@ -289,12 +321,104 @@ impl ConversationView {
289 .unwrap_or_default();
321 .unwrap_or_default();
290 self.composer.update(cx, |composer, cx| {
322 self.composer.update(cx, |composer, cx| {
291 composer.set_conversation(&target.0, &target.1, window, cx);
323 composer.set_conversation(&target.0, &target.1, window, cx);
292 composer.focus(window, cx);
293 });
324 });
325 if !self.draft_active {
326 self.composer
327 .update(cx, |composer, cx| composer.focus(window, cx));
328 }
294 self.hovered_message = None;
329 self.hovered_message = None;
295 self.apply_pending_jump(cx);
330 self.apply_pending_jump(cx);
296 }
331 }
297
332
333 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
334 if !self.draft_active {
335 self.draft_active = true;
336 self.current = None;
337 self.pending.clear();
338 self.pending_outgoing.clear();
339 self.notice = None;
340 self.draft_created = None;
341 self.draft_error = None;
342 self.toolbar_hovered = None;
343 self.toolbar_pinned = None;
344 self.hovered_message = None;
345 self.sync_generation += 1;
346 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
347 self.composer.update(cx, |composer, cx| {
348 composer.set_conversation("", "", window, cx)
349 });
350 self.on_draft_changed(window, cx);
351 self.rebuild(true, cx);
352 }
353 self.draft
354 .update(cx, |draft, cx| draft.focus_query(window, cx));
355 cx.notify();
356 }
357
358 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
359 self.draft_active = false;
360 self.draft_created = None;
361 self.draft_error = None;
362 self.pending.clear();
363 self.pending_outgoing.clear();
364 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
365 }
366
367 fn on_draft_event(
368 &mut self,
369 _: &Entity<NewChatDraft>,
370 event: &NewChatEvent,
371 window: &mut Window,
372 cx: &mut Context<Self>,
373 ) {
374 match event {
375 NewChatEvent::Changed => self.on_draft_changed(window, cx),
376 NewChatEvent::FocusComposer => self
377 .composer
378 .update(cx, |composer, cx| composer.focus(window, cx)),
379 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
380 }
381 }
382
383 fn draft_target_chat(&self, cx: &App) -> Option<String> {
384 let chips = self.draft.read(cx).chips();
385 let [chip] = chips else {
386 return None;
387 };
388 let state = self.app.read(cx);
389 existing_one_on_one(
390 &state.sidebar.chats,
391 state.directory.me.as_ref(),
392 &chip.user_id,
393 )
394 .map(|chat| chat.id.clone())
395 }
396
397 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
398 if !self.draft_active {
399 return;
400 }
401 let target = self.draft_target_chat(cx);
402 if target != self.conversation_id() {
403 match target {
404 Some(chat_id) => self.open(Selection::Chat(chat_id), window, cx),
405 None => {
406 self.current = None;
407 self.sync_generation += 1;
408 self.rebuild(true, cx);
409 }
410 }
411 }
412 let placeholder = {
413 let draft = self.draft.read(cx);
414 composer_placeholder(draft.chips(), &draft.group_name(cx))
415 };
416 self.composer.update(cx, |composer, cx| {
417 composer.set_placeholder(&placeholder, window, cx)
418 });
419 cx.notify();
420 }
421
298 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
422 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
299 let indices: Vec<usize> = self
423 let indices: Vec<usize> = self
300 .rows
424 .rows
@@ -506,7 +630,14 @@ impl ConversationView {
506
630
507 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
631 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
508 let Some(current) = self.current.as_ref() else {
632 let Some(current) = self.current.as_ref() else {
509 self.apply_rows(Vec::new(), true, cx);
633 let mut rows: Vec<Row> = self
634 .pending
635 .iter()
636 .cloned()
637 .map(|row| Row::Message(Box::new(row)))
638 .collect();
639 assign_series(&mut rows);
640 self.apply_rows(rows, true, cx);
510 return;
641 return;
511 };
642 };
512 let conversation_id = current.selection.conversation_id().to_owned();
643 let conversation_id = current.selection.conversation_id().to_owned();
@@ -914,6 +1045,9 @@ impl ConversationView {
914 }
1045 }
915
1046
916 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1047 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
1048 if self.draft_active {
1049 return;
1050 }
917 let state = self.app.read(cx);
1051 let state = self.app.read(cx);
918 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
1052 let Some(Selection::Chat(chat_id)) = self.current.as_ref().map(|c| c.selection.clone())
919 else {
1053 else {
@@ -1019,52 +1153,17 @@ impl ConversationView {
1019 let Some(current) = self.current.as_ref() else {
1153 let Some(current) = self.current.as_ref() else {
1020 return;
1154 return;
1021 };
1155 };
1022 let restore =
1023 |this: &mut Self, message: &str, window: &mut Window, cx: &mut Context<Self>| {
1024 this.notice = Some(message.to_owned());
1025 this.composer
1026 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
1027 cx.notify();
1028 };
1029 if mode.read_only || mode.demo {
1156 if mode.read_only || mode.demo {
1030 restore(self, "Read-only mode: nothing was sent", window, cx);
1157 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1031 return;
1158 return;
1032 }
1159 }
1033 let Some(engine) = engine else {
1160 let Some(engine) = engine else {
1034 restore(self, "Not connected yet: nothing was sent", window, cx);
1161 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1035 return;
1162 return;
1036 };
1163 };
1037 let conversation_id = current.selection.conversation_id().to_owned();
1164 let conversation_id = current.selection.conversation_id().to_owned();
1038 let view_mode = current.mode.clone();
1165 let view_mode = current.mode.clone();
1039 self.pending_counter += 1;
1166 let key = self.push_pending(&outgoing, cx);
1040 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1041 let my_user_id = self.row_context(cx).my_user_id;
1042 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1043 self.pending.push(MessageRow {
1044 key: key.clone(),
1045 author: "You".to_owned(),
1046 sender_id: my_user_id,
1047 created_at: Utc::now(),
1048 series: Series::default(),
1049 card: false,
1050 time: chrono::Local::now().format("%H:%M").to_string(),
1051 day_header: None,
1052 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1053 edited: false,
1054 deleted: false,
1055 reactions: Vec::new(),
1056 images: Vec::new(),
1057 files: Vec::new(),
1058 reply_count: None,
1059 new_marker: false,
1060 reply_faces: Vec::new(),
1061 last_reply_time: None,
1062 open_thread: None,
1063 is_reply: false,
1064 delivery: Delivery::Sending,
1065 receipt: Receipt::Hidden,
1066 own: true,
1067 });
1068 self.notice = None;
1167 self.notice = None;
1069 self.rebuild(false, cx);
1168 self.rebuild(false, cx);
1070 self.scroller
1169 self.scroller
@@ -1112,6 +1211,197 @@ impl ConversationView {
1112 .detach();
1211 .detach();
1113 }
1212 }
1114
1213
1214 fn restore_unsent(
1215 &mut self,
1216 message: &str,
1217 outgoing: &Outgoing,
1218 window: &mut Window,
1219 cx: &mut Context<Self>,
1220 ) {
1221 self.notice = Some(message.to_owned());
1222 self.composer
1223 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1224 cx.notify();
1225 }
1226
1227 fn push_pending(&mut self, outgoing: &Outgoing, cx: &App) -> String {
1228 self.pending_counter += 1;
1229 let key = format!("{PENDING_KEY_PREFIX}{}", self.pending_counter);
1230 let my_user_id = self.row_context(cx).my_user_id;
1231 self.pending_outgoing.insert(key.clone(), outgoing.clone());
1232 self.pending.push(MessageRow {
1233 key: key.clone(),
1234 author: "You".to_owned(),
1235 sender_id: my_user_id,
1236 created_at: Utc::now(),
1237 series: Series::default(),
1238 card: false,
1239 time: chrono::Local::now().format("%H:%M").to_string(),
1240 day_header: None,
1241 blocks: vec![Block::Paragraph(Inline::plain(&outgoing.text))],
1242 edited: false,
1243 deleted: false,
1244 reactions: Vec::new(),
1245 images: Vec::new(),
1246 files: Vec::new(),
1247 reply_count: None,
1248 new_marker: false,
1249 reply_faces: Vec::new(),
1250 last_reply_time: None,
1251 open_thread: None,
1252 is_reply: false,
1253 delivery: Delivery::Sending,
1254 receipt: Receipt::Hidden,
1255 own: true,
1256 });
1257 key
1258 }
1259
1260 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1261 let (recipients, topic) = {
1262 let draft = self.draft.read(cx);
1263 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
1264 (draft.chips().to_vec(), topic)
1265 };
1266 if recipients.is_empty() {
1267 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1268 self.draft
1269 .update(cx, |draft, cx| draft.focus_query(window, cx));
1270 return;
1271 }
1272 if self
1273 .pending
1274 .iter()
1275 .any(|row| matches!(row.delivery, Delivery::Sending))
1276 {
1277 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1278 return;
1279 }
1280 let state = self.app.read(cx);
1281 let (mode, engine) = (state.mode, state.engine.clone());
1282 if mode.read_only {
1283 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1284 return;
1285 }
1286 if mode.demo {
1287 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
1288 return;
1289 }
1290 let Some(engine) = engine else {
1291 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1292 return;
1293 };
1294 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
1295 let known_chat = self
1296 .draft_created
1297 .as_ref()
1298 .filter(|(created_for, _)| *created_for == user_ids)
1299 .map(|(_, chat_id)| chat_id.clone())
1300 .or_else(|| self.draft_target_chat(cx));
1301 self.pending.clear();
1302 self.pending_outgoing.clear();
1303 self.draft_error = None;
1304 self.notice = None;
1305 let key = self.push_pending(&outgoing, cx);
1306 self.rebuild(true, cx);
1307 let recipients_for_finish = user_ids.clone();
1308 let receiver = runtime::spawn(async move {
1309 let chat_id = match known_chat {
1310 Some(chat_id) => chat_id,
1311 None => {
1312 let created = match user_ids.as_slice() {
1313 [user_id] => engine.create_one_on_one(user_id).await,
1314 _ => engine.create_group(&user_ids, topic.as_deref()).await,
1315 };
1316 match created {
1317 Ok(chat_id) => chat_id,
1318 Err(error) => return (None, Some(short_error(&error))),
1319 }
1320 }
1321 };
1322 let sent = engine
1323 .send_message_with_mentions(&chat_id, &outgoing.text, None, &outgoing.mentions)
1324 .await;
1325 (Some(chat_id), sent.err().map(|error| short_error(&error)))
1326 });
1327 cx.spawn_in(window, async move |this, cx| {
1328 let result = receiver.await;
1329 this.update_in(cx, |this, _, cx| {
1330 this.finish_new_chat(&key, recipients_for_finish, result, cx)
1331 })
1332 .ok();
1333 })
1334 .detach();
1335 }
1336
1337 fn finish_new_chat(
1338 &mut self,
1339 key: &str,
1340 user_ids: Vec<String>,
1341 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
1342 cx: &mut Context<Self>,
1343 ) {
1344 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
1345 return;
1346 }
1347 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
1348 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
1349 match (chat_id, error) {
1350 (Some(chat_id), None) => {
1351 self.app.update(cx, |state, cx| {
1352 state.reload_sidebar(cx);
1353 state.select(Selection::Chat(chat_id), cx);
1354 });
1355 }
1356 (created, error) => {
1357 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
1358 row.delivery = Delivery::Failed(error.unwrap_or_default());
1359 }
1360 self.draft_error = Some(
1361 if created.is_some() {
1362 "Couldn't send the message."
1363 } else {
1364 "Couldn't create the chat."
1365 }
1366 .to_owned(),
1367 );
1368 self.rebuild(false, cx);
1369 }
1370 }
1371 }
1372
1373 fn send_demo_new_chat(
1374 &mut self,
1375 outgoing: &Outgoing,
1376 recipients: &[super::new_chat::Pick],
1377 topic: Option<&str>,
1378 cx: &mut Context<Self>,
1379 ) {
1380 let (store, chats) = {
1381 let state = self.app.read(cx);
1382 (state.store.clone(), state.sidebar.chats.clone())
1383 };
1384 let people: Vec<(String, String)> = recipients
1385 .iter()
1386 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
1387 .collect();
1388 let (chat, message) = match self.draft_target_chat(cx) {
1389 Some(chat_id) => {
1390 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1391 return;
1392 };
1393 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1394 }
1395 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1396 };
1397 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1398 let _ = store.upsert_messages(std::slice::from_ref(&message));
1399 self.app.update(cx, |state, cx| {
1400 state.reload_sidebar(cx);
1401 state.select(Selection::Chat(chat.id.clone()), cx);
1402 });
1403 }
1404
1115 fn conversation_id(&self) -> Option<String> {
1405 fn conversation_id(&self) -> Option<String> {
1116 self.current
1406 self.current
1117 .as_ref()
1407 .as_ref()
@@ -1252,6 +1542,9 @@ impl ConversationView {
1252 }
1542 }
1253
1543
1254 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1544 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1545 if self.draft_active {
1546 return;
1547 }
1255 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1548 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
1256 Row::Message(message)
1549 Row::Message(message)
1257 if message.own
1550 if message.own
@@ -1434,7 +1727,11 @@ impl ConversationView {
1434 return;
1727 return;
1435 };
1728 };
1436 self.pending.retain(|row| row.key != key);
1729 self.pending.retain(|row| row.key != key);
1437 self.send(outgoing, window, cx);
1730 if self.draft_active {
1731 self.send_new_chat(outgoing, window, cx);
1732 } else {
1733 self.send(outgoing, window, cx);
1734 }
1438 }
1735 }
1439
1736
1440 fn finish_send(
1737 fn finish_send(
@@ -1470,6 +1767,36 @@ impl ConversationView {
1470 self.rebuild(false, cx);
1767 self.rebuild(false, cx);
1471 }
1768 }
1472
1769
1770 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
1771 let message = self.draft_error.clone()?;
1772 let failed_key = self
1773 .pending
1774 .iter()
1775 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
1776 .map(|row| row.key.clone())?;
1777 Some(
1778 h_flex()
1779 .w_full()
1780 .flex_none()
1781 .px(px(24.))
1782 .py(px(4.))
1783 .gap(px(8.))
1784 .items_center()
1785 .text_size(px(12.))
1786 .text_color(theme::red_soft())
1787 .child(message)
1788 .child(
1789 Button::new("retry-new-chat")
1790 .ghost()
1791 .compact()
1792 .label("Retry")
1793 .on_click(cx.listener(move |this, _, window, cx| {
1794 this.retry(&failed_key, window, cx)
1795 })),
1796 ),
1797 )
1798 }
1799
1473 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
1800 fn render_header(&self, current: &Current, cx: &mut Context<Self>) -> impl IntoElement {
1474 let app = self.app.read(cx);
1801 let app = self.app.read(cx);
1475 let directory = &app.directory;
1802 let directory = &app.directory;
@@ -1597,14 +1924,15 @@ impl Render for ConversationView {
1597 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1924 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1598 let background = theme::background();
1925 let background = theme::background();
1599 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
1926 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
1600 let Some(current) = self.current.as_ref() else {
1927 let drafting = self.draft_active;
1928 if self.current.is_none() && !drafting {
1601 return root
1929 return root
1602 .items_center()
1930 .items_center()
1603 .justify_center()
1931 .justify_center()
1604 .text_color(theme::text_muted())
1932 .text_color(theme::text_muted())
1605 .child("Select a chat or channel")
1933 .child("Select a chat or channel")
1606 .into_any_element();
1934 .into_any_element();
1607 };
1935 }
1608 let rows = self.rows.clone();
1936 let rows = self.rows.clone();
1609 let view = cx.weak_entity();
1937 let view = cx.weak_entity();
1610 let app = self.app.clone();
1938 let app = self.app.clone();
@@ -1661,7 +1989,7 @@ impl Render for ConversationView {
1661 });
1989 });
1662 });
1990 });
1663 }
1991 }
1664 let is_real = !message.key.starts_with(PENDING_KEY_PREFIX);
1992 let is_real = !drafting && !message.key.starts_with(PENDING_KEY_PREFIX);
1665 let hovered = is_real.then(|| {
1993 let hovered = is_real.then(|| {
1666 let (view, key) = (view.clone(), message.key.clone());
1994 let (view, key) = (view.clone(), message.key.clone());
1667 Rc::new(move |hovered: bool, cx: &mut App| {
1995 Rc::new(move |hovered: bool, cx: &mut App| {
@@ -1769,7 +2097,14 @@ impl Render for ConversationView {
1769 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2097 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
1770 .with_bottom_fade(background);
2098 .with_bottom_fade(background);
1771
2099
1772 root = root.child(self.render_header(current, cx));
2100 root = match self.current.as_ref().filter(|_| !drafting) {
2101 Some(current) => root.child(self.render_header(current, cx)),
2102 None => root.child(self.draft.clone()),
2103 };
2104 let sync_failed = self
2105 .current
2106 .as_ref()
2107 .is_some_and(|current| current.sync.failed);
1773 if let Some(notice) = &self.notice {
2108 if let Some(notice) = &self.notice {
1774 root = root.child(
2109 root = root.child(
1775 h_flex()
2110 h_flex()
@@ -1781,7 +2116,7 @@ impl Render for ConversationView {
1781 .bg(theme::amber().opacity(0.15))
2116 .bg(theme::amber().opacity(0.15))
1782 .text_color(theme::amber())
2117 .text_color(theme::amber())
1783 .child(div().flex_1().min_w_0().child(notice.clone()))
2118 .child(div().flex_1().min_w_0().child(notice.clone()))
1784 .when(current.sync.failed, |bar| {
2119 .when(sync_failed, |bar| {
1785 bar.child(
2120 bar.child(
1786 Button::new("retry-fetch")
2121 Button::new("retry-fetch")
1787 .ghost()
2122 .ghost()
@@ -1792,8 +2127,16 @@ impl Render for ConversationView {
1792 }),
2127 }),
1793 );
2128 );
1794 }
2129 }
1795 let empty_channel = current.mode == ViewMode::ThreadList && self.rows.borrow().is_empty();
2130 let empty_channel = self
1796 let body = if empty_channel {
2131 .current
2132 .as_ref()
2133 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2134 && self.rows.borrow().is_empty();
2135 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2136 let draft = self.draft.read(cx);
2137 let group_name = draft.group_name(cx);
2138 draft.render_empty(&self.app.read(cx).directory, &group_name)
2139 } else if empty_channel {
1797 div()
2140 div()
1798 .size_full()
2141 .size_full()
1799 .flex()
2142 .flex()
@@ -1807,7 +2150,15 @@ impl Render for ConversationView {
1807 scroller.into_any_element()
2150 scroller.into_any_element()
1808 };
2151 };
1809 root.child(div().flex_1().min_h_0().child(body))
2152 root.child(div().flex_1().min_h_0().child(body))
2153 .children(self.render_draft_error(cx))
1810 .child(self.composer.clone())
2154 .child(self.composer.clone())
2155 .when(drafting, |root| {
2156 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
2157 if this.draft.read(cx).has_focus(window, cx) {
2158 this.draft.update(cx, |draft, cx| draft.escape(cx));
2159 }
2160 }))
2161 })
1811 .into_any_element()
2162 .into_any_element()
1812 }
2163 }
1813}
2164}
@@ -1841,3 +2192,111 @@ fn progress_bar() -> impl IntoElement {
1841 ),
2192 ),
1842 )
2193 )
1843}
2194}
2195
2196#[cfg(test)]
2197mod tests {
2198 use std::sync::Arc;
2199
2200 use gpui_kit::test::TestWindowExt as _;
2201 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
2202 use store::Store;
2203
2204 use super::ConversationView;
2205 use crate::app_state::{AppState, Mode, Selection};
2206
2207 #[gpui_kit::test]
2208 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
2209 cx.update(gpui_kit::init);
2210 let store = Arc::new(Store::open_in_memory().unwrap());
2211 crate::demo::seed(&store);
2212 let mode = Mode {
2213 demo: true,
2214 read_only: false,
2215 demo_sync: None,
2216 };
2217 let (handle, app, _view) = cx.update(|cx| {
2218 let app = cx.new(|_| {
2219 let mut state = AppState::new(store, mode);
2220 crate::demo::seed_directory(&mut state);
2221 state.selection = Some(crate::demo::first_selection());
2222 state
2223 });
2224 let shared = app.clone();
2225 let (handle, view) =
2226 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2227 cx.new(|cx| ConversationView::new(shared, window, cx))
2228 })
2229 .unwrap();
2230 (handle, app, view)
2231 });
2232 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2233 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
2234 cx.update_window(handle, move |_, window, cx| {
2235 run(window, cx);
2236 window.render_frame(cx);
2237 })
2238 .unwrap();
2239 };
2240 step(cx, |window, cx| window.render_frame(cx));
2241 step(cx, |window, cx| window.input("lea", cx));
2242 step(cx, |window, cx| window.press("enter", cx));
2243 step(cx, |window, cx| window.press("enter", cx));
2244 step(cx, |window, cx| window.input("Hello Lea", cx));
2245 step(cx, |window, cx| window.press("enter", cx));
2246 cx.update(|cx| {
2247 let state = app.read(cx);
2248 assert!(!state.new_chat);
2249 assert_eq!(
2250 state.selection,
2251 Some(Selection::Chat("demo-chat-new-1".to_owned()))
2252 );
2253 let chat = state
2254 .sidebar
2255 .chats
2256 .iter()
2257 .find(|chat| chat.id == "demo-chat-new-1")
2258 .expect("new chat in the sidebar");
2259 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
2260 });
2261 }
2262
2263 #[gpui_kit::test]
2264 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
2265 cx.update(gpui_kit::init);
2266 let store = Arc::new(Store::open_in_memory().unwrap());
2267 crate::demo::seed(&store);
2268 let mode = Mode {
2269 demo: true,
2270 read_only: false,
2271 demo_sync: None,
2272 };
2273 let (handle, app) = cx.update(|cx| {
2274 let app = cx.new(|_| {
2275 let mut state = AppState::new(store, mode);
2276 crate::demo::seed_directory(&mut state);
2277 state.selection = Some(crate::demo::first_selection());
2278 state
2279 });
2280 let shared = app.clone();
2281 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
2282 cx.new(|cx| ConversationView::new(shared, window, cx))
2283 })
2284 .unwrap();
2285 (handle, app)
2286 });
2287 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
2288 cx.update_window(handle, |_, window, cx| {
2289 window.render_frame(cx);
2290 window.press("escape", cx);
2291 window.render_frame(cx);
2292 window.press("escape", cx);
2293 window.render_frame(cx);
2294 })
2295 .unwrap();
2296 cx.update(|cx| {
2297 let state = app.read(cx);
2298 assert!(!state.new_chat);
2299 assert_eq!(state.selection, Some(crate::demo::first_selection()));
2300 });
2301 }
2302}
crates/app/src/views/mod.rs +1 −0
@@ -5,6 +5,7 @@ pub mod conversation;
5 5 pub mod emoji_popup;
6 6 pub mod message_actions;
7 7 pub mod message_row;
8 pub mod new_chat;
8 9 pub mod reaction_picker;
9 10 pub mod shell;
10 11 pub mod sidebar;
@@ -5,6 +5,7 @@ pub mod conversation;
5pub mod emoji_popup;
5pub mod emoji_popup;
6pub mod message_actions;
6pub mod message_actions;
7pub mod message_row;
7pub mod message_row;
8pub mod new_chat;
8pub mod reaction_picker;
9pub mod reaction_picker;
9pub mod shell;
10pub mod shell;
10pub mod sidebar;
11pub mod sidebar;
crates/app/src/views/new_chat.rs added +960 −0
@@ -0,0 +1,960 @@
1 use std::collections::HashSet;
2 use std::time::Duration;
3
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{
6 h_flex,
7 input::{Backspace, Enter, Input, InputEvent, InputState, MoveDown, MoveUp},
8 v_flex,
9 };
10 use gpui_kit::prelude::FluentBuilder as _;
11 use gpui_kit::*;
12 use store::ChatRecord;
13 use teams_core::MentionCandidate;
14
15 use super::avatar::person_avatar;
16 use super::switcher::clamp_highlight;
17 use super::widgets::icon;
18 use crate::app_state::AppState;
19 use crate::data::{self, Directory, Person};
20 use crate::runtime;
21 use crate::theme;
22
23 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
24 const SUGGESTED_LIMIT: usize = 6;
25 const RESULT_LIMIT: usize = 8;
26 const POPUP_WIDTH: f32 = 300.;
27 const POPUP_ROW_HEIGHT: f32 = 44.;
28 const CHIP_NAME_MAX_WIDTH: f32 = 180.;
29 const DEFAULT_PLACEHOLDER: &str = "Type a message";
30
31 #[derive(Debug, Clone, PartialEq, Eq)]
32 pub struct Pick {
33 pub user_id: String,
34 pub name: String,
35 pub mail: Option<String>,
36 }
37
38 pub enum NewChatEvent {
39 Changed,
40 FocusComposer,
41 Close,
42 }
43
44 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
45 enum EnterAction {
46 Add,
47 Advance,
48 Nothing,
49 }
50
51 fn 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
59 fn 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
80 fn 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
85 pub 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
98 fn 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
107 pub 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
125 pub 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
138 pub 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
151 pub 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
159 fn 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
169 fn 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
180 pub 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
195 impl EventEmitter<NewChatEvent> for NewChatDraft {}
196
197 impl 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
728 impl 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)]
772 mod 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 }
@@ -0,0 +1,960 @@
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}
crates/app/src/views/shell.rs +7 −1
@@ -11,14 +11,17 @@ use crate::notify::NotificationCenter;
11 11 use crate::theme;
12 12 use crate::updater::{self, IdleInputs, UpdateStatus};
13 13
14 actions!(teams, [OpenSwitcher]);
14 actions!(teams, [OpenSwitcher, NewChat]);
15 15
16 16 pub fn bind_keys(cx: &mut App) {
17 17 cx.bind_keys([
18 18 KeyBinding::new("ctrl-k", OpenSwitcher, None),
19 KeyBinding::new("ctrl-n", NewChat, None),
19 20 KeyBinding::new("alt-r", ReplyToHovered, None),
20 21 #[cfg(target_os = "macos")]
21 22 KeyBinding::new("cmd-k", OpenSwitcher, None),
23 #[cfg(target_os = "macos")]
24 KeyBinding::new("cmd-n", NewChat, None),
22 25 ]);
23 26 }
24 27
@@ -255,6 +258,9 @@ impl Render for AppShell {
255 258 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
256 259 this.toggle_switcher("", window, cx);
257 260 }))
261 .on_action(cx.listener(|this, _: &NewChat, _, cx| {
262 this.state.update(cx, |state, cx| state.start_new_chat(cx));
263 }))
258 264 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
259 265 this.conversation.update(cx, |conversation, cx| {
260 266 conversation.reply_to_hovered(window, cx)
@@ -11,14 +11,17 @@ use crate::notify::NotificationCenter;
11use crate::theme;
11use crate::theme;
12use crate::updater::{self, IdleInputs, UpdateStatus};
12use crate::updater::{self, IdleInputs, UpdateStatus};
13
13
14actions!(teams, [OpenSwitcher]);
14actions!(teams, [OpenSwitcher, NewChat]);
15
15
16pub fn bind_keys(cx: &mut App) {
16pub fn bind_keys(cx: &mut App) {
17 cx.bind_keys([
17 cx.bind_keys([
18 KeyBinding::new("ctrl-k", OpenSwitcher, None),
18 KeyBinding::new("ctrl-k", OpenSwitcher, None),
19 KeyBinding::new("ctrl-n", NewChat, None),
19 KeyBinding::new("alt-r", ReplyToHovered, None),
20 KeyBinding::new("alt-r", ReplyToHovered, None),
20 #[cfg(target_os = "macos")]
21 #[cfg(target_os = "macos")]
21 KeyBinding::new("cmd-k", OpenSwitcher, None),
22 KeyBinding::new("cmd-k", OpenSwitcher, None),
23 #[cfg(target_os = "macos")]
24 KeyBinding::new("cmd-n", NewChat, None),
22 ]);
25 ]);
23}
26}
24
27
@@ -255,6 +258,9 @@ impl Render for AppShell {
255 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
258 .on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
256 this.toggle_switcher("", window, cx);
259 this.toggle_switcher("", window, cx);
257 }))
260 }))
261 .on_action(cx.listener(|this, _: &NewChat, _, cx| {
262 this.state.update(cx, |state, cx| state.start_new_chat(cx));
263 }))
258 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
264 .on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
259 this.conversation.update(cx, |conversation, cx| {
265 this.conversation.update(cx, |conversation, cx| {
260 conversation.reply_to_hovered(window, cx)
266 conversation.reply_to_hovered(window, cx)
crates/app/src/views/sidebar.rs +103 −16
@@ -3,7 +3,7 @@ use std::collections::HashSet;
3 3 use chrono::{Local, Offset, Utc};
4 4 use gpui_kit::assets::IconName;
5 5 use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6 use gpui_kit::component::{h_flex, v_flex};
6 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7 7 use gpui_kit::prelude::FluentBuilder as _;
8 8 use gpui_kit::*;
9 9 use store::{ChannelRecord, SidebarTeam, TeamRecord};
@@ -33,6 +33,7 @@ const TEAMS_LABEL: &str = "Teams";
33 33 const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
34 34 const TEAM_ROW_HEIGHT: f32 = 40.;
35 35 const REVEAL_ROW_HEIGHT: f32 = 32.;
36 const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
36 37
37 38 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 39 enum SidebarTab {
@@ -105,7 +106,10 @@ fn preview_icon(text: &str) -> Option<IconName> {
105 106
106 107 impl SidebarView {
107 108 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
108 let subscription = cx.subscribe(&state, |_, _, event: &AppEvent, cx| {
109 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
110 if matches!(event, AppEvent::Selection) && state.read(cx).new_chat {
111 this.tab = SidebarTab::Chats;
112 }
109 113 if matches!(
110 114 event,
111 115 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory
@@ -174,18 +178,91 @@ impl SidebarView {
174 178 let chat_marker =
175 179 (unread_chats > 0).then(|| count_badge(unread_chats, false).into_any_element());
176 180 let channel_marker = channel_dot.then(|| dot(7.).into_any_element());
177 div().w_full().px(px(12.)).pt(px(12.)).pb(px(8.)).child(
178 h_flex()
179 .w_full()
180 .gap(px(4.))
181 .p(px(3.))
182 .rounded(px(8.))
183 .bg(theme::background())
184 .border_1()
185 .border_color(theme::border())
186 .child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))
187 .child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),
188 )
181 h_flex()
182 .w_full()
183 .px(px(12.))
184 .pt(px(12.))
185 .pb(px(8.))
186 .gap(px(8.))
187 .child(
188 h_flex()
189 .flex_1()
190 .min_w_0()
191 .gap(px(4.))
192 .p(px(3.))
193 .rounded(px(8.))
194 .bg(theme::background())
195 .border_1()
196 .border_color(theme::border())
197 .child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))
198 .child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),
199 )
200 .child(self.new_chat_button(cx))
201 }
202
203 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
204 let active = self.state.read(cx).new_chat;
205 div()
206 .id("new-chat")
207 .size(px(NEW_CHAT_BUTTON_SIZE))
208 .flex_none()
209 .flex()
210 .items_center()
211 .justify_center()
212 .rounded(px(8.))
213 .border_1()
214 .border_color(theme::border())
215 .cursor_pointer()
216 .when(active, |button| button.bg(theme::surface_raised()))
217 .hover(|button| button.bg(theme::row_hover()))
218 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
219 .child(icon(IconName::Pencil, 16., theme::text_soft()))
220 .on_click(cx.listener(|this, _, _, cx| {
221 this.state.update(cx, |state, cx| state.start_new_chat(cx));
222 }))
223 }
224
225 fn draft_row(&self) -> impl IntoElement {
226 h_flex()
227 .id("new-chat-draft")
228 .mx(px(8.))
229 .h(px(ROW_HEIGHT))
230 .px(px(8.))
231 .gap(px(10.))
232 .items_center()
233 .rounded(px(8.))
234 .bg(theme::surface_raised())
235 .child(
236 div()
237 .size(px(AVATAR_SIZE))
238 .flex_none()
239 .flex()
240 .items_center()
241 .justify_center()
242 .rounded_full()
243 .bg(theme::border_strong())
244 .child(icon(IconName::Pencil, 16., theme::text())),
245 )
246 .child(
247 v_flex()
248 .flex_1()
249 .min_w_0()
250 .gap(px(2.))
251 .child(
252 div()
253 .truncate()
254 .text_size(px(14.))
255 .text_color(theme::text())
256 .child("New chat"),
257 )
258 .child(
259 div()
260 .truncate()
261 .text_size(px(12.5))
262 .text_color(theme::text_muted())
263 .child("Draft"),
264 ),
265 )
189 266 }
190 267
191 268 fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
@@ -455,13 +532,23 @@ impl SidebarView {
455 532 };
456 533 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
457 534
458 let selected = self.state.read(cx).selection.clone();
535 let (selected, drafting) = {
536 let state = self.state.read(cx);
537 (
538 state.selection.clone().filter(|_| !state.new_chat),
539 state.new_chat,
540 )
541 };
459 542 let mut faces: Vec<String> = Vec::new();
460 543 let mut presence_users: Vec<String> = Vec::new();
461 544 let mut y = 0.;
462 545 let mut list = v_flex().w_full().pb(px(12.));
463 546 let mut skipped_height = 0.;
464 547 let directory_state = self.state.clone();
548 if drafting {
549 list = list.child(self.draft_row());
550 y += ROW_HEIGHT;
551 }
465 552 for section in &sections {
466 553 list = with_spacer(list, &mut skipped_height);
467 554 list = list.child(self.section_header(section, cx));
@@ -820,7 +907,7 @@ impl SidebarView {
820 907 (
821 908 state.sidebar.clone(),
822 909 state.directory.pinned_channels.clone(),
823 state.selection.clone(),
910 state.selection.clone().filter(|_| !state.new_chat),
824 911 )
825 912 };
826 913 let mut list = v_flex().w_full().pb(px(12.));
@@ -3,7 +3,7 @@ use std::collections::HashSet;
3use chrono::{Local, Offset, Utc};
3use chrono::{Local, Offset, Utc};
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6use gpui_kit::component::{h_flex, v_flex};
6use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
8use gpui_kit::*;
9use store::{ChannelRecord, SidebarTeam, TeamRecord};
9use store::{ChannelRecord, SidebarTeam, TeamRecord};
@@ -33,6 +33,7 @@ const TEAMS_LABEL: &str = "Teams";
33const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
33const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
34const TEAM_ROW_HEIGHT: f32 = 40.;
34const TEAM_ROW_HEIGHT: f32 = 40.;
35const REVEAL_ROW_HEIGHT: f32 = 32.;
35const REVEAL_ROW_HEIGHT: f32 = 32.;
36const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
36
37
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38enum SidebarTab {
39enum SidebarTab {
@@ -105,7 +106,10 @@ fn preview_icon(text: &str) -> Option<IconName> {
105
106
106impl SidebarView {
107impl SidebarView {
107 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
108 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
108 let subscription = cx.subscribe(&state, |_, _, event: &AppEvent, cx| {
109 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
110 if matches!(event, AppEvent::Selection) && state.read(cx).new_chat {
111 this.tab = SidebarTab::Chats;
112 }
109 if matches!(
113 if matches!(
110 event,
114 event,
111 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory
115 AppEvent::Sidebar | AppEvent::Selection | AppEvent::Directory
@@ -174,18 +178,91 @@ impl SidebarView {
174 let chat_marker =
178 let chat_marker =
175 (unread_chats > 0).then(|| count_badge(unread_chats, false).into_any_element());
179 (unread_chats > 0).then(|| count_badge(unread_chats, false).into_any_element());
176 let channel_marker = channel_dot.then(|| dot(7.).into_any_element());
180 let channel_marker = channel_dot.then(|| dot(7.).into_any_element());
177 div().w_full().px(px(12.)).pt(px(12.)).pb(px(8.)).child(
181 h_flex()
178 h_flex()
182 .w_full()
179 .w_full()
183 .px(px(12.))
180 .gap(px(4.))
184 .pt(px(12.))
181 .p(px(3.))
185 .pb(px(8.))
182 .rounded(px(8.))
186 .gap(px(8.))
183 .bg(theme::background())
187 .child(
184 .border_1()
188 h_flex()
185 .border_color(theme::border())
189 .flex_1()
186 .child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))
190 .min_w_0()
187 .child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),
191 .gap(px(4.))
188 )
192 .p(px(3.))
193 .rounded(px(8.))
194 .bg(theme::background())
195 .border_1()
196 .border_color(theme::border())
197 .child(self.tab_button(SidebarTab::Chats, "Chats", chat_marker, cx))
198 .child(self.tab_button(SidebarTab::Channels, "Channels", channel_marker, cx)),
199 )
200 .child(self.new_chat_button(cx))
201 }
202
203 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
204 let active = self.state.read(cx).new_chat;
205 div()
206 .id("new-chat")
207 .size(px(NEW_CHAT_BUTTON_SIZE))
208 .flex_none()
209 .flex()
210 .items_center()
211 .justify_center()
212 .rounded(px(8.))
213 .border_1()
214 .border_color(theme::border())
215 .cursor_pointer()
216 .when(active, |button| button.bg(theme::surface_raised()))
217 .hover(|button| button.bg(theme::row_hover()))
218 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
219 .child(icon(IconName::Pencil, 16., theme::text_soft()))
220 .on_click(cx.listener(|this, _, _, cx| {
221 this.state.update(cx, |state, cx| state.start_new_chat(cx));
222 }))
223 }
224
225 fn draft_row(&self) -> impl IntoElement {
226 h_flex()
227 .id("new-chat-draft")
228 .mx(px(8.))
229 .h(px(ROW_HEIGHT))
230 .px(px(8.))
231 .gap(px(10.))
232 .items_center()
233 .rounded(px(8.))
234 .bg(theme::surface_raised())
235 .child(
236 div()
237 .size(px(AVATAR_SIZE))
238 .flex_none()
239 .flex()
240 .items_center()
241 .justify_center()
242 .rounded_full()
243 .bg(theme::border_strong())
244 .child(icon(IconName::Pencil, 16., theme::text())),
245 )
246 .child(
247 v_flex()
248 .flex_1()
249 .min_w_0()
250 .gap(px(2.))
251 .child(
252 div()
253 .truncate()
254 .text_size(px(14.))
255 .text_color(theme::text())
256 .child("New chat"),
257 )
258 .child(
259 div()
260 .truncate()
261 .text_size(px(12.5))
262 .text_color(theme::text_muted())
263 .child("Draft"),
264 ),
265 )
189 }
266 }
190
267
191 fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
268 fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
@@ -455,13 +532,23 @@ impl SidebarView {
455 };
532 };
456 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
533 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
457
534
458 let selected = self.state.read(cx).selection.clone();
535 let (selected, drafting) = {
536 let state = self.state.read(cx);
537 (
538 state.selection.clone().filter(|_| !state.new_chat),
539 state.new_chat,
540 )
541 };
459 let mut faces: Vec<String> = Vec::new();
542 let mut faces: Vec<String> = Vec::new();
460 let mut presence_users: Vec<String> = Vec::new();
543 let mut presence_users: Vec<String> = Vec::new();
461 let mut y = 0.;
544 let mut y = 0.;
462 let mut list = v_flex().w_full().pb(px(12.));
545 let mut list = v_flex().w_full().pb(px(12.));
463 let mut skipped_height = 0.;
546 let mut skipped_height = 0.;
464 let directory_state = self.state.clone();
547 let directory_state = self.state.clone();
548 if drafting {
549 list = list.child(self.draft_row());
550 y += ROW_HEIGHT;
551 }
465 for section in &sections {
552 for section in &sections {
466 list = with_spacer(list, &mut skipped_height);
553 list = with_spacer(list, &mut skipped_height);
467 list = list.child(self.section_header(section, cx));
554 list = list.child(self.section_header(section, cx));
@@ -820,7 +907,7 @@ impl SidebarView {
820 (
907 (
821 state.sidebar.clone(),
908 state.sidebar.clone(),
822 state.directory.pinned_channels.clone(),
909 state.directory.pinned_channels.clone(),
823 state.selection.clone(),
910 state.selection.clone().filter(|_| !state.new_chat),
824 )
911 )
825 };
912 };
826 let mut list = v_flex().w_full().pb(px(12.));
913 let mut list = v_flex().w_full().pb(px(12.));