BlueGit

ict rusty-teams

feat(app): rich text composer with format bar

- Composer keeps a Draft: bold, italic, underline, strike, code and
  links show as you type; Markdown converts while typing and on paste
- Lists, nested lists, quotes and code blocks; Enter continues lists
  and code, Tab and Shift+Tab nest, Backspace lifts a line format
- Format bar over a selection with active and mixed states, link field
  with Apply; Ctrl+B, Ctrl+I, Ctrl+U, Ctrl+Shift+X, Ctrl+Shift+C, Ctrl+K
- Paste hint, Ctrl+Z after a converted paste restores the raw text;
  copy and paste inside the composer keeps formatting
- Undo restores formatting through text snapshots
- Send and edit send Teams HTML (send/edit extras APIs take HTML);
  editing loads the message formatted from its HTML
- insert_lines keeps a converted first line on an empty line

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
62bd9112a9987f1719f3a8f326bcc87cfbf74706
Parent
88cc4c71
18 files changed +1660 −125
README.md +1 −0
@@ -12,6 +12,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
12 12 - Chats and channels, with the Teams pin order, chat folders and hidden teams
13 13 - Live updates over the Teams realtime socket, no polling
14 14 - Send, edit, delete, react, quote-reply, @mentions
15 - Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
15 16 - Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
16 17 - Inline images, file cards, Adaptive Cards as text
17 18 - Read receipts, presence (last known status shown at start), unread jump
@@ -12,6 +12,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
12- Chats and channels, with the Teams pin order, chat folders and hidden teams
12- Chats and channels, with the Teams pin order, chat folders and hidden teams
13- Live updates over the Teams realtime socket, no polling
13- Live updates over the Teams realtime socket, no polling
14- Send, edit, delete, react, quote-reply, @mentions
14- Send, edit, delete, react, quote-reply, @mentions
15- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
15- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
16- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
16- Inline images, file cards, Adaptive Cards as text
17- Inline images, file cards, Adaptive Cards as text
17- Read receipts, presence (last known status shown at start), unread jump
18- Read receipts, presence (last known status shown at start), unread jump
ROADMAP.md +4 −4
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 58 %** (47 done, 4 partial, 34 missing of 85). Partial counts half.
5 **Parity: 59 %** (48 done, 4 partial, 33 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
11 11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12 12 | [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13 13 | [Reading](#reading) | 71 % | 13 | 1 | 5 |
14 | [Writing](#writing) | 68 % | 9 | 1 | 4 |
14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
17 17 | [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -87,7 +87,7 @@ Feature parity with the Microsoft Teams desktop client.
87 87 | Feature | State | Note |
88 88 |---|---|---|
89 89 | Send, multi-line, Enter sends | Done | |
90 | Markdown while typing: bold, code, lists, links | Done | |
90 | Markdown while typing: bold, code, lists, links | Done | Converts as you type or paste; Backspace or Ctrl+Z brings the raw text back |
91 91 | Quote-reply (Alt+R) | Done | |
92 92 | @mentions with people search | Done | |
93 93 | Emoji by colon code, English and German aliases | Done | |
@@ -95,7 +95,7 @@ Feature parity with the Microsoft Teams desktop client.
95 95 | Delete own message | Done | |
96 96 | React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
97 97 | Emoji picker | Partial | For reactions; composer still uses colon codes |
98 | Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
98 | Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block |
99 99 | Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
100 100 | GIFs and stickers | Missing | |
101 101 | Schedule send | Missing | |
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 58 %** (47 done, 4 partial, 34 missing of 85). Partial counts half.
5**Parity: 59 %** (48 done, 4 partial, 33 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -11,7 +11,7 @@ Feature parity with the Microsoft Teams desktop client.
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) | 60 % | 6 | 0 | 4 |
12| [Chat list](#chat-list) | 60 % | 6 | 0 | 4 |
13| [Reading](#reading) | 71 % | 13 | 1 | 5 |
13| [Reading](#reading) | 71 % | 13 | 1 | 5 |
14| [Writing](#writing) | 68 % | 9 | 1 | 4 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
16| [Channels](#channels) | 36 % | 2 | 1 | 4 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
17| [Notifications](#notifications) | 75 % | 6 | 0 | 2 |
@@ -87,7 +87,7 @@ Feature parity with the Microsoft Teams desktop client.
87| Feature | State | Note |
87| Feature | State | Note |
88|---|---|---|
88|---|---|---|
89| Send, multi-line, Enter sends | Done | |
89| Send, multi-line, Enter sends | Done | |
90| Markdown while typing: bold, code, lists, links | Done | |
90| Markdown while typing: bold, code, lists, links | Done | Converts as you type or paste; Backspace or Ctrl+Z brings the raw text back |
91| Quote-reply (Alt+R) | Done | |
91| Quote-reply (Alt+R) | Done | |
92| @mentions with people search | Done | |
92| @mentions with people search | Done | |
93| Emoji by colon code, English and German aliases | Done | |
93| Emoji by colon code, English and German aliases | Done | |
@@ -95,7 +95,7 @@ Feature parity with the Microsoft Teams desktop client.
95| Delete own message | Done | |
95| Delete own message | Done | |
96| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
96| React to a message | Done | Hover bar, emoji picker, click a chip to toggle |
97| Emoji picker | Partial | For reactions; composer still uses colon codes |
97| Emoji picker | Partial | For reactions; composer still uses colon codes |
98| Formatting toolbar, Ctrl+B and Ctrl+I | Missing | |
98| Formatting toolbar, Ctrl+B and Ctrl+I | Done | Bar over a selection; Ctrl+U, Ctrl+Shift+X/C, Ctrl+K link; lists, quote, code block |
99| Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
99| Attach a file, paste or drag an image | Done | Images inline, files via OneDrive or the channel's Files |
100| GIFs and stickers | Missing | |
100| GIFs and stickers | Missing | |
101| Schedule send | Missing | |
101| Schedule send | Missing | |
crates/app/assets/symbols/code.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M320-240 80-480l240-240 57 57-184 184 183 183-56 56Zm320 0-57-57 184-184-183-183 56-56 240 240-240 240Z"/></svg>
crates/app/assets/symbols/format_list_bulleted.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M360-200v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360ZM200-160q-33 0-56.5-23.5T120-240q0-33 23.5-56.5T200-320q33 0 56.5 23.5T280-240q0 33-23.5 56.5T200-160Zm0-240q-33 0-56.5-23.5T120-480q0-33 23.5-56.5T200-560q33 0 56.5 23.5T280-480q0 33-23.5 56.5T200-400Zm0-240q-33 0-56.5-23.5T120-720q0-33 23.5-56.5T200-800q33 0 56.5 23.5T280-720q0 33-23.5 56.5T200-640Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M360-200v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360ZM200-160q-33 0-56.5-23.5T120-240q0-33 23.5-56.5T200-320q33 0 56.5 23.5T280-240q0 33-23.5 56.5T200-160Zm0-240q-33 0-56.5-23.5T120-480q0-33 23.5-56.5T200-560q33 0 56.5 23.5T280-480q0 33-23.5 56.5T200-400Zm0-240q-33 0-56.5-23.5T120-720q0-33 23.5-56.5T200-800q33 0 56.5 23.5T280-720q0 33-23.5 56.5T200-640Z"/></svg>
crates/app/assets/symbols/format_list_numbered.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-80v-60h100v-30h-60v-60h60v-30H120v-60h120q17 0 28.5 11.5T280-280v40q0 17-11.5 28.5T240-200q17 0 28.5 11.5T280-160v40q0 17-11.5 28.5T240-80H120Zm0-280v-110q0-17 11.5-28.5T160-510h60v-30H120v-60h120q17 0 28.5 11.5T280-560v70q0 17-11.5 28.5T240-450h-60v30h100v60H120Zm60-280v-180h-60v-60h120v240h-60Zm180 440v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-80v-60h100v-30h-60v-60h60v-30H120v-60h120q17 0 28.5 11.5T280-280v40q0 17-11.5 28.5T240-200q17 0 28.5 11.5T280-160v40q0 17-11.5 28.5T240-80H120Zm0-280v-110q0-17 11.5-28.5T160-510h60v-30H120v-60h120q17 0 28.5 11.5T280-560v70q0 17-11.5 28.5T240-450h-60v30h100v60H120Zm60-280v-180h-60v-60h120v240h-60Zm180 440v-80h480v80H360Zm0-240v-80h480v80H360Zm0-240v-80h480v80H360Z"/></svg>
crates/app/assets/symbols/format_quote.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m228-240 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T458-480L320-240h-92Zm360 0 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T818-480L680-240h-92ZM320-500q25 0 42.5-17.5T380-560q0-25-17.5-42.5T320-620q-25 0-42.5 17.5T260-560q0 25 17.5 42.5T320-500Zm360 0q25 0 42.5-17.5T740-560q0-25-17.5-42.5T680-620q-25 0-42.5 17.5T620-560q0 25 17.5 42.5T680-500Zm0-60Zm-360 0Z"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m228-240 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T458-480L320-240h-92Zm360 0 92-160q-66 0-113-47t-47-113q0-66 47-113t113-47q66 0 113 47t47 113q0 23-5.5 42.5T818-480L680-240h-92ZM320-500q25 0 42.5-17.5T380-560q0-25-17.5-42.5T320-620q-25 0-42.5 17.5T260-560q0 25 17.5 42.5T320-500Zm360 0q25 0 42.5-17.5T740-560q0-25-17.5-42.5T680-620q-25 0-42.5 17.5T620-560q0 25 17.5 42.5T680-500Zm0-60Zm-360 0Z"/></svg>
crates/app/src/assets.rs +6 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 18] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 23] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -27,6 +27,11 @@ const SYMBOLS: [(&str, &[u8]); 18] = symbols![
27 27 "download",
28 28 "folder_open",
29 29 "refresh",
30 "code",
31 "link",
32 "format_list_bulleted",
33 "format_list_numbered",
34 "format_quote",
30 35 ];
31 36
32 37 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 18] = symbols![
11const SYMBOLS: [(&str, &[u8]); 23] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -27,6 +27,11 @@ const SYMBOLS: [(&str, &[u8]); 18] = symbols![
27 "download",
27 "download",
28 "folder_open",
28 "folder_open",
29 "refresh",
29 "refresh",
30 "code",
31 "link",
32 "format_list_bulleted",
33 "format_list_numbered",
34 "format_quote",
30];
35];
31
36
32pub struct AppAssets;
37pub struct AppAssets;
crates/app/src/demo.rs +19 −10
@@ -333,12 +333,13 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
333 333
334 334 pub fn send_in_chat(
335 335 chat: &ChatRecord,
336 text: &str,
336 preview: &str,
337 html: &str,
337 338 now: DateTime<Utc>,
338 339 ) -> (ChatRecord, MessageRecord) {
339 340 let mut chat = chat.clone();
340 341 chat.last_message_at = Some(now);
341 chat.last_message_preview = Some(text.to_owned());
342 chat.last_message_preview = Some(preview.to_owned());
342 343 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
343 344 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
344 345 chat.last_message_deleted = false;
@@ -349,7 +350,7 @@ pub fn send_in_chat(
349 350 None,
350 351 (DEMO_USER_ID, DEMO_USER_NAME),
351 352 now,
352 &teams_core::markdown_to_html(text),
353 html,
353 354 "[]",
354 355 false,
355 356 );
@@ -360,7 +361,8 @@ pub fn new_chat(
360 361 existing: &[ChatRecord],
361 362 people: &[(String, String)],
362 363 topic: Option<&str>,
363 text: &str,
364 preview: &str,
365 html: &str,
364 366 now: DateTime<Utc>,
365 367 ) -> (ChatRecord, MessageRecord) {
366 368 let number = existing
@@ -388,7 +390,7 @@ pub fn new_chat(
388 390 members,
389 391 ..Default::default()
390 392 };
391 send_in_chat(&chat, text, now)
393 send_in_chat(&chat, preview, html, now)
392 394 }
393 395
394 396 fn image_directory() -> PathBuf {
@@ -1060,14 +1062,21 @@ mod tests {
1060 1062 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1061 1063 ];
1062 1064 let now = Utc::now();
1063 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1065 let (chat, record) = new_chat(
1066 &[],
1067 &people,
1068 Some("Crew"),
1069 "Hello all",
1070 "Hello <i>all</i>",
1071 now,
1072 );
1064 1073 assert_eq!(chat.id, "demo-chat-new-1");
1065 1074 assert_eq!(chat.kind, "group");
1066 1075 assert_eq!(chat.title, "Crew");
1067 1076 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1068 1077 assert_eq!(chat.members.len(), 3);
1069 1078 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1070 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1079 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
1071 1080 assert_eq!(chat.last_message_at, Some(now));
1072 1081 assert_eq!(record.conversation_id, chat.id);
1073 1082 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
@@ -1077,10 +1086,10 @@ mod tests {
1077 1086 #[test]
1078 1087 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1079 1088 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1080 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1089 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
1081 1090 assert_eq!(first.kind, "oneOnOne");
1082 1091 assert!(first.title.is_empty());
1083 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1092 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
1084 1093 assert_eq!(second.id, "demo-chat-new-2");
1085 1094 }
1086 1095
@@ -1091,7 +1100,7 @@ mod tests {
1091 1100 unread: true,
1092 1101 ..Default::default()
1093 1102 };
1094 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1103 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
1095 1104 assert!(!chat.unread);
1096 1105 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1097 1106 assert_eq!(record.conversation_id, "demo-chat-x");
@@ -333,12 +333,13 @@ pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCand
333
333
334pub fn send_in_chat(
334pub fn send_in_chat(
335 chat: &ChatRecord,
335 chat: &ChatRecord,
336 text: &str,
336 preview: &str,
337 html: &str,
337 now: DateTime<Utc>,
338 now: DateTime<Utc>,
338) -> (ChatRecord, MessageRecord) {
339) -> (ChatRecord, MessageRecord) {
339 let mut chat = chat.clone();
340 let mut chat = chat.clone();
340 chat.last_message_at = Some(now);
341 chat.last_message_at = Some(now);
341 chat.last_message_preview = Some(text.to_owned());
342 chat.last_message_preview = Some(preview.to_owned());
342 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
343 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_sender_name = Some(DEMO_USER_NAME.to_owned());
344 chat.last_message_deleted = false;
345 chat.last_message_deleted = false;
@@ -349,7 +350,7 @@ pub fn send_in_chat(
349 None,
350 None,
350 (DEMO_USER_ID, DEMO_USER_NAME),
351 (DEMO_USER_ID, DEMO_USER_NAME),
351 now,
352 now,
352 &teams_core::markdown_to_html(text),
353 html,
353 "[]",
354 "[]",
354 false,
355 false,
355 );
356 );
@@ -360,7 +361,8 @@ pub fn new_chat(
360 existing: &[ChatRecord],
361 existing: &[ChatRecord],
361 people: &[(String, String)],
362 people: &[(String, String)],
362 topic: Option<&str>,
363 topic: Option<&str>,
363 text: &str,
364 preview: &str,
365 html: &str,
364 now: DateTime<Utc>,
366 now: DateTime<Utc>,
365) -> (ChatRecord, MessageRecord) {
367) -> (ChatRecord, MessageRecord) {
366 let number = existing
368 let number = existing
@@ -388,7 +390,7 @@ pub fn new_chat(
388 members,
390 members,
389 ..Default::default()
391 ..Default::default()
390 };
392 };
391 send_in_chat(&chat, text, now)
393 send_in_chat(&chat, preview, html, now)
392}
394}
393
395
394fn image_directory() -> PathBuf {
396fn image_directory() -> PathBuf {
@@ -1060,14 +1062,21 @@ mod tests {
1060 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1062 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1061 ];
1063 ];
1062 let now = Utc::now();
1064 let now = Utc::now();
1063 let (chat, record) = new_chat(&[], &people, Some("Crew"), "Hello *all*", now);
1065 let (chat, record) = new_chat(
1066 &[],
1067 &people,
1068 Some("Crew"),
1069 "Hello all",
1070 "Hello <i>all</i>",
1071 now,
1072 );
1064 assert_eq!(chat.id, "demo-chat-new-1");
1073 assert_eq!(chat.id, "demo-chat-new-1");
1065 assert_eq!(chat.kind, "group");
1074 assert_eq!(chat.kind, "group");
1066 assert_eq!(chat.title, "Crew");
1075 assert_eq!(chat.title, "Crew");
1067 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1076 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1068 assert_eq!(chat.members.len(), 3);
1077 assert_eq!(chat.members.len(), 3);
1069 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1078 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1070 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello *all*"));
1079 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
1071 assert_eq!(chat.last_message_at, Some(now));
1080 assert_eq!(chat.last_message_at, Some(now));
1072 assert_eq!(record.conversation_id, chat.id);
1081 assert_eq!(record.conversation_id, chat.id);
1073 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1082 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
@@ -1077,10 +1086,10 @@ mod tests {
1077 #[test]
1086 #[test]
1078 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1087 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1079 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1088 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1080 let (first, _) = new_chat(&[], &people, None, "Hi", Utc::now());
1089 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
1081 assert_eq!(first.kind, "oneOnOne");
1090 assert_eq!(first.kind, "oneOnOne");
1082 assert!(first.title.is_empty());
1091 assert!(first.title.is_empty());
1083 let (second, _) = new_chat(&[first], &people, None, "Hi again", Utc::now());
1092 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
1084 assert_eq!(second.id, "demo-chat-new-2");
1093 assert_eq!(second.id, "demo-chat-new-2");
1085 }
1094 }
1086
1095
@@ -1091,7 +1100,7 @@ mod tests {
1091 unread: true,
1100 unread: true,
1092 ..Default::default()
1101 ..Default::default()
1093 };
1102 };
1094 let (chat, record) = send_in_chat(&base, "Ping", Utc::now());
1103 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
1095 assert!(!chat.unread);
1104 assert!(!chat.unread);
1096 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1105 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1097 assert_eq!(record.conversation_id, "demo-chat-x");
1106 assert_eq!(record.conversation_id, "demo-chat-x");
crates/app/src/rows.rs +28 −1
@@ -5,7 +5,9 @@ use std::sync::Arc;
5 5 use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6 6 use gpui_kit::Image;
7 7 use store::MessageRecord;
8 use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
8 use teams_core::{
9 Draft, FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions,
10 };
9 11
10 12 use crate::format;
11 13 use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -355,6 +357,15 @@ pub fn message_text(record: &MessageRecord) -> String {
355 357 .join("\n")
356 358 }
357 359
360 /// The message as the composer edits it, formatting kept.
361 pub fn message_draft(record: &MessageRecord) -> Draft {
362 let own_spans: Vec<Span> = message_spans(record)
363 .into_iter()
364 .filter(|span| !matches!(span, Span::Quote(_)))
365 .collect();
366 Draft::from_spans(&own_spans).trimmed()
367 }
368
358 369 pub fn reply_excerpt(record: &MessageRecord) -> String {
359 370 let own_spans: Vec<Span> = message_spans(record)
360 371 .into_iter()
@@ -645,6 +656,22 @@ mod tests {
645 656 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
646 657 }
647 658
659 #[test]
660 fn editing_loads_the_message_formatted_without_its_reply_quote() {
661 let mut edited = record("a", None, 8, 6);
662 edited.body_html =
663 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
664 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
665 <ol><li>one</li><li>two</li></ol>"
666 .into();
667 let draft = message_draft(&edited);
668 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
669 assert_eq!(
670 draft.to_html(),
671 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
672 );
673 }
674
648 675 #[test]
649 676 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
650 677 let mut text = record("a", None, 8, 6);
@@ -5,7 +5,9 @@ use std::sync::Arc;
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
6use gpui_kit::Image;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::{FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions};
8use teams_core::{
9 Draft, FileCard, ImageRef, ReactionInfo, Span, files, images, message_spans, reactions,
10};
9
11
10use crate::format;
12use crate::format;
11use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
13use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
@@ -355,6 +357,15 @@ pub fn message_text(record: &MessageRecord) -> String {
355 .join("\n")
357 .join("\n")
356}
358}
357
359
360/// The message as the composer edits it, formatting kept.
361pub fn message_draft(record: &MessageRecord) -> Draft {
362 let own_spans: Vec<Span> = message_spans(record)
363 .into_iter()
364 .filter(|span| !matches!(span, Span::Quote(_)))
365 .collect();
366 Draft::from_spans(&own_spans).trimmed()
367}
368
358pub fn reply_excerpt(record: &MessageRecord) -> String {
369pub fn reply_excerpt(record: &MessageRecord) -> String {
359 let own_spans: Vec<Span> = message_spans(record)
370 let own_spans: Vec<Span> = message_spans(record)
360 .into_iter()
371 .into_iter()
@@ -645,6 +656,22 @@ mod tests {
645 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
656 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
646 }
657 }
647
658
659 #[test]
660 fn editing_loads_the_message_formatted_without_its_reply_quote() {
661 let mut edited = record("a", None, 8, 6);
662 edited.body_html =
663 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
664 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
665 <ol><li>one</li><li>two</li></ol>"
666 .into();
667 let draft = message_draft(&edited);
668 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
669 assert_eq!(
670 draft.to_html(),
671 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
672 );
673 }
674
648 #[test]
675 #[test]
649 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
676 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
650 let mut text = record("a", None, 8, 6);
677 let mut text = record("a", None, 8, 6);
crates/app/src/views/composer.rs +1012 −78
@@ -1,15 +1,18 @@
1 use std::collections::{HashMap, HashSet};
1 use std::cell::Cell;
2 use std::collections::{HashMap, HashSet, VecDeque};
2 3 use std::ops::Range;
3 4 use std::path::PathBuf;
5 use std::rc::Rc;
4 6 use std::sync::Arc;
5 7 use std::time::Duration;
6 8
7 9 use gpui_kit::assets::IconName;
8 10 use gpui_kit::component::{
9 h_flex,
11 ActiveTheme as _, h_flex,
10 12 input::{
11 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
12 MoveUp, Textarea, TextareaState,
13 Backspace, Copy, Cut, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent,
14 InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
13 16 },
14 17 tooltip::Tooltip,
15 18 v_flex,
@@ -17,7 +20,9 @@ use gpui_kit::component::{
17 20 use gpui_kit::prelude::FluentBuilder as _;
18 21 use gpui_kit::*;
19 22 use teams_core::{
20 FileReference, HostedImage, MentionCandidate, MentionInput, MessageExtras, UploadedFile,
23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24 MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,
25 map_offset, reverse_edits,
21 26 };
22 27
23 28 use super::attachment_tray::{
@@ -26,7 +31,9 @@ use super::attachment_tray::{
26 31 prepare_pasted_image, read_attachment, render_tray,
27 32 };
28 33 use super::avatar::{person_avatar, square_avatar};
34 use super::draft_style::draft_style;
29 35 use super::emoji_popup::{self, EmojiPopup};
36 use super::format_toolbar::{self, FormatButton};
30 37 use super::widgets::{icon, symbol};
31 38 use crate::app_state::AppState;
32 39 use crate::emoji;
@@ -44,6 +51,40 @@ const POPUP_ROW_HEIGHT: f32 = 44.;
44 51 const DEMO_UPLOAD_STEPS: u8 = 10;
45 52 const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
46 53 const DEMO_FAILURE_STEP: u8 = 6;
54 const SNAPSHOT_LIMIT: usize = 100;
55 const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
56 const KEY_CONTEXT: &str = "Composer";
57
58 actions!(
59 composer,
60 [
61 ToggleBold,
62 ToggleItalic,
63 ToggleUnderline,
64 ToggleStrike,
65 ToggleCode,
66 EditLink
67 ]
68 );
69
70 pub fn bind_keys(cx: &mut App) {
71 cx.bind_keys([
72 KeyBinding::new("ctrl-b", ToggleBold, Some(KEY_CONTEXT)),
73 KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),
74 KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),
75 KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),
76 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
77 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
78 #[cfg(target_os = "macos")]
79 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
80 #[cfg(target_os = "macos")]
81 KeyBinding::new("cmd-i", ToggleItalic, Some(KEY_CONTEXT)),
82 #[cfg(target_os = "macos")]
83 KeyBinding::new("cmd-u", ToggleUnderline, Some(KEY_CONTEXT)),
84 #[cfg(target_os = "macos")]
85 KeyBinding::new("cmd-k", EditLink, Some(KEY_CONTEXT)),
86 ]);
87 }
47 88
48 89 #[derive(Debug, Clone, PartialEq, Eq)]
49 90 pub struct ReplyPreview {
@@ -60,7 +101,7 @@ pub struct EditPreview {
60 101
61 102 #[derive(Debug, Clone, PartialEq, Eq)]
62 103 pub struct Outgoing {
63 pub text: String,
104 pub draft: Draft,
64 105 pub mentions: Vec<MentionInput>,
65 106 pub reply: Option<ReplyPreview>,
66 107 pub edit: Option<EditPreview>,
@@ -69,6 +110,16 @@ pub struct Outgoing {
69 110 }
70 111
71 112 impl Outgoing {
113 /// Without list and quote markers, for previews.
114 pub fn text(&self) -> String {
115 self.draft.plain_text()
116 }
117
118 /// The body before mentions become `<at>` tags.
119 pub fn html(&self) -> String {
120 self.draft.to_html()
121 }
122
72 123 pub fn has_attachments(&self) -> bool {
73 124 !self.images.is_empty() || !self.files.is_empty()
74 125 }
@@ -125,13 +176,24 @@ struct MentionPopup {
125 176 highlighted: usize,
126 177 }
127 178
179 /// An automatic edit Backspace takes back while nothing changed since.
128 180 struct Conversion {
129 181 value: String,
130 182 cursor: usize,
183 before: Draft,
184 restore: Vec<Edit>,
185 }
186
187 struct LinkEditor {
131 188 range: Range<usize>,
132 original: String,
189 field: Entity<InputState>,
133 190 }
134 191
192 type DraftDecorations = (
193 TextDecorationCollection<TextareaMode>,
194 RangeDecorationCollection<TextareaMode>,
195 );
196
135 197 pub struct Composer {
136 198 app: Entity<AppState>,
137 199 input: Entity<TextareaState>,
@@ -148,11 +210,23 @@ pub struct Composer {
148 210 conversion: Option<Conversion>,
149 211 undone_value: Option<String>,
150 212 previous_value: String,
213 draft: Draft,
214 decorations: DraftDecorations,
215 pending_style: Option<TypingStyle>,
216 snapshots: VecDeque<Draft>,
217 replaying_history: bool,
218 pasted_markdown: Option<String>,
219 paste_hint: Option<Task<()>>,
220 copied: Option<(String, Vec<DraftLine>)>,
221 toolbar_dismissed: Option<Range<usize>>,
222 mouse_selecting: bool,
223 link_editor: Option<LinkEditor>,
224 composer_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
151 225 tray: AttachmentTray,
152 226 uploads: HashMap<u64, UploadHandle>,
153 227 demo_failed: HashSet<u64>,
154 228 carry_images_into: Option<String>,
155 _subscription: Subscription,
229 _subscriptions: [Subscription; 2],
156 230 }
157 231
158 232 impl EventEmitter<ComposerEvent> for Composer {}
@@ -214,6 +288,22 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {
214 288 }
215 289 }
216 290
291 fn looks_like_url(text: &str) -> bool {
292 ["https://", "http://", "www."]
293 .iter()
294 .any(|prefix| text.starts_with(prefix))
295 && !text.contains(char::is_whitespace)
296 }
297
298 fn normalized_url(text: &str) -> String {
299 let text = text.trim();
300 if text.is_empty() || text.contains("://") || text.starts_with("mailto:") {
301 text.to_owned()
302 } else {
303 format!("https://{text}")
304 }
305 }
306
217 307 fn candidate_key(candidate: &MentionCandidate) -> &str {
218 308 match candidate {
219 309 MentionCandidate::Person(person) => &person.user_id,
@@ -231,6 +321,13 @@ impl Composer {
231 321 .placeholder("Type a message")
232 322 });
233 323 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
324 let observer = cx.observe(&input, |_, _, cx| cx.notify());
325 let decorations = input.update(cx, |state, cx| {
326 (
327 state.create_decorations_collection(Vec::new(), cx),
328 state.create_range_decorations_collection(Vec::new(), cx),
329 )
330 });
234 331 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
235 332 Composer {
236 333 app,
@@ -248,11 +345,23 @@ impl Composer {
248 345 conversion: None,
249 346 undone_value: None,
250 347 previous_value: String::new(),
348 draft: Draft::default(),
349 decorations,
350 pending_style: None,
351 snapshots: VecDeque::new(),
352 replaying_history: false,
353 pasted_markdown: None,
354 paste_hint: None,
355 copied: None,
356 toolbar_dismissed: None,
357 mouse_selecting: false,
358 link_editor: None,
359 composer_bounds: Rc::new(Cell::new(None)),
251 360 tray: AttachmentTray::default(),
252 361 uploads: HashMap::new(),
253 362 demo_failed: HashSet::new(),
254 363 carry_images_into: None,
255 _subscription: subscription,
364 _subscriptions: [subscription, observer],
256 365 }
257 366 }
258 367
@@ -265,7 +374,7 @@ impl Composer {
265 374 ) {
266 375 cx.notify();
267 376 if matches!(event, InputEvent::Change) {
268 self.convert_typed(window, cx);
377 self.on_change(window, cx);
269 378 self.update_emoji(cx);
270 379 self.update_mention(cx);
271 380 }
@@ -312,29 +421,216 @@ impl Composer {
312 421 self.lookup = None;
313 422 }
314 423
315 fn convert_typed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
424 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316 425 let state = self.input.read(cx);
317 426 let (value, cursor) = (state.value().to_string(), state.cursor());
318 427 let previous = std::mem::replace(&mut self.previous_value, value.clone());
319 let found = match emoji::typed_char(&previous, &value, cursor) {
320 Some(':') => emoji::closing_code(&value, cursor)
428 let replaying = std::mem::take(&mut self.replaying_history);
429 if value == self.draft.text() {
430 self.refresh_style(cx);
431 return;
432 }
433 if replaying && let Some(snapshot) = self.snapshot_for(&value) {
434 self.draft = snapshot;
435 self.pending_style = None;
436 self.refresh_style(cx);
437 return;
438 }
439 let typing = self.pending_style.take();
440 let cursor = self.draft.apply_edit(&value, cursor, typing.as_ref());
441 self.commit(Some(cursor), window, cx);
442 if replaying {
443 return;
444 }
445 if let Some(pasted) = self.pasted_markdown.take()
446 && self.convert_paste(&pasted, cursor, window, cx)
447 {
448 return;
449 }
450 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
451 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
452 return;
453 }
454 self.convert_emoji(typed, cursor, window, cx);
455 }
456
457 fn convert_markdown(
458 &mut self,
459 cursor: usize,
460 window: &mut Window,
461 cx: &mut Context<Self>,
462 ) -> bool {
463 let before = self.draft.clone();
464 let Some((cursor, style)) = self.draft.convert_typed(cursor) else {
465 self.draft.take_edits();
466 return false;
467 };
468 self.finish_conversion(before, cursor, window, cx);
469 self.pending_style = (!style.is_empty()).then_some(style);
470 true
471 }
472
473 fn convert_emoji(
474 &mut self,
475 typed: Option<char>,
476 cursor: usize,
477 window: &mut Window,
478 cx: &mut Context<Self>,
479 ) {
480 let value = self.draft.text();
481 let found = match typed {
482 Some(':') => emoji::closing_code(value, cursor)
321 483 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
322 Some(' ') => emoji::smiley_before_space(&value, cursor),
484 Some(' ') => emoji::smiley_before_space(value, cursor),
323 485 _ => None,
324 486 };
325 487 let Some((range, glyph)) = found else {
326 488 return;
327 489 };
328 let original = value[range.clone()].to_owned();
329 let cursor = self.replace_text(range.clone(), glyph, cursor, window, cx);
330 self.previous_value = self.input.read(cx).value().to_string();
490 let before = self.draft.clone();
491 self.draft.replace(range.clone(), glyph);
492 self.finish_conversion(before, cursor + glyph.len() - range.len(), window, cx);
493 self.remember_emoji(glyph, cx);
494 }
495
496 fn finish_conversion(
497 &mut self,
498 before: Draft,
499 cursor: usize,
500 window: &mut Window,
501 cx: &mut Context<Self>,
502 ) {
503 let edits = self.draft.take_edits();
504 let restore = reverse_edits(&edits, before.text());
505 self.apply_to_input(edits, cursor..cursor, window, cx);
331 506 self.conversion = Some(Conversion {
332 value: self.previous_value.clone(),
507 value: self.draft.text().to_owned(),
333 508 cursor,
334 range: range.start..range.start + glyph.len(),
335 original,
509 before,
510 restore,
336 511 });
337 self.remember_emoji(glyph, cx);
512 }
513
514 fn convert_paste(
515 &mut self,
516 pasted: &str,
517 cursor: usize,
518 window: &mut Window,
519 cx: &mut Context<Self>,
520 ) -> bool {
521 let pasted = pasted.replace("\r\n", "\n");
522 let Some(start) = cursor
523 .checked_sub(pasted.len())
524 .filter(|start| self.draft.text().get(*start..cursor) == Some(pasted.as_str()))
525 else {
526 return false;
527 };
528 let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);
529 let cursor = self.draft.insert_lines(start..cursor, &lines);
530 self.commit(Some(cursor), window, cx);
531 self.paste_hint = Some(cx.spawn(async move |this, cx| {
532 cx.background_executor().timer(PASTE_HINT_DURATION).await;
533 this.update(cx, |this, cx| {
534 this.paste_hint = None;
535 cx.notify();
536 })
537 .ok();
538 }));
539 true
540 }
541
542 /// Puts the draft's pending edits into the input, then places the selection.
543 fn commit(&mut self, cursor: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
544 let edits = self.draft.take_edits();
545 let selection = self.input.read(cx).selected_range();
546 let selection = match cursor {
547 Some(cursor) => cursor..cursor,
548 None if edits.is_empty() => selection,
549 None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),
550 };
551 self.apply_to_input(edits, selection, window, cx);
552 }
553
554 fn apply_to_input(
555 &mut self,
556 edits: Vec<Edit>,
557 selection: Range<usize>,
558 window: &mut Window,
559 cx: &mut Context<Self>,
560 ) {
561 self.input.update(cx, |state, cx| {
562 let edited = !edits.is_empty();
563 if edited {
564 state.apply_edits(&edits, window, cx);
565 }
566 if edited || state.selected_range() != selection {
567 state.set_selected_range(selection.clone(), cx);
568 }
569 });
570 let value = self.input.read(cx).value().to_string();
571 if value != self.draft.text() {
572 self.draft.apply_edit(&value, selection.end, None);
573 self.draft.take_edits();
574 }
575 self.previous_value = value;
576 self.remember_snapshot();
577 self.refresh_style(cx);
578 }
579
580 fn remember_snapshot(&mut self) {
581 if self
582 .snapshots
583 .back()
584 .is_some_and(|last| last.text() == self.draft.text())
585 {
586 self.snapshots.pop_back();
587 }
588 self.snapshots.push_back(self.draft.clone());
589 if self.snapshots.len() > SNAPSHOT_LIMIT {
590 self.snapshots.pop_front();
591 }
592 }
593
594 fn snapshot_for(&self, value: &str) -> Option<Draft> {
595 self.snapshots
596 .iter()
597 .rev()
598 .find(|snapshot| snapshot.text() == value)
599 .cloned()
600 }
601
602 fn refresh_style(&mut self, cx: &mut Context<Self>) {
603 let style = draft_style(&self.draft, cx.theme().mono_font_family.clone());
604 let (text, ranges) = &self.decorations;
605 text.set(style.text, cx);
606 ranges.set(style.ranges, cx);
607 self.input
608 .update(cx, |state, cx| state.set_hanging_indents(style.markers, cx));
609 }
610
611 fn load_draft(
612 &mut self,
613 draft: Draft,
614 content: InputContent,
615 window: &mut Window,
616 cx: &mut Context<Self>,
617 ) {
618 let end = draft.text().len();
619 self.input.update(cx, |state, cx| {
620 state.set_value(content, window, cx);
621 state.set_selected_range(end..end, cx);
622 });
623 self.previous_value = draft.text().to_owned();
624 self.draft = draft;
625 self.pending_style = None;
626 self.conversion = None;
627 self.pasted_markdown = None;
628 self.paste_hint = None;
629 self.link_editor = None;
630 self.toolbar_dismissed = None;
631 self.snapshots.clear();
632 self.remember_snapshot();
633 self.refresh_style(cx);
338 634 }
339 635
340 636 /// Returns the cursor, kept at the same spot relative to the text after `range`.
@@ -363,18 +659,228 @@ impl Composer {
363 659 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
364 660 return false;
365 661 };
366 self.replace_text(
367 conversion.range,
368 &conversion.original,
369 conversion.cursor,
370 window,
371 cx,
372 );
662 let cursor = map_offset(&conversion.restore, conversion.cursor);
663 self.draft = conversion.before;
664 self.pending_style = None;
665 self.apply_to_input(conversion.restore, cursor..cursor, window, cx);
373 666 self.undone_value = Some(self.input.read(cx).value().to_string());
374 667 self.update_emoji(cx);
375 668 true
376 669 }
377 670
671 fn selection(&self, cx: &App) -> Range<usize> {
672 self.input.read(cx).selected_range()
673 }
674
675 fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) {
676 let selection = self.selection(cx);
677 if selection.is_empty() {
678 let cursor = selection.start;
679 let mut pending = self
680 .pending_style
681 .take()
682 .filter(|pending| pending.at == cursor)
683 .unwrap_or(TypingStyle {
684 at: cursor,
685 ..TypingStyle::default()
686 });
687 pending.toggle(kind, &self.draft.style_at(cursor));
688 self.pending_style = (!pending.is_empty()).then_some(pending);
689 } else {
690 self.draft.toggle(selection, kind);
691 self.draft.take_edits();
692 self.remember_snapshot();
693 self.refresh_style(cx);
694 }
695 cx.notify();
696 }
697
698 fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {
699 let selection = self.selection(cx);
700 self.draft.toggle_lines(selection, kind);
701 self.commit(None, window, cx);
702 cx.notify();
703 }
704
705 fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {
706 match button {
707 FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),
708 FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
709 FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),
710 FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),
711 FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),
712 FormatButton::Link => self.open_link_editor(window, cx),
713 FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),
714 FormatButton::Numbered => self.toggle_lines(LineKind::Numbered(0), window, cx),
715 FormatButton::Quote => self.toggle_lines(LineKind::Quote, window, cx),
716 }
717 }
718
719 fn format_state(&self, button: FormatButton, selection: &Range<usize>) -> FormatState {
720 let range = selection.clone();
721 match button {
722 FormatButton::Bold => self.draft.state(range, &MarkKind::Bold),
723 FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),
724 FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),
725 FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),
726 FormatButton::Code => self.draft.state(range, &MarkKind::Code),
727 FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),
728 FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),
729 FormatButton::Numbered => self.draft.line_state(range, &LineKind::Numbered(0)),
730 FormatButton::Quote => self.draft.line_state(range, &LineKind::Quote),
731 }
732 }
733
734 fn edit_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
735 if self.link_editor.is_some() {
736 return;
737 }
738 if self.draft.is_blank() && self.selection(cx).is_empty() {
739 window.dispatch_action(Box::new(super::shell::OpenSwitcher), cx);
740 return;
741 }
742 self.open_link_editor(window, cx);
743 }
744
745 fn open_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
746 let range = self.selection(cx);
747 let prefill = self
748 .draft
749 .link_in(range.clone())
750 .or_else(|| {
751 cx.read_from_clipboard()
752 .and_then(|item| item.text())
753 .map(|text| text.trim().to_owned())
754 .filter(|text| looks_like_url(text))
755 })
756 .unwrap_or_default();
757 let field = cx.new(|cx| {
758 InputState::new(window, cx)
759 .placeholder("Paste or type a link")
760 .default_value(prefill)
761 });
762 field.update(cx, |state, cx| {
763 state.focus(window, cx);
764 state.select_all(window, cx);
765 });
766 self.link_editor = Some(LinkEditor { range, field });
767 cx.notify();
768 }
769
770 fn apply_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
771 let Some(editor) = self.link_editor.take() else {
772 return;
773 };
774 let url = normalized_url(&editor.field.read(cx).value());
775 self.focus(window, cx);
776 if editor.range.is_empty() {
777 if !url.is_empty() {
778 let end = self.draft.insert_link(editor.range.start, &url, &url);
779 self.commit(Some(end), window, cx);
780 }
781 } else {
782 self.draft.set_link(editor.range.clone(), &url);
783 self.draft.take_edits();
784 self.remember_snapshot();
785 self.refresh_style(cx);
786 self.input.update(cx, |state, cx| {
787 state.set_selected_range(editor.range.clone(), cx)
788 });
789 self.toolbar_dismissed = Some(editor.range);
790 }
791 cx.notify();
792 }
793
794 fn close_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
795 let Some(editor) = self.link_editor.take() else {
796 return;
797 };
798 self.focus(window, cx);
799 self.input
800 .update(cx, |state, cx| state.set_selected_range(editor.range, cx));
801 cx.notify();
802 }
803
804 fn break_line(&mut self, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
805 let selection = self.selection(cx);
806 if !selection.is_empty() {
807 return false;
808 }
809 match self.draft.break_line(selection.start, shift) {
810 Some(cursor) => {
811 self.commit(Some(cursor), window, cx);
812 true
813 }
814 None => false,
815 }
816 }
817
818 fn backspace_at_start(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
819 let selection = self.selection(cx);
820 if !selection.is_empty() {
821 return false;
822 }
823 match self.draft.backspace_at_start(selection.start) {
824 Some(cursor) => {
825 self.commit(Some(cursor), window, cx);
826 true
827 }
828 None => false,
829 }
830 }
831
832 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
833 let selection = self.selection(cx);
834 if !self.draft.indent(selection, outdent) {
835 return false;
836 }
837 self.commit(None, window, cx);
838 true
839 }
840
841 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
842 let selection = self.selection(cx);
843 let Some(text) = self.draft.text().get(selection.clone()).map(str::to_owned) else {
844 return false;
845 };
846 if text.is_empty() {
847 return false;
848 }
849 let lines = self.draft.slice(selection);
850 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
851 text.clone(),
852 lines.clone(),
853 ));
854 self.copied = Some((text, lines));
855 true
856 }
857
858 fn copied_lines(&self, item: &ClipboardItem, text: &str) -> Option<Vec<DraftLine>> {
859 item.entries()
860 .iter()
861 .find_map(|entry| match entry {
862 ClipboardEntry::String(string) if string.text() == text => {
863 string.metadata_json::<Vec<DraftLine>>()
864 }
865 _ => None,
866 })
867 .or_else(|| {
868 let normalized = text.replace("\r\n", "\n");
869 self.copied
870 .as_ref()
871 .filter(|(copied, _)| *copied == normalized)
872 .map(|(_, lines)| lines.clone())
873 })
874 }
875
876 fn toolbar_requested(&self, cx: &App) -> bool {
877 let selection = self.selection(cx);
878 !selection.is_empty()
879 && !self.mouse_selecting
880 && self.toolbar_dismissed.as_ref() != Some(&selection)
881 && !self.popup_is_open()
882 }
883
378 884 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
379 885 self.recent_emoji.push(glyph);
380 886 self.recent_emoji.save(&self.app.read(cx).store);
@@ -543,8 +1049,7 @@ impl Composer {
543 1049 self.discard_uploaded(dropped, cx);
544 1050 self.reply = None;
545 1051 if self.editing.take().is_some() {
546 self.input
547 .update(cx, |state, cx| state.set_value("", window, cx));
1052 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
548 1053 }
549 1054 self.mention_inputs.clear();
550 1055 self.close_popup();
@@ -581,15 +1086,16 @@ impl Composer {
581 1086
582 1087 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
583 1088 let state = self.input.read(cx);
584 let mut text = state.value().trim().to_owned();
585 1089 if !self.can_send(cx) {
586 1090 return None;
587 1091 }
1092 let mut draft = self.current_draft(cx).trimmed();
588 1093 let attachments_apply = self.editing.is_none();
589 1094 if self.undone_value.as_deref() != Some(state.value().as_ref())
590 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
1095 && let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
591 1096 {
592 text.replace_range(range, glyph);
1097 draft.replace(range, glyph);
1098 draft.take_edits();
593 1099 }
594 1100 let mentions = state
595 1101 .tokens()
@@ -598,7 +1104,7 @@ impl Composer {
598 1104 .cloned()
599 1105 .collect();
600 1106 Some(Outgoing {
601 text,
1107 draft,
602 1108 mentions,
603 1109 reply: self.reply.clone(),
604 1110 edit: self.editing.clone(),
@@ -615,8 +1121,18 @@ impl Composer {
615 1121 })
616 1122 }
617 1123
1124 /// The draft, or the plain input text while a change is still on its way to the draft.
1125 fn current_draft(&self, cx: &App) -> Draft {
1126 let value = self.input.read(cx).value();
1127 if self.draft.text() == value.as_ref() {
1128 self.draft.clone()
1129 } else {
1130 Draft::plain(&value)
1131 }
1132 }
1133
618 1134 fn can_send(&self, cx: &App) -> bool {
619 let has_text = !self.input.read(cx).value().trim().is_empty();
1135 let has_text = !self.current_draft(cx).is_blank();
620 1136 if self.editing.is_some() {
621 1137 return has_text;
622 1138 }
@@ -693,21 +1209,30 @@ impl Composer {
693 1209 .detach();
694 1210 }
695 1211
696 fn paste(&mut self, item: &ClipboardItem, cx: &mut Context<Self>) -> bool {
697 if self.editing.is_some() {
698 return false;
699 }
700 match paste_action(item) {
701 PasteAction::Text => false,
702 PasteAction::Files(paths) => {
703 self.add_paths(paths, cx);
704 true
705 }
706 PasteAction::Image(pasted) => {
707 self.add_pasted_image(pasted, cx);
708 true
1212 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
1213 if self.editing.is_none() {
1214 match paste_action(item) {
1215 PasteAction::Text => {}
1216 PasteAction::Files(paths) => {
1217 self.add_paths(paths, cx);
1218 return true;
1219 }
1220 PasteAction::Image(pasted) => {
1221 self.add_pasted_image(pasted, cx);
1222 return true;
1223 }
709 1224 }
710 1225 }
1226 let Some(text) = item.text() else {
1227 return false;
1228 };
1229 if let Some(lines) = self.copied_lines(item, &text) {
1230 let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1231 self.commit(Some(cursor), window, cx);
1232 return true;
1233 }
1234 self.pasted_markdown = has_markdown(&text).then_some(text);
1235 false
711 1236 }
712 1237
713 1238 fn finish_reading(
@@ -878,8 +1403,7 @@ impl Composer {
878 1403 let Some(outgoing) = self.outgoing(cx) else {
879 1404 return;
880 1405 };
881 self.input
882 .update(cx, |state, cx| state.set_value("", window, cx));
1406 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
883 1407 self.mention_inputs.clear();
884 1408 if self.editing.is_none() {
885 1409 self.tray.clear();
@@ -893,11 +1417,12 @@ impl Composer {
893 1417
894 1418 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
895 1419 self.mention_inputs.clear();
896 let mut content = InputContent::new(outgoing.text.clone());
1420 let text = outgoing.draft.text();
1421 let mut content = InputContent::new(text.to_owned());
897 1422 let mut cursor = 0;
898 1423 for mention in &outgoing.mentions {
899 1424 let needle = format!("@{}", mention.text);
900 let Some(offset) = outgoing.text[cursor..].find(&needle) else {
1425 let Some(offset) = text[cursor..].find(&needle) else {
901 1426 continue;
902 1427 };
903 1428 let range = cursor + offset..cursor + offset + needle.len();
@@ -910,11 +1435,7 @@ impl Composer {
910 1435 cursor = range.end;
911 1436 }
912 1437 }
913 let end = outgoing.text.len();
914 self.input.update(cx, |state, cx| {
915 state.set_value(content, window, cx);
916 state.set_selected_range(end..end, cx);
917 });
1438 self.load_draft(outgoing.draft.clone(), content, window, cx);
918 1439 self.reply = outgoing.reply.clone();
919 1440 self.editing = outgoing.edit.clone();
920 1441 if outgoing.edit.is_none() {
@@ -925,21 +1446,19 @@ impl Composer {
925 1446 cx.notify();
926 1447 }
927 1448
1449 /// Markdown in `text` arrives formatted.
928 1450 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
929 let text = text.to_owned();
930 let end = text.len();
931 self.input.update(cx, |state, cx| {
932 state.set_value(text, window, cx);
933 state.set_selected_range(end..end, cx);
934 });
1451 let draft = Draft::from_markdown(text);
1452 let content = InputContent::new(draft.text().to_owned());
1453 self.load_draft(draft, content, window, cx);
935 1454 self.mention_inputs.clear();
936 1455 self.update_emoji(cx);
937 1456 self.update_mention(cx);
938 1457 cx.notify();
939 1458 }
940 1459
941 pub fn is_empty(&self, cx: &App) -> bool {
942 self.input.read(cx).value().trim().is_empty() && self.tray.is_empty()
1460 pub fn is_empty(&self, _: &App) -> bool {
1461 self.draft.is_blank() && self.tray.is_empty()
943 1462 }
944 1463
945 1464 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1059,6 +1578,91 @@ impl Composer {
1059 1578 ))
1060 1579 }
1061 1580
1581 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
1582 let composer = cx.entity().downgrade();
1583 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
1584 return None;
1585 }
1586 let state = self.input.read(cx);
1587 let range = self
1588 .link_editor
1589 .as_ref()
1590 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
1591 let start = state.range_to_bounds(&(range.start..range.start))?;
1592 let end = state.range_to_bounds(&(range.end..range.end))?;
1593 let input_bounds = state.input_bounds();
1594 let center_x = if start.origin.y == end.origin.y {
1595 (start.origin.x + end.origin.x) / 2.
1596 } else {
1597 input_bounds.center().x
1598 };
1599 let edges = self
1600 .composer_bounds
1601 .get()
1602 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
1603 (bounds.left(), bounds.right())
1604 });
1605 let width = match self.link_editor {
1606 Some(_) => format_toolbar::link_width(),
1607 None => format_toolbar::bar_width(),
1608 };
1609 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
1610 let element = match &self.link_editor {
1611 Some(editor) => format_toolbar::render(
1612 placement,
1613 format_toolbar::Mode::Link {
1614 field: &editor.field,
1615 on_apply: Rc::new(move |window, cx| {
1616 composer
1617 .update(cx, |this, cx| this.apply_link(window, cx))
1618 .ok();
1619 }),
1620 },
1621 ),
1622 None => {
1623 let state_of = |button| self.format_state(button, &range);
1624 format_toolbar::render(
1625 placement,
1626 format_toolbar::Mode::Bar {
1627 state: &state_of,
1628 on_press: Rc::new(move |button, window, cx| {
1629 composer
1630 .update(cx, |this, cx| this.press_format(button, window, cx))
1631 .ok();
1632 }),
1633 },
1634 )
1635 }
1636 };
1637 Some(element)
1638 }
1639
1640 fn render_paste_hint(&self) -> Option<Div> {
1641 self.paste_hint.as_ref()?;
1642 Some(
1643 h_flex()
1644 .mt(px(6.))
1645 .gap(px(6.))
1646 .items_center()
1647 .text_size(px(12.))
1648 .text_color(theme::text_muted())
1649 .child("Formatted from Markdown")
1650 .child(
1651 div()
1652 .px(px(5.))
1653 .py(px(1.))
1654 .rounded(px(4.))
1655 .border_1()
1656 .border_color(theme::border_strong())
1657 .bg(theme::surface_raised())
1658 .text_size(px(11.))
1659 .text_color(theme::text())
1660 .child("Ctrl+Z"),
1661 )
1662 .child("plain text"),
1663 )
1664 }
1665
1062 1666 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1063 1667 let edit = self.editing.as_ref()?;
1064 1668 Some(
@@ -1204,9 +1808,9 @@ impl Render for Composer {
1204 1808 let input = Textarea::new(&self.input)
1205 1809 .appearance(false)
1206 1810 .bordered(false)
1207 .on_paste(move |item, _, cx| {
1811 .on_paste(move |item, window, cx| {
1208 1812 composer
1209 .update(cx, |this, cx| this.paste(item, cx))
1813 .update(cx, |this, cx| this.paste(item, window, cx))
1210 1814 .unwrap_or(false)
1211 1815 })
1212 1816 .token(|context, _, _| {
@@ -1241,14 +1845,68 @@ impl Render for Composer {
1241 1845 .text_color(theme::amber())
1242 1846 .child(notice.to_owned())
1243 1847 });
1848 let composer_bounds = self.composer_bounds.clone();
1244 1849 v_flex()
1245 1850 .w_full()
1246 1851 .flex_none()
1247 1852 .px(px(24.))
1248 1853 .pt(px(8.))
1249 1854 .pb(px(12.))
1855 .key_context(KEY_CONTEXT)
1856 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
1857 if this.link_editor.is_none() {
1858 this.toggle_mark(MarkKind::Bold, cx);
1859 }
1860 }))
1861 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
1862 if this.link_editor.is_none() {
1863 this.toggle_mark(MarkKind::Italic, cx);
1864 }
1865 }))
1866 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
1867 if this.link_editor.is_none() {
1868 this.toggle_mark(MarkKind::Underline, cx);
1869 }
1870 }))
1871 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
1872 if this.link_editor.is_none() {
1873 this.toggle_mark(MarkKind::Strike, cx);
1874 }
1875 }))
1876 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
1877 if this.link_editor.is_none() {
1878 this.toggle_mark(MarkKind::Code, cx);
1879 }
1880 }))
1881 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
1882 .capture_action(cx.listener(|this, _: &Undo, _, _| {
1883 if this.link_editor.is_none() {
1884 this.replaying_history = true;
1885 this.conversion = None;
1886 this.paste_hint = None;
1887 }
1888 }))
1889 .capture_action(cx.listener(|this, _: &Redo, _, _| {
1890 if this.link_editor.is_none() {
1891 this.replaying_history = true;
1892 this.conversion = None;
1893 }
1894 }))
1895 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
1896 if this.link_editor.is_none() && this.copy_selection(cx) {
1897 cx.stop_propagation();
1898 }
1899 }))
1900 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
1901 if this.link_editor.is_none() && this.copy_selection(cx) {
1902 this.input
1903 .update(cx, |state, cx| state.replace("", window, cx));
1904 cx.stop_propagation();
1905 }
1906 }))
1250 1907 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
1251 if this.popup_is_open() {
1908 if this.link_editor.is_some() {
1909 } else if this.popup_is_open() {
1252 1910 this.move_highlight(-1, cx);
1253 1911 cx.stop_propagation();
1254 1912 } else if this.editing.is_none() && this.is_empty(cx) {
@@ -1257,29 +1915,55 @@ impl Render for Composer {
1257 1915 }
1258 1916 }))
1259 1917 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
1260 if this.popup_is_open() {
1918 if this.link_editor.is_none() && this.popup_is_open() {
1261 1919 this.move_highlight(1, cx);
1262 1920 cx.stop_propagation();
1263 1921 }
1264 1922 }))
1265 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
1266 if this.popup_is_open() {
1923 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
1924 if this.link_editor.is_some() {
1925 this.apply_link(window, cx);
1926 cx.stop_propagation();
1927 } else if this.popup_is_open() {
1267 1928 this.accept_popup(window, cx);
1268 1929 cx.stop_propagation();
1930 } else if this.break_line(action.shift, window, cx) {
1931 cx.stop_propagation();
1269 1932 }
1270 1933 }))
1271 1934 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
1272 if this.popup_is_open() {
1935 if this.link_editor.is_some() {
1936 } else if this.popup_is_open() {
1273 1937 this.accept_popup(window, cx);
1274 1938 cx.stop_propagation();
1939 } else if this.indent(false, window, cx) {
1940 cx.stop_propagation();
1941 }
1942 }))
1943 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
1944 if this.link_editor.is_none() && this.indent(true, window, cx) {
1945 cx.stop_propagation();
1275 1946 }
1276 1947 }))
1277 1948 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
1278 if this.undo_conversion(window, cx) {
1949 if this.link_editor.is_none()
1950 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
1951 {
1279 1952 cx.stop_propagation();
1280 1953 }
1281 1954 }))
1282 1955 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
1956 if this.link_editor.is_some() {
1957 this.close_link_editor(window, cx);
1958 cx.stop_propagation();
1959 return;
1960 }
1961 if this.toolbar_requested(cx) {
1962 this.toolbar_dismissed = Some(this.selection(cx));
1963 cx.notify();
1964 cx.stop_propagation();
1965 return;
1966 }
1283 1967 if let Some(popup) = &this.emoji_popup {
1284 1968 this.emoji_dismissed_at = Some(popup.range.start);
1285 1969 }
@@ -1301,8 +1985,10 @@ impl Render for Composer {
1301 1985 .w_full()
1302 1986 .children(self.render_popup(cx))
1303 1987 .children(self.render_emoji_popup(window, cx))
1988 .children(self.render_toolbar(focused, cx))
1304 1989 .child(
1305 1990 v_flex()
1991 .relative()
1306 1992 .w_full()
1307 1993 .rounded(px(10.))
1308 1994 .bg(theme::surface())
@@ -1312,6 +1998,14 @@ impl Render for Composer {
1312 1998 } else {
1313 1999 theme::border_strong()
1314 2000 })
2001 .child(
2002 canvas(
2003 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2004 |_, _, _, _| {},
2005 )
2006 .absolute()
2007 .size_full(),
2008 )
1315 2009 .children(tray)
1316 2010 .child(
1317 2011 h_flex()
@@ -1322,11 +2016,37 @@ impl Render for Composer {
1322 2016 .pl(px(if can_attach { 6. } else { 12. }))
1323 2017 .pr(px(6.))
1324 2018 .children(attach)
1325 .child(div().flex_1().min_w_0().child(input))
2019 .child(
2020 div()
2021 .flex_1()
2022 .min_w_0()
2023 .capture_any_mouse_down(cx.listener(
2024 |this, _: &MouseDownEvent, _, _| {
2025 this.mouse_selecting = true;
2026 this.toolbar_dismissed = None;
2027 this.link_editor = None;
2028 },
2029 ))
2030 .capture_any_mouse_up(cx.listener(
2031 |this, _: &MouseUpEvent, _, cx| {
2032 this.mouse_selecting = false;
2033 cx.notify();
2034 },
2035 ))
2036 .on_mouse_up_out(
2037 MouseButton::Left,
2038 cx.listener(|this, _, _, cx| {
2039 this.mouse_selecting = false;
2040 cx.notify();
2041 }),
2042 )
2043 .child(input),
2044 )
1326 2045 .child(send),
1327 2046 ),
1328 2047 ),
1329 2048 )
2049 .children(self.render_paste_hint())
1330 2050 }
1331 2051 }
1332 2052
@@ -1410,7 +2130,7 @@ mod tests {
1410 2130 use super::{Outgoing, OutgoingFile, OutgoingImage};
1411 2131
1412 2132 let outgoing = Outgoing {
1413 text: String::new(),
2133 draft: teams_core::Draft::default(),
1414 2134 mentions: Vec::new(),
1415 2135 reply: None,
1416 2136 edit: None,
@@ -1486,6 +2206,220 @@ mod tests {
1486 2206 assert_eq!(value, "X");
1487 2207 }
1488 2208
2209 struct Typist<'a> {
2210 cx: &'a mut TestAppContext,
2211 handle: gpui_kit::AnyWindowHandle,
2212 composer: gpui_kit::Entity<Composer>,
2213 }
2214
2215 impl Typist<'_> {
2216 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
2217 self.cx
2218 .update_window(self.handle, |_, window, cx| action(window, cx))
2219 .unwrap();
2220 self.cx.run_until_parked();
2221 }
2222
2223 fn type_text(&mut self, text: &str) {
2224 for character in text.chars() {
2225 self.act(|window, cx| window.input(&character.to_string(), cx));
2226 }
2227 }
2228
2229 fn press(&mut self, keys: &str) {
2230 for key in keys.split(' ') {
2231 self.act(|window, cx| window.press(key, cx));
2232 }
2233 }
2234
2235 fn value(&mut self) -> String {
2236 let composer = self.composer.clone();
2237 self.cx
2238 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
2239 }
2240
2241 fn draft(&mut self) -> teams_core::Draft {
2242 let composer = self.composer.clone();
2243 self.cx.update(|cx| composer.read(cx).draft.clone())
2244 }
2245
2246 fn outgoing(&mut self) -> super::super::Outgoing {
2247 let composer = self.composer.clone();
2248 self.cx
2249 .update(|cx| composer.read(cx).outgoing(cx))
2250 .expect("text to send")
2251 }
2252 }
2253
2254 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
2255 let (handle, composer) = demo_composer(cx);
2256 cx.update(super::super::bind_keys);
2257 let mut typist = Typist {
2258 cx,
2259 handle,
2260 composer: composer.clone(),
2261 };
2262 typist.act(|window, cx| {
2263 composer.update(cx, |composer, cx| composer.focus(window, cx));
2264 window.render_frame(cx);
2265 });
2266 typist
2267 }
2268
2269 #[gpui_kit::test]
2270 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
2271 use teams_core::{FormatState, MarkKind};
2272
2273 let mut typist = typist(cx);
2274 typist.type_text("a **bold**");
2275 assert_eq!(typist.value(), "a bold");
2276 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
2277 typist.press("backspace");
2278 assert_eq!(typist.value(), "a **bold**");
2279 assert!(typist.draft().marks().is_empty());
2280 let composer = typist.composer.clone();
2281 assert_eq!(
2282 typist
2283 .cx
2284 .update(|cx| composer.read(cx).input.read(cx).cursor()),
2285 10
2286 );
2287 typist.press("backspace");
2288 typist.type_text("* x");
2289 assert_eq!(typist.value(), "a bold x");
2290 assert_eq!(
2291 typist.draft().state(6..8, &MarkKind::Bold),
2292 FormatState::Off
2293 );
2294 }
2295
2296 #[gpui_kit::test]
2297 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
2298 let mut typist = typist(cx);
2299 typist.type_text("1. one");
2300 typist.press("enter");
2301 typist.type_text("two");
2302 assert_eq!(typist.value(), "1. one\n2. two");
2303 typist.press("enter enter");
2304 assert_eq!(typist.value(), "1. one\n2. two\n");
2305 typist.type_text("after");
2306 typist.press("enter");
2307 assert_eq!(typist.value(), "");
2308 }
2309
2310 #[gpui_kit::test]
2311 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
2312 let mut typist = typist(cx);
2313 typist.type_text("- a");
2314 typist.press("enter tab");
2315 typist.type_text("b");
2316 assert_eq!(typist.value(), "• a\n\u{2003}\u{2003}◦ b");
2317 typist.press("shift-tab");
2318 assert_eq!(typist.value(), "• a\n• b");
2319 }
2320
2321 #[gpui_kit::test]
2322 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
2323 use teams_core::{FormatState, MarkKind};
2324
2325 let mut typist = typist(cx);
2326 typist.type_text("hello");
2327 typist.press("shift-left shift-left ctrl-b");
2328 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2329 assert_eq!(
2330 typist.draft().state(0..5, &MarkKind::Bold),
2331 FormatState::Mixed
2332 );
2333 typist.press("ctrl-b");
2334 assert!(typist.draft().marks().is_empty());
2335 typist.press("end ctrl-i");
2336 typist.type_text("!");
2337 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
2338 }
2339
2340 #[gpui_kit::test]
2341 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
2342 let mut typist = typist(cx);
2343 typist
2344 .cx
2345 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2346 "**hi** there".to_owned(),
2347 ));
2348 typist.press("ctrl-v");
2349 assert_eq!(typist.value(), "hi there");
2350 let composer = typist.composer.clone();
2351 assert!(
2352 typist
2353 .cx
2354 .update(|cx| composer.read(cx).paste_hint.is_some())
2355 );
2356 typist.press("ctrl-z");
2357 assert_eq!(typist.value(), "**hi** there");
2358 assert!(typist.draft().marks().is_empty());
2359 }
2360
2361 #[gpui_kit::test]
2362 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
2363 use teams_core::{FormatState, MarkKind};
2364
2365 let mut typist = typist(cx);
2366 typist.type_text("`code` ");
2367 typist.press("ctrl-a ctrl-c end ctrl-v");
2368 assert_eq!(typist.value(), "code code ");
2369 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
2370 }
2371
2372 #[gpui_kit::test]
2373 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
2374 use teams_core::{FormatState, MarkKind};
2375
2376 let mut typist = typist(cx);
2377 typist.type_text("~~old~~");
2378 typist.press("ctrl-a");
2379 typist.type_text("new");
2380 typist.press("ctrl-z ctrl-z");
2381 assert_eq!(typist.value(), "old");
2382 assert_eq!(
2383 typist.draft().state(0..3, &MarkKind::Strike),
2384 FormatState::On
2385 );
2386 }
2387
2388 #[gpui_kit::test]
2389 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
2390 let mut typist = typist(cx);
2391 typist.type_text("see docs");
2392 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
2393 let composer = typist.composer.clone();
2394 assert!(
2395 typist
2396 .cx
2397 .update(|cx| composer.read(cx).link_editor.is_some())
2398 );
2399 typist.type_text("example.com");
2400 typist.press("enter");
2401 assert!(
2402 typist
2403 .cx
2404 .update(|cx| composer.read(cx).link_editor.is_none())
2405 );
2406 assert_eq!(
2407 typist.outgoing().html(),
2408 "see <a href=\"https://example.com\">docs</a>"
2409 );
2410 }
2411
2412 #[gpui_kit::test]
2413 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
2414 let mut typist = typist(cx);
2415 typist.type_text("> quoted");
2416 typist.press("shift-enter");
2417 typist.type_text("more");
2418 let outgoing = typist.outgoing();
2419 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
2420 assert_eq!(outgoing.text(), "quoted\nmore");
2421 }
2422
1489 2423 #[gpui_kit::test]
1490 2424 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
1491 2425 cx.update(gpui_kit::init);
@@ -1527,7 +2461,7 @@ mod tests {
1527 2461 let outgoing = composer
1528 2462 .outgoing(cx)
1529 2463 .expect("an attachment alone is a message");
1530 assert_eq!(outgoing.text, "");
2464 assert_eq!(outgoing.text(), "");
1531 2465 assert_eq!(outgoing.files.len(), 1);
1532 2466 assert_eq!(outgoing.files[0].name, "plan.pdf");
1533 2467 });
@@ -1617,7 +2551,7 @@ mod tests {
1617 2551 cx.update_window(handle, |_, window, cx| {
1618 2552 composer.update(cx, |composer, cx| {
1619 2553 let draft = Outgoing {
1620 text: "old".into(),
2554 draft: teams_core::Draft::plain("old"),
1621 2555 mentions: Vec::new(),
1622 2556 reply: None,
1623 2557 edit: Some(EditPreview {
@@ -1636,7 +2570,7 @@ mod tests {
1636 2570 assert_eq!(composer.tray.items().len(), 1);
1637 2571 let outgoing = composer.outgoing(cx).unwrap();
1638 2572 assert!(outgoing.files.is_empty());
1639 assert_eq!(outgoing.text, "old");
2573 assert_eq!(outgoing.text(), "old");
1640 2574 });
1641 2575 cx.update_window(handle, |_, window, cx| {
1642 2576 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
@@ -1,15 +1,18 @@
1use std::collections::{HashMap, HashSet};
1use std::cell::Cell;
2use std::collections::{HashMap, HashSet, VecDeque};
2use std::ops::Range;
3use std::ops::Range;
3use std::path::PathBuf;
4use std::path::PathBuf;
5use std::rc::Rc;
4use std::sync::Arc;
6use std::sync::Arc;
5use std::time::Duration;
7use std::time::Duration;
6
8
7use gpui_kit::assets::IconName;
9use gpui_kit::assets::IconName;
8use gpui_kit::component::{
10use gpui_kit::component::{
9 h_flex,
11 ActiveTheme as _, h_flex,
10 input::{
12 input::{
11 Backspace, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent, MoveDown,
13 Backspace, Copy, Cut, Enter, Escape, IndentInline, InlineToken, InputContent, InputEvent,
12 MoveUp, Textarea, TextareaState,
14 InputState, MoveDown, MoveUp, OutdentInline, RangeDecorationCollection, Redo,
15 TextDecorationCollection, Textarea, TextareaMode, TextareaState, Undo,
13 },
16 },
14 tooltip::Tooltip,
17 tooltip::Tooltip,
15 v_flex,
18 v_flex,
@@ -17,7 +20,9 @@ use gpui_kit::component::{
17use gpui_kit::prelude::FluentBuilder as _;
20use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
21use gpui_kit::*;
19use teams_core::{
22use teams_core::{
20 FileReference, HostedImage, MentionCandidate, MentionInput, MessageExtras, UploadedFile,
23 Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24 MentionCandidate, MentionInput, MessageExtras, TypingStyle, UploadedFile, has_markdown,
25 map_offset, reverse_edits,
21};
26};
22
27
23use super::attachment_tray::{
28use super::attachment_tray::{
@@ -26,7 +31,9 @@ use super::attachment_tray::{
26 prepare_pasted_image, read_attachment, render_tray,
31 prepare_pasted_image, read_attachment, render_tray,
27};
32};
28use super::avatar::{person_avatar, square_avatar};
33use super::avatar::{person_avatar, square_avatar};
34use super::draft_style::draft_style;
29use super::emoji_popup::{self, EmojiPopup};
35use super::emoji_popup::{self, EmojiPopup};
36use super::format_toolbar::{self, FormatButton};
30use super::widgets::{icon, symbol};
37use super::widgets::{icon, symbol};
31use crate::app_state::AppState;
38use crate::app_state::AppState;
32use crate::emoji;
39use crate::emoji;
@@ -44,6 +51,40 @@ const POPUP_ROW_HEIGHT: f32 = 44.;
44const DEMO_UPLOAD_STEPS: u8 = 10;
51const DEMO_UPLOAD_STEPS: u8 = 10;
45const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
52const DEMO_UPLOAD_STEP: Duration = Duration::from_millis(120);
46const DEMO_FAILURE_STEP: u8 = 6;
53const DEMO_FAILURE_STEP: u8 = 6;
54const SNAPSHOT_LIMIT: usize = 100;
55const PASTE_HINT_DURATION: Duration = Duration::from_secs(4);
56const KEY_CONTEXT: &str = "Composer";
57
58actions!(
59 composer,
60 [
61 ToggleBold,
62 ToggleItalic,
63 ToggleUnderline,
64 ToggleStrike,
65 ToggleCode,
66 EditLink
67 ]
68);
69
70pub fn bind_keys(cx: &mut App) {
71 cx.bind_keys([
72 KeyBinding::new("ctrl-b", ToggleBold, Some(KEY_CONTEXT)),
73 KeyBinding::new("ctrl-i", ToggleItalic, Some(KEY_CONTEXT)),
74 KeyBinding::new("ctrl-u", ToggleUnderline, Some(KEY_CONTEXT)),
75 KeyBinding::new("ctrl-shift-x", ToggleStrike, Some(KEY_CONTEXT)),
76 KeyBinding::new("ctrl-shift-c", ToggleCode, Some(KEY_CONTEXT)),
77 KeyBinding::new("ctrl-k", EditLink, Some(KEY_CONTEXT)),
78 #[cfg(target_os = "macos")]
79 KeyBinding::new("cmd-b", ToggleBold, Some(KEY_CONTEXT)),
80 #[cfg(target_os = "macos")]
81 KeyBinding::new("cmd-i", ToggleItalic, Some(KEY_CONTEXT)),
82 #[cfg(target_os = "macos")]
83 KeyBinding::new("cmd-u", ToggleUnderline, Some(KEY_CONTEXT)),
84 #[cfg(target_os = "macos")]
85 KeyBinding::new("cmd-k", EditLink, Some(KEY_CONTEXT)),
86 ]);
87}
47
88
48#[derive(Debug, Clone, PartialEq, Eq)]
89#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct ReplyPreview {
90pub struct ReplyPreview {
@@ -60,7 +101,7 @@ pub struct EditPreview {
60
101
61#[derive(Debug, Clone, PartialEq, Eq)]
102#[derive(Debug, Clone, PartialEq, Eq)]
62pub struct Outgoing {
103pub struct Outgoing {
63 pub text: String,
104 pub draft: Draft,
64 pub mentions: Vec<MentionInput>,
105 pub mentions: Vec<MentionInput>,
65 pub reply: Option<ReplyPreview>,
106 pub reply: Option<ReplyPreview>,
66 pub edit: Option<EditPreview>,
107 pub edit: Option<EditPreview>,
@@ -69,6 +110,16 @@ pub struct Outgoing {
69}
110}
70
111
71impl Outgoing {
112impl Outgoing {
113 /// Without list and quote markers, for previews.
114 pub fn text(&self) -> String {
115 self.draft.plain_text()
116 }
117
118 /// The body before mentions become `<at>` tags.
119 pub fn html(&self) -> String {
120 self.draft.to_html()
121 }
122
72 pub fn has_attachments(&self) -> bool {
123 pub fn has_attachments(&self) -> bool {
73 !self.images.is_empty() || !self.files.is_empty()
124 !self.images.is_empty() || !self.files.is_empty()
74 }
125 }
@@ -125,13 +176,24 @@ struct MentionPopup {
125 highlighted: usize,
176 highlighted: usize,
126}
177}
127
178
179/// An automatic edit Backspace takes back while nothing changed since.
128struct Conversion {
180struct Conversion {
129 value: String,
181 value: String,
130 cursor: usize,
182 cursor: usize,
183 before: Draft,
184 restore: Vec<Edit>,
185}
186
187struct LinkEditor {
131 range: Range<usize>,
188 range: Range<usize>,
132 original: String,
189 field: Entity<InputState>,
133}
190}
134
191
192type DraftDecorations = (
193 TextDecorationCollection<TextareaMode>,
194 RangeDecorationCollection<TextareaMode>,
195);
196
135pub struct Composer {
197pub struct Composer {
136 app: Entity<AppState>,
198 app: Entity<AppState>,
137 input: Entity<TextareaState>,
199 input: Entity<TextareaState>,
@@ -148,11 +210,23 @@ pub struct Composer {
148 conversion: Option<Conversion>,
210 conversion: Option<Conversion>,
149 undone_value: Option<String>,
211 undone_value: Option<String>,
150 previous_value: String,
212 previous_value: String,
213 draft: Draft,
214 decorations: DraftDecorations,
215 pending_style: Option<TypingStyle>,
216 snapshots: VecDeque<Draft>,
217 replaying_history: bool,
218 pasted_markdown: Option<String>,
219 paste_hint: Option<Task<()>>,
220 copied: Option<(String, Vec<DraftLine>)>,
221 toolbar_dismissed: Option<Range<usize>>,
222 mouse_selecting: bool,
223 link_editor: Option<LinkEditor>,
224 composer_bounds: Rc<Cell<Option<Bounds<Pixels>>>>,
151 tray: AttachmentTray,
225 tray: AttachmentTray,
152 uploads: HashMap<u64, UploadHandle>,
226 uploads: HashMap<u64, UploadHandle>,
153 demo_failed: HashSet<u64>,
227 demo_failed: HashSet<u64>,
154 carry_images_into: Option<String>,
228 carry_images_into: Option<String>,
155 _subscription: Subscription,
229 _subscriptions: [Subscription; 2],
156}
230}
157
231
158impl EventEmitter<ComposerEvent> for Composer {}
232impl EventEmitter<ComposerEvent> for Composer {}
@@ -214,6 +288,22 @@ fn candidate_subtitle(candidate: &MentionCandidate) -> String {
214 }
288 }
215}
289}
216
290
291fn looks_like_url(text: &str) -> bool {
292 ["https://", "http://", "www."]
293 .iter()
294 .any(|prefix| text.starts_with(prefix))
295 && !text.contains(char::is_whitespace)
296}
297
298fn normalized_url(text: &str) -> String {
299 let text = text.trim();
300 if text.is_empty() || text.contains("://") || text.starts_with("mailto:") {
301 text.to_owned()
302 } else {
303 format!("https://{text}")
304 }
305}
306
217fn candidate_key(candidate: &MentionCandidate) -> &str {
307fn candidate_key(candidate: &MentionCandidate) -> &str {
218 match candidate {
308 match candidate {
219 MentionCandidate::Person(person) => &person.user_id,
309 MentionCandidate::Person(person) => &person.user_id,
@@ -231,6 +321,13 @@ impl Composer {
231 .placeholder("Type a message")
321 .placeholder("Type a message")
232 });
322 });
233 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
323 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
324 let observer = cx.observe(&input, |_, _, cx| cx.notify());
325 let decorations = input.update(cx, |state, cx| {
326 (
327 state.create_decorations_collection(Vec::new(), cx),
328 state.create_range_decorations_collection(Vec::new(), cx),
329 )
330 });
234 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
331 let recent_emoji = emoji::Recent::load(&app.read(cx).store);
235 Composer {
332 Composer {
236 app,
333 app,
@@ -248,11 +345,23 @@ impl Composer {
248 conversion: None,
345 conversion: None,
249 undone_value: None,
346 undone_value: None,
250 previous_value: String::new(),
347 previous_value: String::new(),
348 draft: Draft::default(),
349 decorations,
350 pending_style: None,
351 snapshots: VecDeque::new(),
352 replaying_history: false,
353 pasted_markdown: None,
354 paste_hint: None,
355 copied: None,
356 toolbar_dismissed: None,
357 mouse_selecting: false,
358 link_editor: None,
359 composer_bounds: Rc::new(Cell::new(None)),
251 tray: AttachmentTray::default(),
360 tray: AttachmentTray::default(),
252 uploads: HashMap::new(),
361 uploads: HashMap::new(),
253 demo_failed: HashSet::new(),
362 demo_failed: HashSet::new(),
254 carry_images_into: None,
363 carry_images_into: None,
255 _subscription: subscription,
364 _subscriptions: [subscription, observer],
256 }
365 }
257 }
366 }
258
367
@@ -265,7 +374,7 @@ impl Composer {
265 ) {
374 ) {
266 cx.notify();
375 cx.notify();
267 if matches!(event, InputEvent::Change) {
376 if matches!(event, InputEvent::Change) {
268 self.convert_typed(window, cx);
377 self.on_change(window, cx);
269 self.update_emoji(cx);
378 self.update_emoji(cx);
270 self.update_mention(cx);
379 self.update_mention(cx);
271 }
380 }
@@ -312,29 +421,216 @@ impl Composer {
312 self.lookup = None;
421 self.lookup = None;
313 }
422 }
314
423
315 fn convert_typed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
424 fn on_change(&mut self, window: &mut Window, cx: &mut Context<Self>) {
316 let state = self.input.read(cx);
425 let state = self.input.read(cx);
317 let (value, cursor) = (state.value().to_string(), state.cursor());
426 let (value, cursor) = (state.value().to_string(), state.cursor());
318 let previous = std::mem::replace(&mut self.previous_value, value.clone());
427 let previous = std::mem::replace(&mut self.previous_value, value.clone());
319 let found = match emoji::typed_char(&previous, &value, cursor) {
428 let replaying = std::mem::take(&mut self.replaying_history);
320 Some(':') => emoji::closing_code(&value, cursor)
429 if value == self.draft.text() {
430 self.refresh_style(cx);
431 return;
432 }
433 if replaying && let Some(snapshot) = self.snapshot_for(&value) {
434 self.draft = snapshot;
435 self.pending_style = None;
436 self.refresh_style(cx);
437 return;
438 }
439 let typing = self.pending_style.take();
440 let cursor = self.draft.apply_edit(&value, cursor, typing.as_ref());
441 self.commit(Some(cursor), window, cx);
442 if replaying {
443 return;
444 }
445 if let Some(pasted) = self.pasted_markdown.take()
446 && self.convert_paste(&pasted, cursor, window, cx)
447 {
448 return;
449 }
450 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
451 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
452 return;
453 }
454 self.convert_emoji(typed, cursor, window, cx);
455 }
456
457 fn convert_markdown(
458 &mut self,
459 cursor: usize,
460 window: &mut Window,
461 cx: &mut Context<Self>,
462 ) -> bool {
463 let before = self.draft.clone();
464 let Some((cursor, style)) = self.draft.convert_typed(cursor) else {
465 self.draft.take_edits();
466 return false;
467 };
468 self.finish_conversion(before, cursor, window, cx);
469 self.pending_style = (!style.is_empty()).then_some(style);
470 true
471 }
472
473 fn convert_emoji(
474 &mut self,
475 typed: Option<char>,
476 cursor: usize,
477 window: &mut Window,
478 cx: &mut Context<Self>,
479 ) {
480 let value = self.draft.text();
481 let found = match typed {
482 Some(':') => emoji::closing_code(value, cursor)
321 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
483 .and_then(|(range, code)| Some((range, emoji::lookup(code)?))),
322 Some(' ') => emoji::smiley_before_space(&value, cursor),
484 Some(' ') => emoji::smiley_before_space(value, cursor),
323 _ => None,
485 _ => None,
324 };
486 };
325 let Some((range, glyph)) = found else {
487 let Some((range, glyph)) = found else {
326 return;
488 return;
327 };
489 };
328 let original = value[range.clone()].to_owned();
490 let before = self.draft.clone();
329 let cursor = self.replace_text(range.clone(), glyph, cursor, window, cx);
491 self.draft.replace(range.clone(), glyph);
330 self.previous_value = self.input.read(cx).value().to_string();
492 self.finish_conversion(before, cursor + glyph.len() - range.len(), window, cx);
493 self.remember_emoji(glyph, cx);
494 }
495
496 fn finish_conversion(
497 &mut self,
498 before: Draft,
499 cursor: usize,
500 window: &mut Window,
501 cx: &mut Context<Self>,
502 ) {
503 let edits = self.draft.take_edits();
504 let restore = reverse_edits(&edits, before.text());
505 self.apply_to_input(edits, cursor..cursor, window, cx);
331 self.conversion = Some(Conversion {
506 self.conversion = Some(Conversion {
332 value: self.previous_value.clone(),
507 value: self.draft.text().to_owned(),
333 cursor,
508 cursor,
334 range: range.start..range.start + glyph.len(),
509 before,
335 original,
510 restore,
336 });
511 });
337 self.remember_emoji(glyph, cx);
512 }
513
514 fn convert_paste(
515 &mut self,
516 pasted: &str,
517 cursor: usize,
518 window: &mut Window,
519 cx: &mut Context<Self>,
520 ) -> bool {
521 let pasted = pasted.replace("\r\n", "\n");
522 let Some(start) = cursor
523 .checked_sub(pasted.len())
524 .filter(|start| self.draft.text().get(*start..cursor) == Some(pasted.as_str()))
525 else {
526 return false;
527 };
528 let lines = Draft::from_markdown(&pasted).slice(0..usize::MAX);
529 let cursor = self.draft.insert_lines(start..cursor, &lines);
530 self.commit(Some(cursor), window, cx);
531 self.paste_hint = Some(cx.spawn(async move |this, cx| {
532 cx.background_executor().timer(PASTE_HINT_DURATION).await;
533 this.update(cx, |this, cx| {
534 this.paste_hint = None;
535 cx.notify();
536 })
537 .ok();
538 }));
539 true
540 }
541
542 /// Puts the draft's pending edits into the input, then places the selection.
543 fn commit(&mut self, cursor: Option<usize>, window: &mut Window, cx: &mut Context<Self>) {
544 let edits = self.draft.take_edits();
545 let selection = self.input.read(cx).selected_range();
546 let selection = match cursor {
547 Some(cursor) => cursor..cursor,
548 None if edits.is_empty() => selection,
549 None => map_offset(&edits, selection.start)..map_offset(&edits, selection.end),
550 };
551 self.apply_to_input(edits, selection, window, cx);
552 }
553
554 fn apply_to_input(
555 &mut self,
556 edits: Vec<Edit>,
557 selection: Range<usize>,
558 window: &mut Window,
559 cx: &mut Context<Self>,
560 ) {
561 self.input.update(cx, |state, cx| {
562 let edited = !edits.is_empty();
563 if edited {
564 state.apply_edits(&edits, window, cx);
565 }
566 if edited || state.selected_range() != selection {
567 state.set_selected_range(selection.clone(), cx);
568 }
569 });
570 let value = self.input.read(cx).value().to_string();
571 if value != self.draft.text() {
572 self.draft.apply_edit(&value, selection.end, None);
573 self.draft.take_edits();
574 }
575 self.previous_value = value;
576 self.remember_snapshot();
577 self.refresh_style(cx);
578 }
579
580 fn remember_snapshot(&mut self) {
581 if self
582 .snapshots
583 .back()
584 .is_some_and(|last| last.text() == self.draft.text())
585 {
586 self.snapshots.pop_back();
587 }
588 self.snapshots.push_back(self.draft.clone());
589 if self.snapshots.len() > SNAPSHOT_LIMIT {
590 self.snapshots.pop_front();
591 }
592 }
593
594 fn snapshot_for(&self, value: &str) -> Option<Draft> {
595 self.snapshots
596 .iter()
597 .rev()
598 .find(|snapshot| snapshot.text() == value)
599 .cloned()
600 }
601
602 fn refresh_style(&mut self, cx: &mut Context<Self>) {
603 let style = draft_style(&self.draft, cx.theme().mono_font_family.clone());
604 let (text, ranges) = &self.decorations;
605 text.set(style.text, cx);
606 ranges.set(style.ranges, cx);
607 self.input
608 .update(cx, |state, cx| state.set_hanging_indents(style.markers, cx));
609 }
610
611 fn load_draft(
612 &mut self,
613 draft: Draft,
614 content: InputContent,
615 window: &mut Window,
616 cx: &mut Context<Self>,
617 ) {
618 let end = draft.text().len();
619 self.input.update(cx, |state, cx| {
620 state.set_value(content, window, cx);
621 state.set_selected_range(end..end, cx);
622 });
623 self.previous_value = draft.text().to_owned();
624 self.draft = draft;
625 self.pending_style = None;
626 self.conversion = None;
627 self.pasted_markdown = None;
628 self.paste_hint = None;
629 self.link_editor = None;
630 self.toolbar_dismissed = None;
631 self.snapshots.clear();
632 self.remember_snapshot();
633 self.refresh_style(cx);
338 }
634 }
339
635
340 /// Returns the cursor, kept at the same spot relative to the text after `range`.
636 /// Returns the cursor, kept at the same spot relative to the text after `range`.
@@ -363,18 +659,228 @@ impl Composer {
363 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
659 let Some(conversion) = self.conversion.take().filter(|_| unchanged) else {
364 return false;
660 return false;
365 };
661 };
366 self.replace_text(
662 let cursor = map_offset(&conversion.restore, conversion.cursor);
367 conversion.range,
663 self.draft = conversion.before;
368 &conversion.original,
664 self.pending_style = None;
369 conversion.cursor,
665 self.apply_to_input(conversion.restore, cursor..cursor, window, cx);
370 window,
371 cx,
372 );
373 self.undone_value = Some(self.input.read(cx).value().to_string());
666 self.undone_value = Some(self.input.read(cx).value().to_string());
374 self.update_emoji(cx);
667 self.update_emoji(cx);
375 true
668 true
376 }
669 }
377
670
671 fn selection(&self, cx: &App) -> Range<usize> {
672 self.input.read(cx).selected_range()
673 }
674
675 fn toggle_mark(&mut self, kind: MarkKind, cx: &mut Context<Self>) {
676 let selection = self.selection(cx);
677 if selection.is_empty() {
678 let cursor = selection.start;
679 let mut pending = self
680 .pending_style
681 .take()
682 .filter(|pending| pending.at == cursor)
683 .unwrap_or(TypingStyle {
684 at: cursor,
685 ..TypingStyle::default()
686 });
687 pending.toggle(kind, &self.draft.style_at(cursor));
688 self.pending_style = (!pending.is_empty()).then_some(pending);
689 } else {
690 self.draft.toggle(selection, kind);
691 self.draft.take_edits();
692 self.remember_snapshot();
693 self.refresh_style(cx);
694 }
695 cx.notify();
696 }
697
698 fn toggle_lines(&mut self, kind: LineKind, window: &mut Window, cx: &mut Context<Self>) {
699 let selection = self.selection(cx);
700 self.draft.toggle_lines(selection, kind);
701 self.commit(None, window, cx);
702 cx.notify();
703 }
704
705 fn press_format(&mut self, button: FormatButton, window: &mut Window, cx: &mut Context<Self>) {
706 match button {
707 FormatButton::Bold => self.toggle_mark(MarkKind::Bold, cx),
708 FormatButton::Italic => self.toggle_mark(MarkKind::Italic, cx),
709 FormatButton::Underline => self.toggle_mark(MarkKind::Underline, cx),
710 FormatButton::Strike => self.toggle_mark(MarkKind::Strike, cx),
711 FormatButton::Code => self.toggle_mark(MarkKind::Code, cx),
712 FormatButton::Link => self.open_link_editor(window, cx),
713 FormatButton::Bulleted => self.toggle_lines(LineKind::Bullet(0), window, cx),
714 FormatButton::Numbered => self.toggle_lines(LineKind::Numbered(0), window, cx),
715 FormatButton::Quote => self.toggle_lines(LineKind::Quote, window, cx),
716 }
717 }
718
719 fn format_state(&self, button: FormatButton, selection: &Range<usize>) -> FormatState {
720 let range = selection.clone();
721 match button {
722 FormatButton::Bold => self.draft.state(range, &MarkKind::Bold),
723 FormatButton::Italic => self.draft.state(range, &MarkKind::Italic),
724 FormatButton::Underline => self.draft.state(range, &MarkKind::Underline),
725 FormatButton::Strike => self.draft.state(range, &MarkKind::Strike),
726 FormatButton::Code => self.draft.state(range, &MarkKind::Code),
727 FormatButton::Link => self.draft.state(range, &MarkKind::Link(String::new())),
728 FormatButton::Bulleted => self.draft.line_state(range, &LineKind::Bullet(0)),
729 FormatButton::Numbered => self.draft.line_state(range, &LineKind::Numbered(0)),
730 FormatButton::Quote => self.draft.line_state(range, &LineKind::Quote),
731 }
732 }
733
734 fn edit_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
735 if self.link_editor.is_some() {
736 return;
737 }
738 if self.draft.is_blank() && self.selection(cx).is_empty() {
739 window.dispatch_action(Box::new(super::shell::OpenSwitcher), cx);
740 return;
741 }
742 self.open_link_editor(window, cx);
743 }
744
745 fn open_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
746 let range = self.selection(cx);
747 let prefill = self
748 .draft
749 .link_in(range.clone())
750 .or_else(|| {
751 cx.read_from_clipboard()
752 .and_then(|item| item.text())
753 .map(|text| text.trim().to_owned())
754 .filter(|text| looks_like_url(text))
755 })
756 .unwrap_or_default();
757 let field = cx.new(|cx| {
758 InputState::new(window, cx)
759 .placeholder("Paste or type a link")
760 .default_value(prefill)
761 });
762 field.update(cx, |state, cx| {
763 state.focus(window, cx);
764 state.select_all(window, cx);
765 });
766 self.link_editor = Some(LinkEditor { range, field });
767 cx.notify();
768 }
769
770 fn apply_link(&mut self, window: &mut Window, cx: &mut Context<Self>) {
771 let Some(editor) = self.link_editor.take() else {
772 return;
773 };
774 let url = normalized_url(&editor.field.read(cx).value());
775 self.focus(window, cx);
776 if editor.range.is_empty() {
777 if !url.is_empty() {
778 let end = self.draft.insert_link(editor.range.start, &url, &url);
779 self.commit(Some(end), window, cx);
780 }
781 } else {
782 self.draft.set_link(editor.range.clone(), &url);
783 self.draft.take_edits();
784 self.remember_snapshot();
785 self.refresh_style(cx);
786 self.input.update(cx, |state, cx| {
787 state.set_selected_range(editor.range.clone(), cx)
788 });
789 self.toolbar_dismissed = Some(editor.range);
790 }
791 cx.notify();
792 }
793
794 fn close_link_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
795 let Some(editor) = self.link_editor.take() else {
796 return;
797 };
798 self.focus(window, cx);
799 self.input
800 .update(cx, |state, cx| state.set_selected_range(editor.range, cx));
801 cx.notify();
802 }
803
804 fn break_line(&mut self, shift: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
805 let selection = self.selection(cx);
806 if !selection.is_empty() {
807 return false;
808 }
809 match self.draft.break_line(selection.start, shift) {
810 Some(cursor) => {
811 self.commit(Some(cursor), window, cx);
812 true
813 }
814 None => false,
815 }
816 }
817
818 fn backspace_at_start(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
819 let selection = self.selection(cx);
820 if !selection.is_empty() {
821 return false;
822 }
823 match self.draft.backspace_at_start(selection.start) {
824 Some(cursor) => {
825 self.commit(Some(cursor), window, cx);
826 true
827 }
828 None => false,
829 }
830 }
831
832 fn indent(&mut self, outdent: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {
833 let selection = self.selection(cx);
834 if !self.draft.indent(selection, outdent) {
835 return false;
836 }
837 self.commit(None, window, cx);
838 true
839 }
840
841 fn copy_selection(&mut self, cx: &mut Context<Self>) -> bool {
842 let selection = self.selection(cx);
843 let Some(text) = self.draft.text().get(selection.clone()).map(str::to_owned) else {
844 return false;
845 };
846 if text.is_empty() {
847 return false;
848 }
849 let lines = self.draft.slice(selection);
850 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
851 text.clone(),
852 lines.clone(),
853 ));
854 self.copied = Some((text, lines));
855 true
856 }
857
858 fn copied_lines(&self, item: &ClipboardItem, text: &str) -> Option<Vec<DraftLine>> {
859 item.entries()
860 .iter()
861 .find_map(|entry| match entry {
862 ClipboardEntry::String(string) if string.text() == text => {
863 string.metadata_json::<Vec<DraftLine>>()
864 }
865 _ => None,
866 })
867 .or_else(|| {
868 let normalized = text.replace("\r\n", "\n");
869 self.copied
870 .as_ref()
871 .filter(|(copied, _)| *copied == normalized)
872 .map(|(_, lines)| lines.clone())
873 })
874 }
875
876 fn toolbar_requested(&self, cx: &App) -> bool {
877 let selection = self.selection(cx);
878 !selection.is_empty()
879 && !self.mouse_selecting
880 && self.toolbar_dismissed.as_ref() != Some(&selection)
881 && !self.popup_is_open()
882 }
883
378 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
884 fn remember_emoji(&mut self, glyph: &str, cx: &App) {
379 self.recent_emoji.push(glyph);
885 self.recent_emoji.push(glyph);
380 self.recent_emoji.save(&self.app.read(cx).store);
886 self.recent_emoji.save(&self.app.read(cx).store);
@@ -543,8 +1049,7 @@ impl Composer {
543 self.discard_uploaded(dropped, cx);
1049 self.discard_uploaded(dropped, cx);
544 self.reply = None;
1050 self.reply = None;
545 if self.editing.take().is_some() {
1051 if self.editing.take().is_some() {
546 self.input
1052 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
547 .update(cx, |state, cx| state.set_value("", window, cx));
548 }
1053 }
549 self.mention_inputs.clear();
1054 self.mention_inputs.clear();
550 self.close_popup();
1055 self.close_popup();
@@ -581,15 +1086,16 @@ impl Composer {
581
1086
582 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
1087 fn outgoing(&self, cx: &App) -> Option<Outgoing> {
583 let state = self.input.read(cx);
1088 let state = self.input.read(cx);
584 let mut text = state.value().trim().to_owned();
585 if !self.can_send(cx) {
1089 if !self.can_send(cx) {
586 return None;
1090 return None;
587 }
1091 }
1092 let mut draft = self.current_draft(cx).trimmed();
588 let attachments_apply = self.editing.is_none();
1093 let attachments_apply = self.editing.is_none();
589 if self.undone_value.as_deref() != Some(state.value().as_ref())
1094 if self.undone_value.as_deref() != Some(state.value().as_ref())
590 && let Some((range, glyph)) = emoji::trailing_smiley(&text)
1095 && let Some((range, glyph)) = emoji::trailing_smiley(draft.text())
591 {
1096 {
592 text.replace_range(range, glyph);
1097 draft.replace(range, glyph);
1098 draft.take_edits();
593 }
1099 }
594 let mentions = state
1100 let mentions = state
595 .tokens()
1101 .tokens()
@@ -598,7 +1104,7 @@ impl Composer {
598 .cloned()
1104 .cloned()
599 .collect();
1105 .collect();
600 Some(Outgoing {
1106 Some(Outgoing {
601 text,
1107 draft,
602 mentions,
1108 mentions,
603 reply: self.reply.clone(),
1109 reply: self.reply.clone(),
604 edit: self.editing.clone(),
1110 edit: self.editing.clone(),
@@ -615,8 +1121,18 @@ impl Composer {
615 })
1121 })
616 }
1122 }
617
1123
1124 /// The draft, or the plain input text while a change is still on its way to the draft.
1125 fn current_draft(&self, cx: &App) -> Draft {
1126 let value = self.input.read(cx).value();
1127 if self.draft.text() == value.as_ref() {
1128 self.draft.clone()
1129 } else {
1130 Draft::plain(&value)
1131 }
1132 }
1133
618 fn can_send(&self, cx: &App) -> bool {
1134 fn can_send(&self, cx: &App) -> bool {
619 let has_text = !self.input.read(cx).value().trim().is_empty();
1135 let has_text = !self.current_draft(cx).is_blank();
620 if self.editing.is_some() {
1136 if self.editing.is_some() {
621 return has_text;
1137 return has_text;
622 }
1138 }
@@ -693,21 +1209,30 @@ impl Composer {
693 .detach();
1209 .detach();
694 }
1210 }
695
1211
696 fn paste(&mut self, item: &ClipboardItem, cx: &mut Context<Self>) -> bool {
1212 fn paste(&mut self, item: &ClipboardItem, window: &mut Window, cx: &mut Context<Self>) -> bool {
697 if self.editing.is_some() {
1213 if self.editing.is_none() {
698 return false;
1214 match paste_action(item) {
699 }
1215 PasteAction::Text => {}
700 match paste_action(item) {
1216 PasteAction::Files(paths) => {
701 PasteAction::Text => false,
1217 self.add_paths(paths, cx);
702 PasteAction::Files(paths) => {
1218 return true;
703 self.add_paths(paths, cx);
1219 }
704 true
1220 PasteAction::Image(pasted) => {
705 }
1221 self.add_pasted_image(pasted, cx);
706 PasteAction::Image(pasted) => {
1222 return true;
707 self.add_pasted_image(pasted, cx);
1223 }
708 true
709 }
1224 }
710 }
1225 }
1226 let Some(text) = item.text() else {
1227 return false;
1228 };
1229 if let Some(lines) = self.copied_lines(item, &text) {
1230 let cursor = self.draft.insert_lines(self.selection(cx), &lines);
1231 self.commit(Some(cursor), window, cx);
1232 return true;
1233 }
1234 self.pasted_markdown = has_markdown(&text).then_some(text);
1235 false
711 }
1236 }
712
1237
713 fn finish_reading(
1238 fn finish_reading(
@@ -878,8 +1403,7 @@ impl Composer {
878 let Some(outgoing) = self.outgoing(cx) else {
1403 let Some(outgoing) = self.outgoing(cx) else {
879 return;
1404 return;
880 };
1405 };
881 self.input
1406 self.load_draft(Draft::default(), InputContent::new(""), window, cx);
882 .update(cx, |state, cx| state.set_value("", window, cx));
883 self.mention_inputs.clear();
1407 self.mention_inputs.clear();
884 if self.editing.is_none() {
1408 if self.editing.is_none() {
885 self.tray.clear();
1409 self.tray.clear();
@@ -893,11 +1417,12 @@ impl Composer {
893
1417
894 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1418 pub fn restore(&mut self, outgoing: &Outgoing, window: &mut Window, cx: &mut Context<Self>) {
895 self.mention_inputs.clear();
1419 self.mention_inputs.clear();
896 let mut content = InputContent::new(outgoing.text.clone());
1420 let text = outgoing.draft.text();
1421 let mut content = InputContent::new(text.to_owned());
897 let mut cursor = 0;
1422 let mut cursor = 0;
898 for mention in &outgoing.mentions {
1423 for mention in &outgoing.mentions {
899 let needle = format!("@{}", mention.text);
1424 let needle = format!("@{}", mention.text);
900 let Some(offset) = outgoing.text[cursor..].find(&needle) else {
1425 let Some(offset) = text[cursor..].find(&needle) else {
901 continue;
1426 continue;
902 };
1427 };
903 let range = cursor + offset..cursor + offset + needle.len();
1428 let range = cursor + offset..cursor + offset + needle.len();
@@ -910,11 +1435,7 @@ impl Composer {
910 cursor = range.end;
1435 cursor = range.end;
911 }
1436 }
912 }
1437 }
913 let end = outgoing.text.len();
1438 self.load_draft(outgoing.draft.clone(), content, window, cx);
914 self.input.update(cx, |state, cx| {
915 state.set_value(content, window, cx);
916 state.set_selected_range(end..end, cx);
917 });
918 self.reply = outgoing.reply.clone();
1439 self.reply = outgoing.reply.clone();
919 self.editing = outgoing.edit.clone();
1440 self.editing = outgoing.edit.clone();
920 if outgoing.edit.is_none() {
1441 if outgoing.edit.is_none() {
@@ -925,21 +1446,19 @@ impl Composer {
925 cx.notify();
1446 cx.notify();
926 }
1447 }
927
1448
1449 /// Markdown in `text` arrives formatted.
928 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1450 pub fn set_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
929 let text = text.to_owned();
1451 let draft = Draft::from_markdown(text);
930 let end = text.len();
1452 let content = InputContent::new(draft.text().to_owned());
931 self.input.update(cx, |state, cx| {
1453 self.load_draft(draft, content, window, cx);
932 state.set_value(text, window, cx);
933 state.set_selected_range(end..end, cx);
934 });
935 self.mention_inputs.clear();
1454 self.mention_inputs.clear();
936 self.update_emoji(cx);
1455 self.update_emoji(cx);
937 self.update_mention(cx);
1456 self.update_mention(cx);
938 cx.notify();
1457 cx.notify();
939 }
1458 }
940
1459
941 pub fn is_empty(&self, cx: &App) -> bool {
1460 pub fn is_empty(&self, _: &App) -> bool {
942 self.input.read(cx).value().trim().is_empty() && self.tray.is_empty()
1461 self.draft.is_blank() && self.tray.is_empty()
943 }
1462 }
944
1463
945 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
1464 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
@@ -1059,6 +1578,91 @@ impl Composer {
1059 ))
1578 ))
1060 }
1579 }
1061
1580
1581 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
1582 let composer = cx.entity().downgrade();
1583 if self.link_editor.is_none() && !(focused && self.toolbar_requested(cx)) {
1584 return None;
1585 }
1586 let state = self.input.read(cx);
1587 let range = self
1588 .link_editor
1589 .as_ref()
1590 .map_or_else(|| state.selected_range(), |editor| editor.range.clone());
1591 let start = state.range_to_bounds(&(range.start..range.start))?;
1592 let end = state.range_to_bounds(&(range.end..range.end))?;
1593 let input_bounds = state.input_bounds();
1594 let center_x = if start.origin.y == end.origin.y {
1595 (start.origin.x + end.origin.x) / 2.
1596 } else {
1597 input_bounds.center().x
1598 };
1599 let edges = self
1600 .composer_bounds
1601 .get()
1602 .map_or((input_bounds.left(), input_bounds.right()), |bounds| {
1603 (bounds.left(), bounds.right())
1604 });
1605 let width = match self.link_editor {
1606 Some(_) => format_toolbar::link_width(),
1607 None => format_toolbar::bar_width(),
1608 };
1609 let placement = format_toolbar::place(center_x, start.origin.y, edges, width);
1610 let element = match &self.link_editor {
1611 Some(editor) => format_toolbar::render(
1612 placement,
1613 format_toolbar::Mode::Link {
1614 field: &editor.field,
1615 on_apply: Rc::new(move |window, cx| {
1616 composer
1617 .update(cx, |this, cx| this.apply_link(window, cx))
1618 .ok();
1619 }),
1620 },
1621 ),
1622 None => {
1623 let state_of = |button| self.format_state(button, &range);
1624 format_toolbar::render(
1625 placement,
1626 format_toolbar::Mode::Bar {
1627 state: &state_of,
1628 on_press: Rc::new(move |button, window, cx| {
1629 composer
1630 .update(cx, |this, cx| this.press_format(button, window, cx))
1631 .ok();
1632 }),
1633 },
1634 )
1635 }
1636 };
1637 Some(element)
1638 }
1639
1640 fn render_paste_hint(&self) -> Option<Div> {
1641 self.paste_hint.as_ref()?;
1642 Some(
1643 h_flex()
1644 .mt(px(6.))
1645 .gap(px(6.))
1646 .items_center()
1647 .text_size(px(12.))
1648 .text_color(theme::text_muted())
1649 .child("Formatted from Markdown")
1650 .child(
1651 div()
1652 .px(px(5.))
1653 .py(px(1.))
1654 .rounded(px(4.))
1655 .border_1()
1656 .border_color(theme::border_strong())
1657 .bg(theme::surface_raised())
1658 .text_size(px(11.))
1659 .text_color(theme::text())
1660 .child("Ctrl+Z"),
1661 )
1662 .child("plain text"),
1663 )
1664 }
1665
1062 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1666 fn render_edit_strip(&self, cx: &mut Context<Self>) -> Option<Div> {
1063 let edit = self.editing.as_ref()?;
1667 let edit = self.editing.as_ref()?;
1064 Some(
1668 Some(
@@ -1204,9 +1808,9 @@ impl Render for Composer {
1204 let input = Textarea::new(&self.input)
1808 let input = Textarea::new(&self.input)
1205 .appearance(false)
1809 .appearance(false)
1206 .bordered(false)
1810 .bordered(false)
1207 .on_paste(move |item, _, cx| {
1811 .on_paste(move |item, window, cx| {
1208 composer
1812 composer
1209 .update(cx, |this, cx| this.paste(item, cx))
1813 .update(cx, |this, cx| this.paste(item, window, cx))
1210 .unwrap_or(false)
1814 .unwrap_or(false)
1211 })
1815 })
1212 .token(|context, _, _| {
1816 .token(|context, _, _| {
@@ -1241,14 +1845,68 @@ impl Render for Composer {
1241 .text_color(theme::amber())
1845 .text_color(theme::amber())
1242 .child(notice.to_owned())
1846 .child(notice.to_owned())
1243 });
1847 });
1848 let composer_bounds = self.composer_bounds.clone();
1244 v_flex()
1849 v_flex()
1245 .w_full()
1850 .w_full()
1246 .flex_none()
1851 .flex_none()
1247 .px(px(24.))
1852 .px(px(24.))
1248 .pt(px(8.))
1853 .pt(px(8.))
1249 .pb(px(12.))
1854 .pb(px(12.))
1855 .key_context(KEY_CONTEXT)
1856 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
1857 if this.link_editor.is_none() {
1858 this.toggle_mark(MarkKind::Bold, cx);
1859 }
1860 }))
1861 .on_action(cx.listener(|this, _: &ToggleItalic, _, cx| {
1862 if this.link_editor.is_none() {
1863 this.toggle_mark(MarkKind::Italic, cx);
1864 }
1865 }))
1866 .on_action(cx.listener(|this, _: &ToggleUnderline, _, cx| {
1867 if this.link_editor.is_none() {
1868 this.toggle_mark(MarkKind::Underline, cx);
1869 }
1870 }))
1871 .on_action(cx.listener(|this, _: &ToggleStrike, _, cx| {
1872 if this.link_editor.is_none() {
1873 this.toggle_mark(MarkKind::Strike, cx);
1874 }
1875 }))
1876 .on_action(cx.listener(|this, _: &ToggleCode, _, cx| {
1877 if this.link_editor.is_none() {
1878 this.toggle_mark(MarkKind::Code, cx);
1879 }
1880 }))
1881 .on_action(cx.listener(|this, _: &EditLink, window, cx| this.edit_link(window, cx)))
1882 .capture_action(cx.listener(|this, _: &Undo, _, _| {
1883 if this.link_editor.is_none() {
1884 this.replaying_history = true;
1885 this.conversion = None;
1886 this.paste_hint = None;
1887 }
1888 }))
1889 .capture_action(cx.listener(|this, _: &Redo, _, _| {
1890 if this.link_editor.is_none() {
1891 this.replaying_history = true;
1892 this.conversion = None;
1893 }
1894 }))
1895 .capture_action(cx.listener(|this, _: &Copy, _, cx| {
1896 if this.link_editor.is_none() && this.copy_selection(cx) {
1897 cx.stop_propagation();
1898 }
1899 }))
1900 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
1901 if this.link_editor.is_none() && this.copy_selection(cx) {
1902 this.input
1903 .update(cx, |state, cx| state.replace("", window, cx));
1904 cx.stop_propagation();
1905 }
1906 }))
1250 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
1907 .capture_action(cx.listener(|this, _: &MoveUp, _, cx| {
1251 if this.popup_is_open() {
1908 if this.link_editor.is_some() {
1909 } else if this.popup_is_open() {
1252 this.move_highlight(-1, cx);
1910 this.move_highlight(-1, cx);
1253 cx.stop_propagation();
1911 cx.stop_propagation();
1254 } else if this.editing.is_none() && this.is_empty(cx) {
1912 } else if this.editing.is_none() && this.is_empty(cx) {
@@ -1257,29 +1915,55 @@ impl Render for Composer {
1257 }
1915 }
1258 }))
1916 }))
1259 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
1917 .capture_action(cx.listener(|this, _: &MoveDown, _, cx| {
1260 if this.popup_is_open() {
1918 if this.link_editor.is_none() && this.popup_is_open() {
1261 this.move_highlight(1, cx);
1919 this.move_highlight(1, cx);
1262 cx.stop_propagation();
1920 cx.stop_propagation();
1263 }
1921 }
1264 }))
1922 }))
1265 .capture_action(cx.listener(|this, _: &Enter, window, cx| {
1923 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
1266 if this.popup_is_open() {
1924 if this.link_editor.is_some() {
1925 this.apply_link(window, cx);
1926 cx.stop_propagation();
1927 } else if this.popup_is_open() {
1267 this.accept_popup(window, cx);
1928 this.accept_popup(window, cx);
1268 cx.stop_propagation();
1929 cx.stop_propagation();
1930 } else if this.break_line(action.shift, window, cx) {
1931 cx.stop_propagation();
1269 }
1932 }
1270 }))
1933 }))
1271 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
1934 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
1272 if this.popup_is_open() {
1935 if this.link_editor.is_some() {
1936 } else if this.popup_is_open() {
1273 this.accept_popup(window, cx);
1937 this.accept_popup(window, cx);
1274 cx.stop_propagation();
1938 cx.stop_propagation();
1939 } else if this.indent(false, window, cx) {
1940 cx.stop_propagation();
1941 }
1942 }))
1943 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
1944 if this.link_editor.is_none() && this.indent(true, window, cx) {
1945 cx.stop_propagation();
1275 }
1946 }
1276 }))
1947 }))
1277 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
1948 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
1278 if this.undo_conversion(window, cx) {
1949 if this.link_editor.is_none()
1950 && (this.undo_conversion(window, cx) || this.backspace_at_start(window, cx))
1951 {
1279 cx.stop_propagation();
1952 cx.stop_propagation();
1280 }
1953 }
1281 }))
1954 }))
1282 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
1955 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
1956 if this.link_editor.is_some() {
1957 this.close_link_editor(window, cx);
1958 cx.stop_propagation();
1959 return;
1960 }
1961 if this.toolbar_requested(cx) {
1962 this.toolbar_dismissed = Some(this.selection(cx));
1963 cx.notify();
1964 cx.stop_propagation();
1965 return;
1966 }
1283 if let Some(popup) = &this.emoji_popup {
1967 if let Some(popup) = &this.emoji_popup {
1284 this.emoji_dismissed_at = Some(popup.range.start);
1968 this.emoji_dismissed_at = Some(popup.range.start);
1285 }
1969 }
@@ -1301,8 +1985,10 @@ impl Render for Composer {
1301 .w_full()
1985 .w_full()
1302 .children(self.render_popup(cx))
1986 .children(self.render_popup(cx))
1303 .children(self.render_emoji_popup(window, cx))
1987 .children(self.render_emoji_popup(window, cx))
1988 .children(self.render_toolbar(focused, cx))
1304 .child(
1989 .child(
1305 v_flex()
1990 v_flex()
1991 .relative()
1306 .w_full()
1992 .w_full()
1307 .rounded(px(10.))
1993 .rounded(px(10.))
1308 .bg(theme::surface())
1994 .bg(theme::surface())
@@ -1312,6 +1998,14 @@ impl Render for Composer {
1312 } else {
1998 } else {
1313 theme::border_strong()
1999 theme::border_strong()
1314 })
2000 })
2001 .child(
2002 canvas(
2003 move |bounds, _, _| composer_bounds.set(Some(bounds)),
2004 |_, _, _, _| {},
2005 )
2006 .absolute()
2007 .size_full(),
2008 )
1315 .children(tray)
2009 .children(tray)
1316 .child(
2010 .child(
1317 h_flex()
2011 h_flex()
@@ -1322,11 +2016,37 @@ impl Render for Composer {
1322 .pl(px(if can_attach { 6. } else { 12. }))
2016 .pl(px(if can_attach { 6. } else { 12. }))
1323 .pr(px(6.))
2017 .pr(px(6.))
1324 .children(attach)
2018 .children(attach)
1325 .child(div().flex_1().min_w_0().child(input))
2019 .child(
2020 div()
2021 .flex_1()
2022 .min_w_0()
2023 .capture_any_mouse_down(cx.listener(
2024 |this, _: &MouseDownEvent, _, _| {
2025 this.mouse_selecting = true;
2026 this.toolbar_dismissed = None;
2027 this.link_editor = None;
2028 },
2029 ))
2030 .capture_any_mouse_up(cx.listener(
2031 |this, _: &MouseUpEvent, _, cx| {
2032 this.mouse_selecting = false;
2033 cx.notify();
2034 },
2035 ))
2036 .on_mouse_up_out(
2037 MouseButton::Left,
2038 cx.listener(|this, _, _, cx| {
2039 this.mouse_selecting = false;
2040 cx.notify();
2041 }),
2042 )
2043 .child(input),
2044 )
1326 .child(send),
2045 .child(send),
1327 ),
2046 ),
1328 ),
2047 ),
1329 )
2048 )
2049 .children(self.render_paste_hint())
1330 }
2050 }
1331}
2051}
1332
2052
@@ -1410,7 +2130,7 @@ mod tests {
1410 use super::{Outgoing, OutgoingFile, OutgoingImage};
2130 use super::{Outgoing, OutgoingFile, OutgoingImage};
1411
2131
1412 let outgoing = Outgoing {
2132 let outgoing = Outgoing {
1413 text: String::new(),
2133 draft: teams_core::Draft::default(),
1414 mentions: Vec::new(),
2134 mentions: Vec::new(),
1415 reply: None,
2135 reply: None,
1416 edit: None,
2136 edit: None,
@@ -1486,6 +2206,220 @@ mod tests {
1486 assert_eq!(value, "X");
2206 assert_eq!(value, "X");
1487 }
2207 }
1488
2208
2209 struct Typist<'a> {
2210 cx: &'a mut TestAppContext,
2211 handle: gpui_kit::AnyWindowHandle,
2212 composer: gpui_kit::Entity<Composer>,
2213 }
2214
2215 impl Typist<'_> {
2216 fn act(&mut self, action: impl FnOnce(&mut gpui_kit::Window, &mut gpui_kit::App)) {
2217 self.cx
2218 .update_window(self.handle, |_, window, cx| action(window, cx))
2219 .unwrap();
2220 self.cx.run_until_parked();
2221 }
2222
2223 fn type_text(&mut self, text: &str) {
2224 for character in text.chars() {
2225 self.act(|window, cx| window.input(&character.to_string(), cx));
2226 }
2227 }
2228
2229 fn press(&mut self, keys: &str) {
2230 for key in keys.split(' ') {
2231 self.act(|window, cx| window.press(key, cx));
2232 }
2233 }
2234
2235 fn value(&mut self) -> String {
2236 let composer = self.composer.clone();
2237 self.cx
2238 .update(|cx| composer.read(cx).input.read(cx).value().to_string())
2239 }
2240
2241 fn draft(&mut self) -> teams_core::Draft {
2242 let composer = self.composer.clone();
2243 self.cx.update(|cx| composer.read(cx).draft.clone())
2244 }
2245
2246 fn outgoing(&mut self) -> super::super::Outgoing {
2247 let composer = self.composer.clone();
2248 self.cx
2249 .update(|cx| composer.read(cx).outgoing(cx))
2250 .expect("text to send")
2251 }
2252 }
2253
2254 fn typist(cx: &mut TestAppContext) -> Typist<'_> {
2255 let (handle, composer) = demo_composer(cx);
2256 cx.update(super::super::bind_keys);
2257 let mut typist = Typist {
2258 cx,
2259 handle,
2260 composer: composer.clone(),
2261 };
2262 typist.act(|window, cx| {
2263 composer.update(cx, |composer, cx| composer.focus(window, cx));
2264 window.render_frame(cx);
2265 });
2266 typist
2267 }
2268
2269 #[gpui_kit::test]
2270 fn typed_markdown_is_formatted_and_backspace_brings_it_back(cx: &mut TestAppContext) {
2271 use teams_core::{FormatState, MarkKind};
2272
2273 let mut typist = typist(cx);
2274 typist.type_text("a **bold**");
2275 assert_eq!(typist.value(), "a bold");
2276 assert_eq!(typist.draft().state(2..6, &MarkKind::Bold), FormatState::On);
2277 typist.press("backspace");
2278 assert_eq!(typist.value(), "a **bold**");
2279 assert!(typist.draft().marks().is_empty());
2280 let composer = typist.composer.clone();
2281 assert_eq!(
2282 typist
2283 .cx
2284 .update(|cx| composer.read(cx).input.read(cx).cursor()),
2285 10
2286 );
2287 typist.press("backspace");
2288 typist.type_text("* x");
2289 assert_eq!(typist.value(), "a bold x");
2290 assert_eq!(
2291 typist.draft().state(6..8, &MarkKind::Bold),
2292 FormatState::Off
2293 );
2294 }
2295
2296 #[gpui_kit::test]
2297 fn enter_continues_a_list_instead_of_sending(cx: &mut TestAppContext) {
2298 let mut typist = typist(cx);
2299 typist.type_text("1. one");
2300 typist.press("enter");
2301 typist.type_text("two");
2302 assert_eq!(typist.value(), "1. one\n2. two");
2303 typist.press("enter enter");
2304 assert_eq!(typist.value(), "1. one\n2. two\n");
2305 typist.type_text("after");
2306 typist.press("enter");
2307 assert_eq!(typist.value(), "");
2308 }
2309
2310 #[gpui_kit::test]
2311 fn tab_nests_a_list_item(cx: &mut TestAppContext) {
2312 let mut typist = typist(cx);
2313 typist.type_text("- a");
2314 typist.press("enter tab");
2315 typist.type_text("b");
2316 assert_eq!(typist.value(), "• a\n\u{2003}\u{2003}◦ b");
2317 typist.press("shift-tab");
2318 assert_eq!(typist.value(), "• a\n• b");
2319 }
2320
2321 #[gpui_kit::test]
2322 fn ctrl_b_toggles_bold_on_a_selection_and_for_the_next_text(cx: &mut TestAppContext) {
2323 use teams_core::{FormatState, MarkKind};
2324
2325 let mut typist = typist(cx);
2326 typist.type_text("hello");
2327 typist.press("shift-left shift-left ctrl-b");
2328 assert_eq!(typist.draft().state(3..5, &MarkKind::Bold), FormatState::On);
2329 assert_eq!(
2330 typist.draft().state(0..5, &MarkKind::Bold),
2331 FormatState::Mixed
2332 );
2333 typist.press("ctrl-b");
2334 assert!(typist.draft().marks().is_empty());
2335 typist.press("end ctrl-i");
2336 typist.type_text("!");
2337 assert_eq!(typist.outgoing().html(), "hello<i>!</i>");
2338 }
2339
2340 #[gpui_kit::test]
2341 fn pasted_markdown_converts_and_ctrl_z_restores_the_raw_text(cx: &mut TestAppContext) {
2342 let mut typist = typist(cx);
2343 typist
2344 .cx
2345 .write_to_clipboard(gpui_kit::ClipboardItem::new_string(
2346 "**hi** there".to_owned(),
2347 ));
2348 typist.press("ctrl-v");
2349 assert_eq!(typist.value(), "hi there");
2350 let composer = typist.composer.clone();
2351 assert!(
2352 typist
2353 .cx
2354 .update(|cx| composer.read(cx).paste_hint.is_some())
2355 );
2356 typist.press("ctrl-z");
2357 assert_eq!(typist.value(), "**hi** there");
2358 assert!(typist.draft().marks().is_empty());
2359 }
2360
2361 #[gpui_kit::test]
2362 fn copy_and_paste_inside_the_composer_keeps_formatting(cx: &mut TestAppContext) {
2363 use teams_core::{FormatState, MarkKind};
2364
2365 let mut typist = typist(cx);
2366 typist.type_text("`code` ");
2367 typist.press("ctrl-a ctrl-c end ctrl-v");
2368 assert_eq!(typist.value(), "code code ");
2369 assert_eq!(typist.draft().state(5..9, &MarkKind::Code), FormatState::On);
2370 }
2371
2372 #[gpui_kit::test]
2373 fn undo_brings_the_formatting_back_with_the_text(cx: &mut TestAppContext) {
2374 use teams_core::{FormatState, MarkKind};
2375
2376 let mut typist = typist(cx);
2377 typist.type_text("~~old~~");
2378 typist.press("ctrl-a");
2379 typist.type_text("new");
2380 typist.press("ctrl-z ctrl-z");
2381 assert_eq!(typist.value(), "old");
2382 assert_eq!(
2383 typist.draft().state(0..3, &MarkKind::Strike),
2384 FormatState::On
2385 );
2386 }
2387
2388 #[gpui_kit::test]
2389 fn ctrl_k_turns_the_selection_into_a_link(cx: &mut TestAppContext) {
2390 let mut typist = typist(cx);
2391 typist.type_text("see docs");
2392 typist.press("shift-left shift-left shift-left shift-left ctrl-k");
2393 let composer = typist.composer.clone();
2394 assert!(
2395 typist
2396 .cx
2397 .update(|cx| composer.read(cx).link_editor.is_some())
2398 );
2399 typist.type_text("example.com");
2400 typist.press("enter");
2401 assert!(
2402 typist
2403 .cx
2404 .update(|cx| composer.read(cx).link_editor.is_none())
2405 );
2406 assert_eq!(
2407 typist.outgoing().html(),
2408 "see <a href=\"https://example.com\">docs</a>"
2409 );
2410 }
2411
2412 #[gpui_kit::test]
2413 fn quotes_continue_on_shift_enter_and_send_as_blockquote(cx: &mut TestAppContext) {
2414 let mut typist = typist(cx);
2415 typist.type_text("> quoted");
2416 typist.press("shift-enter");
2417 typist.type_text("more");
2418 let outgoing = typist.outgoing();
2419 assert_eq!(outgoing.html(), "<blockquote>quoted<br>more</blockquote>");
2420 assert_eq!(outgoing.text(), "quoted\nmore");
2421 }
2422
1489 #[gpui_kit::test]
2423 #[gpui_kit::test]
1490 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
2424 fn demo_upload_runs_to_done_and_a_file_alone_can_be_sent(cx: &mut TestAppContext) {
1491 cx.update(gpui_kit::init);
2425 cx.update(gpui_kit::init);
@@ -1527,7 +2461,7 @@ mod tests {
1527 let outgoing = composer
2461 let outgoing = composer
1528 .outgoing(cx)
2462 .outgoing(cx)
1529 .expect("an attachment alone is a message");
2463 .expect("an attachment alone is a message");
1530 assert_eq!(outgoing.text, "");
2464 assert_eq!(outgoing.text(), "");
1531 assert_eq!(outgoing.files.len(), 1);
2465 assert_eq!(outgoing.files.len(), 1);
1532 assert_eq!(outgoing.files[0].name, "plan.pdf");
2466 assert_eq!(outgoing.files[0].name, "plan.pdf");
1533 });
2467 });
@@ -1617,7 +2551,7 @@ mod tests {
1617 cx.update_window(handle, |_, window, cx| {
2551 cx.update_window(handle, |_, window, cx| {
1618 composer.update(cx, |composer, cx| {
2552 composer.update(cx, |composer, cx| {
1619 let draft = Outgoing {
2553 let draft = Outgoing {
1620 text: "old".into(),
2554 draft: teams_core::Draft::plain("old"),
1621 mentions: Vec::new(),
2555 mentions: Vec::new(),
1622 reply: None,
2556 reply: None,
1623 edit: Some(EditPreview {
2557 edit: Some(EditPreview {
@@ -1636,7 +2570,7 @@ mod tests {
1636 assert_eq!(composer.tray.items().len(), 1);
2570 assert_eq!(composer.tray.items().len(), 1);
1637 let outgoing = composer.outgoing(cx).unwrap();
2571 let outgoing = composer.outgoing(cx).unwrap();
1638 assert!(outgoing.files.is_empty());
2572 assert!(outgoing.files.is_empty());
1639 assert_eq!(outgoing.text, "old");
2573 assert_eq!(outgoing.text(), "old");
1640 });
2574 });
1641 cx.update_window(handle, |_, window, cx| {
2575 cx.update_window(handle, |_, window, cx| {
1642 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
2576 composer.update(cx, |composer, cx| composer.cancel_edit(window, cx));
crates/app/src/views/conversation.rs +23 −18
@@ -33,13 +33,12 @@ use crate::data::{is_one_on_one, others};
33 33 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34 34 use crate::reaction_model::UNKNOWN_REACTOR;
35 35 use crate::read_state::{ReadTrigger, plan_read};
36 use crate::render::Block;
37 use crate::render::blocks::Inline;
36 use crate::render::layout_blocks;
38 37 use crate::rows::{
39 38 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
40 assign_series, changed_indices, diff_keys, flat_rows, message_text, placeholder_rows,
41 reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows, thread_rows,
42 trailing_skeleton,
39 assign_series, changed_indices, diff_keys, flat_rows, message_draft, message_text,
40 placeholder_rows, reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows,
41 thread_rows, trailing_skeleton,
43 42 };
44 43 use crate::runtime;
45 44 use crate::sidebar_model::{AvatarSpec, Face};
@@ -1520,11 +1519,10 @@ impl ConversationView {
1520 1519 let sent = outgoing.clone();
1521 1520 let receiver = runtime::spawn(async move {
1522 1521 let extras = sent.extras();
1522 let html = sent.html();
1523 let text = &html;
1523 1524 let Outgoing {
1524 text,
1525 mentions,
1526 reply,
1527 ..
1525 mentions, reply, ..
1528 1526 } = &sent;
1529 1527 match (&view_mode, reply) {
1530 1528 (_, Some(reply)) => {
@@ -1603,10 +1601,10 @@ impl ConversationView {
1603 1601 card: false,
1604 1602 time: chrono::Local::now().format("%H:%M").to_string(),
1605 1603 day_header: None,
1606 blocks: if outgoing.text.is_empty() {
1604 blocks: if outgoing.draft.is_blank() {
1607 1605 Vec::new()
1608 1606 } else {
1609 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1607 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
1610 1608 },
1611 1609 edited: false,
1612 1610 deleted: false,
@@ -1713,7 +1711,7 @@ impl ConversationView {
1713 1711 let sent = engine
1714 1712 .send_message_with_extras(
1715 1713 &chat_id,
1716 &outgoing.text,
1714 &outgoing.html(),
1717 1715 None,
1718 1716 &outgoing.mentions,
1719 1717 &outgoing.extras(),
@@ -1787,9 +1785,16 @@ impl ConversationView {
1787 1785 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1788 1786 return;
1789 1787 };
1790 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1788 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
1791 1789 }
1792 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1790 None => crate::demo::new_chat(
1791 &chats,
1792 &people,
1793 topic,
1794 &outgoing.text(),
1795 &outgoing.html(),
1796 Utc::now(),
1797 ),
1793 1798 };
1794 1799 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1795 1800 let _ = store.upsert_messages(std::slice::from_ref(&message));
@@ -1930,7 +1935,7 @@ impl ConversationView {
1930 1935 Vec::new()
1931 1936 };
1932 1937 let draft = Outgoing {
1933 text: message_text(&record),
1938 draft: message_draft(&record),
1934 1939 mentions,
1935 1940 reply: None,
1936 1941 edit: Some(edit),
@@ -1971,7 +1976,7 @@ impl ConversationView {
1971 1976 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1972 1977 if mode.demo {
1973 1978 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1974 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1979 record.body_html = outgoing.html();
1975 1980 record.edited_at = Some(Utc::now());
1976 1981 let _ = store.upsert_messages(std::slice::from_ref(&record));
1977 1982 self.rebuild(false, cx);
@@ -1988,10 +1993,10 @@ impl ConversationView {
1988 1993 let sent = outgoing.clone();
1989 1994 let receiver = runtime::spawn(async move {
1990 1995 engine
1991 .edit_message_with_mentions(
1996 .edit_message_html(
1992 1997 &conversation_id,
1993 1998 &edit.message_id,
1994 &sent.text,
1999 &sent.html(),
1995 2000 &sent.mentions,
1996 2001 )
1997 2002 .await
@@ -33,13 +33,12 @@ use crate::data::{is_one_on_one, others};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
33use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
34use crate::reaction_model::UNKNOWN_REACTOR;
34use crate::reaction_model::UNKNOWN_REACTOR;
35use crate::read_state::{ReadTrigger, plan_read};
35use crate::read_state::{ReadTrigger, plan_read};
36use crate::render::Block;
36use crate::render::layout_blocks;
37use crate::render::blocks::Inline;
38use crate::rows::{
37use crate::rows::{
39 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
38 Delivery, LocalImage, MessageRow, Receipt, Row, RowContext, Series, StartInfo, api_reaction,
40 assign_series, changed_indices, diff_keys, flat_rows, message_text, placeholder_rows,
39 assign_series, changed_indices, diff_keys, flat_rows, message_draft, message_text,
41 reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows, thread_rows,
40 placeholder_rows, reaction_glyph, reaction_type_for, reply_excerpt, thread_list_rows,
42 trailing_skeleton,
41 thread_rows, trailing_skeleton,
43};
42};
44use crate::runtime;
43use crate::runtime;
45use crate::sidebar_model::{AvatarSpec, Face};
44use crate::sidebar_model::{AvatarSpec, Face};
@@ -1520,11 +1519,10 @@ impl ConversationView {
1520 let sent = outgoing.clone();
1519 let sent = outgoing.clone();
1521 let receiver = runtime::spawn(async move {
1520 let receiver = runtime::spawn(async move {
1522 let extras = sent.extras();
1521 let extras = sent.extras();
1522 let html = sent.html();
1523 let text = &html;
1523 let Outgoing {
1524 let Outgoing {
1524 text,
1525 mentions, reply, ..
1525 mentions,
1526 reply,
1527 ..
1528 } = &sent;
1526 } = &sent;
1529 match (&view_mode, reply) {
1527 match (&view_mode, reply) {
1530 (_, Some(reply)) => {
1528 (_, Some(reply)) => {
@@ -1603,10 +1601,10 @@ impl ConversationView {
1603 card: false,
1601 card: false,
1604 time: chrono::Local::now().format("%H:%M").to_string(),
1602 time: chrono::Local::now().format("%H:%M").to_string(),
1605 day_header: None,
1603 day_header: None,
1606 blocks: if outgoing.text.is_empty() {
1604 blocks: if outgoing.draft.is_blank() {
1607 Vec::new()
1605 Vec::new()
1608 } else {
1606 } else {
1609 vec![Block::Paragraph(Inline::plain(&outgoing.text))]
1607 layout_blocks(&teams_core::html_to_spans(&outgoing.html()))
1610 },
1608 },
1611 edited: false,
1609 edited: false,
1612 deleted: false,
1610 deleted: false,
@@ -1713,7 +1711,7 @@ impl ConversationView {
1713 let sent = engine
1711 let sent = engine
1714 .send_message_with_extras(
1712 .send_message_with_extras(
1715 &chat_id,
1713 &chat_id,
1716 &outgoing.text,
1714 &outgoing.html(),
1717 None,
1715 None,
1718 &outgoing.mentions,
1716 &outgoing.mentions,
1719 &outgoing.extras(),
1717 &outgoing.extras(),
@@ -1787,9 +1785,16 @@ impl ConversationView {
1787 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1785 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
1788 return;
1786 return;
1789 };
1787 };
1790 crate::demo::send_in_chat(chat, &outgoing.text, Utc::now())
1788 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
1791 }
1789 }
1792 None => crate::demo::new_chat(&chats, &people, topic, &outgoing.text, Utc::now()),
1790 None => crate::demo::new_chat(
1791 &chats,
1792 &people,
1793 topic,
1794 &outgoing.text(),
1795 &outgoing.html(),
1796 Utc::now(),
1797 ),
1793 };
1798 };
1794 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1799 let _ = store.upsert_chats(std::slice::from_ref(&chat));
1795 let _ = store.upsert_messages(std::slice::from_ref(&message));
1800 let _ = store.upsert_messages(std::slice::from_ref(&message));
@@ -1930,7 +1935,7 @@ impl ConversationView {
1930 Vec::new()
1935 Vec::new()
1931 };
1936 };
1932 let draft = Outgoing {
1937 let draft = Outgoing {
1933 text: message_text(&record),
1938 draft: message_draft(&record),
1934 mentions,
1939 mentions,
1935 reply: None,
1940 reply: None,
1936 edit: Some(edit),
1941 edit: Some(edit),
@@ -1971,7 +1976,7 @@ impl ConversationView {
1971 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1976 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
1972 if mode.demo {
1977 if mode.demo {
1973 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1978 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
1974 record.body_html = teams_core::markdown_to_html(&outgoing.text);
1979 record.body_html = outgoing.html();
1975 record.edited_at = Some(Utc::now());
1980 record.edited_at = Some(Utc::now());
1976 let _ = store.upsert_messages(std::slice::from_ref(&record));
1981 let _ = store.upsert_messages(std::slice::from_ref(&record));
1977 self.rebuild(false, cx);
1982 self.rebuild(false, cx);
@@ -1988,10 +1993,10 @@ impl ConversationView {
1988 let sent = outgoing.clone();
1993 let sent = outgoing.clone();
1989 let receiver = runtime::spawn(async move {
1994 let receiver = runtime::spawn(async move {
1990 engine
1995 engine
1991 .edit_message_with_mentions(
1996 .edit_message_html(
1992 &conversation_id,
1997 &conversation_id,
1993 &edit.message_id,
1998 &edit.message_id,
1994 &sent.text,
1999 &sent.html(),
1995 &sent.mentions,
2000 &sent.mentions,
1996 )
2001 )
1997 .await
2002 .await
crates/app/src/views/draft_style.rs added +189 −0
@@ -0,0 +1,189 @@
1 use std::ops::Range;
2
3 use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
4 use gpui_kit::*;
5 use teams_core::{Draft, LineKind, MarkKind};
6
7 use crate::theme;
8
9 const CODE_PILL_RADIUS: f32 = 4.;
10 const CODE_BLOCK_RADIUS: f32 = 6.;
11 const QUOTE_BAR_WIDTH: f32 = 3.;
12
13 /// How the composer paints a draft: text styles, fills and the list markers to hang under.
14 pub struct DraftStyle {
15 pub text: Vec<TextDecoration>,
16 pub ranges: Vec<RangeDecoration>,
17 pub markers: Vec<Range<usize>>,
18 }
19
20 fn color(color: Hsla) -> HighlightStyle {
21 HighlightStyle {
22 color: Some(color),
23 ..Default::default()
24 }
25 }
26
27 fn underline(color: Option<Hsla>) -> UnderlineStyle {
28 UnderlineStyle {
29 thickness: px(1.),
30 color,
31 wavy: false,
32 }
33 }
34
35 fn mark_style(kind: &MarkKind) -> HighlightStyle {
36 let mut style = HighlightStyle::default();
37 match kind {
38 MarkKind::Bold => style.font_weight = Some(FontWeight::BOLD),
39 MarkKind::Italic => style.font_style = Some(FontStyle::Italic),
40 MarkKind::Underline => style.underline = Some(underline(None)),
41 MarkKind::Strike => {
42 style.color = Some(theme::text_muted());
43 style.strikethrough = Some(StrikethroughStyle {
44 thickness: px(1.),
45 color: None,
46 });
47 }
48 MarkKind::Code => style.color = Some(theme::text_strong()),
49 MarkKind::Link(_) => {
50 style.color = Some(theme::accent_text());
51 style.underline = Some(underline(Some(theme::accent_text())));
52 }
53 }
54 style
55 }
56
57 /// A range the block or bar decoration paints over every line of `lines`; `None` when the
58 /// block is one empty line it cannot address yet.
59 fn block_range(draft: &Draft, lines: Range<usize>) -> Option<Range<usize>> {
60 let line_ranges = draft.line_ranges();
61 let start = line_ranges[lines.start].start;
62 let end = line_ranges[lines.end - 1].end;
63 if end > start {
64 return Some(start..end);
65 }
66 if end < draft.text().len() {
67 return Some(start..start + 1);
68 }
69 let previous_has_text = lines.start > 0 && !line_ranges[lines.start - 1].is_empty();
70 previous_has_text.then(|| start - 1..start)
71 }
72
73 pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
74 let mut text = Vec::new();
75 let mut ranges = Vec::new();
76 let mut markers = Vec::new();
77 for mark in draft.marks() {
78 let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
79 if mark.kind == MarkKind::Code {
80 text.push(decoration.with_font_family(mono.clone()));
81 ranges.push(
82 RangeDecoration::new(mark.range.clone())
83 .with_style(RangeDecorationStyle::Pill)
84 .with_color(theme::inline_code_fill(false))
85 .with_border(theme::inline_code_border())
86 .with_radius(px(CODE_PILL_RADIUS)),
87 );
88 } else {
89 text.push(decoration);
90 }
91 }
92 let kinds = draft.lines();
93 let mut index = 0;
94 while index < kinds.len() {
95 let kind = &kinds[index];
96 let run_end = index
97 + kinds[index..]
98 .iter()
99 .take_while(|other| *other == kind)
100 .count();
101 for line in index..run_end {
102 let marker = draft.marker_range(line);
103 let content = draft.content_range(line);
104 if !marker.is_empty() {
105 markers.push(marker.clone());
106 if kind.is_list() {
107 text.push(TextDecoration::new(marker, color(theme::text_soft())));
108 }
109 }
110 if content.is_empty() {
111 continue;
112 }
113 match kind {
114 LineKind::Quote => {
115 text.push(TextDecoration::new(content, color(theme::text_soft())))
116 }
117 LineKind::Code(_) => text.push(
118 TextDecoration::new(content, color(theme::text_strong()))
119 .with_font_family(mono.clone()),
120 ),
121 _ => {}
122 }
123 }
124 let block = match kind {
125 LineKind::Code(_) => block_range(draft, index..run_end).map(|range| {
126 RangeDecoration::new(range)
127 .with_style(RangeDecorationStyle::Block)
128 .with_color(theme::code_surface())
129 .with_radius(px(CODE_BLOCK_RADIUS))
130 }),
131 LineKind::Quote => block_range(draft, index..run_end).map(|range| {
132 RangeDecoration::new(range)
133 .with_style(RangeDecorationStyle::Bar)
134 .with_color(theme::border_strong())
135 .with_radius(px(QUOTE_BAR_WIDTH))
136 }),
137 _ => None,
138 };
139 ranges.extend(block);
140 index = run_end;
141 }
142 DraftStyle {
143 text,
144 ranges,
145 markers,
146 }
147 }
148
149 #[cfg(test)]
150 mod tests {
151 use gpui_kit::component::input::RangeDecorationStyle;
152 use teams_core::{Draft, DraftLine, LineKind};
153
154 use super::{block_range, draft_style};
155
156 #[test]
157 fn list_markers_hang_and_code_gets_a_pill() {
158 let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");
159 let style = draft_style(&draft, "Mono".into());
160 assert_eq!(style.markers, [draft.marker_range(0)]);
161 assert_eq!(
162 style
163 .ranges
164 .iter()
165 .map(|range| range.style())
166 .collect::<Vec<_>>(),
167 [RangeDecorationStyle::Pill, RangeDecorationStyle::Block]
168 );
169 }
170
171 #[test]
172 fn an_empty_code_line_at_the_end_still_gets_its_block() {
173 let draft = Draft::from_lines(&[
174 DraftLine {
175 kind: LineKind::Text,
176 number: None,
177 content: "intro".into(),
178 marks: Vec::new(),
179 },
180 DraftLine {
181 kind: LineKind::Code(None),
182 number: None,
183 content: String::new(),
184 marks: Vec::new(),
185 },
186 ]);
187 assert_eq!(block_range(&draft, 1..2), Some(5..6));
188 }
189 }
@@ -0,0 +1,189 @@
1use std::ops::Range;
2
3use gpui_kit::component::input::{RangeDecoration, RangeDecorationStyle, TextDecoration};
4use gpui_kit::*;
5use teams_core::{Draft, LineKind, MarkKind};
6
7use crate::theme;
8
9const CODE_PILL_RADIUS: f32 = 4.;
10const CODE_BLOCK_RADIUS: f32 = 6.;
11const QUOTE_BAR_WIDTH: f32 = 3.;
12
13/// How the composer paints a draft: text styles, fills and the list markers to hang under.
14pub struct DraftStyle {
15 pub text: Vec<TextDecoration>,
16 pub ranges: Vec<RangeDecoration>,
17 pub markers: Vec<Range<usize>>,
18}
19
20fn color(color: Hsla) -> HighlightStyle {
21 HighlightStyle {
22 color: Some(color),
23 ..Default::default()
24 }
25}
26
27fn underline(color: Option<Hsla>) -> UnderlineStyle {
28 UnderlineStyle {
29 thickness: px(1.),
30 color,
31 wavy: false,
32 }
33}
34
35fn mark_style(kind: &MarkKind) -> HighlightStyle {
36 let mut style = HighlightStyle::default();
37 match kind {
38 MarkKind::Bold => style.font_weight = Some(FontWeight::BOLD),
39 MarkKind::Italic => style.font_style = Some(FontStyle::Italic),
40 MarkKind::Underline => style.underline = Some(underline(None)),
41 MarkKind::Strike => {
42 style.color = Some(theme::text_muted());
43 style.strikethrough = Some(StrikethroughStyle {
44 thickness: px(1.),
45 color: None,
46 });
47 }
48 MarkKind::Code => style.color = Some(theme::text_strong()),
49 MarkKind::Link(_) => {
50 style.color = Some(theme::accent_text());
51 style.underline = Some(underline(Some(theme::accent_text())));
52 }
53 }
54 style
55}
56
57/// A range the block or bar decoration paints over every line of `lines`; `None` when the
58/// block is one empty line it cannot address yet.
59fn block_range(draft: &Draft, lines: Range<usize>) -> Option<Range<usize>> {
60 let line_ranges = draft.line_ranges();
61 let start = line_ranges[lines.start].start;
62 let end = line_ranges[lines.end - 1].end;
63 if end > start {
64 return Some(start..end);
65 }
66 if end < draft.text().len() {
67 return Some(start..start + 1);
68 }
69 let previous_has_text = lines.start > 0 && !line_ranges[lines.start - 1].is_empty();
70 previous_has_text.then(|| start - 1..start)
71}
72
73pub fn draft_style(draft: &Draft, mono: SharedString) -> DraftStyle {
74 let mut text = Vec::new();
75 let mut ranges = Vec::new();
76 let mut markers = Vec::new();
77 for mark in draft.marks() {
78 let decoration = TextDecoration::new(mark.range.clone(), mark_style(&mark.kind));
79 if mark.kind == MarkKind::Code {
80 text.push(decoration.with_font_family(mono.clone()));
81 ranges.push(
82 RangeDecoration::new(mark.range.clone())
83 .with_style(RangeDecorationStyle::Pill)
84 .with_color(theme::inline_code_fill(false))
85 .with_border(theme::inline_code_border())
86 .with_radius(px(CODE_PILL_RADIUS)),
87 );
88 } else {
89 text.push(decoration);
90 }
91 }
92 let kinds = draft.lines();
93 let mut index = 0;
94 while index < kinds.len() {
95 let kind = &kinds[index];
96 let run_end = index
97 + kinds[index..]
98 .iter()
99 .take_while(|other| *other == kind)
100 .count();
101 for line in index..run_end {
102 let marker = draft.marker_range(line);
103 let content = draft.content_range(line);
104 if !marker.is_empty() {
105 markers.push(marker.clone());
106 if kind.is_list() {
107 text.push(TextDecoration::new(marker, color(theme::text_soft())));
108 }
109 }
110 if content.is_empty() {
111 continue;
112 }
113 match kind {
114 LineKind::Quote => {
115 text.push(TextDecoration::new(content, color(theme::text_soft())))
116 }
117 LineKind::Code(_) => text.push(
118 TextDecoration::new(content, color(theme::text_strong()))
119 .with_font_family(mono.clone()),
120 ),
121 _ => {}
122 }
123 }
124 let block = match kind {
125 LineKind::Code(_) => block_range(draft, index..run_end).map(|range| {
126 RangeDecoration::new(range)
127 .with_style(RangeDecorationStyle::Block)
128 .with_color(theme::code_surface())
129 .with_radius(px(CODE_BLOCK_RADIUS))
130 }),
131 LineKind::Quote => block_range(draft, index..run_end).map(|range| {
132 RangeDecoration::new(range)
133 .with_style(RangeDecorationStyle::Bar)
134 .with_color(theme::border_strong())
135 .with_radius(px(QUOTE_BAR_WIDTH))
136 }),
137 _ => None,
138 };
139 ranges.extend(block);
140 index = run_end;
141 }
142 DraftStyle {
143 text,
144 ranges,
145 markers,
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use gpui_kit::component::input::RangeDecorationStyle;
152 use teams_core::{Draft, DraftLine, LineKind};
153
154 use super::{block_range, draft_style};
155
156 #[test]
157 fn list_markers_hang_and_code_gets_a_pill() {
158 let draft = Draft::from_markdown("- one `x`\n```\nfn\n```");
159 let style = draft_style(&draft, "Mono".into());
160 assert_eq!(style.markers, [draft.marker_range(0)]);
161 assert_eq!(
162 style
163 .ranges
164 .iter()
165 .map(|range| range.style())
166 .collect::<Vec<_>>(),
167 [RangeDecorationStyle::Pill, RangeDecorationStyle::Block]
168 );
169 }
170
171 #[test]
172 fn an_empty_code_line_at_the_end_still_gets_its_block() {
173 let draft = Draft::from_lines(&[
174 DraftLine {
175 kind: LineKind::Text,
176 number: None,
177 content: "intro".into(),
178 marks: Vec::new(),
179 },
180 DraftLine {
181 kind: LineKind::Code(None),
182 number: None,
183 content: String::new(),
184 marks: Vec::new(),
185 },
186 ]);
187 assert_eq!(block_range(&draft, 1..2), Some(5..6));
188 }
189}
crates/app/src/views/format_toolbar.rs added +320 −0
@@ -0,0 +1,320 @@
1 use std::rc::Rc;
2
3 use gpui_kit::component::input::{Input, InputState};
4 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5 use gpui_kit::prelude::FluentBuilder as _;
6 use gpui_kit::*;
7 use teams_core::FormatState;
8
9 use super::widgets::symbol;
10 use crate::theme;
11
12 const PADDING: f32 = 4.;
13 const BUTTON: f32 = 28.;
14 const BUTTON_GAP: f32 = 2.;
15 const SEPARATOR_MARGIN: f32 = 4.;
16 const GAP: f32 = 8.;
17 const ARROW_WIDTH: f32 = 14.;
18 const ARROW_HEIGHT: f32 = 7.;
19 const ARROW_MARGIN: f32 = 12.;
20 const LINK_FIELD_WIDTH: f32 = 240.;
21 const APPLY_WIDTH: f32 = 64.;
22 const ACTIVE_ALPHA: f32 = 0.22;
23
24 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
25 pub enum FormatButton {
26 Bold,
27 Italic,
28 Underline,
29 Strike,
30 Code,
31 Link,
32 Bulleted,
33 Numbered,
34 Quote,
35 }
36
37 pub const GROUPS: [&[FormatButton]; 3] = [
38 &[
39 FormatButton::Bold,
40 FormatButton::Italic,
41 FormatButton::Underline,
42 FormatButton::Strike,
43 ],
44 &[FormatButton::Code, FormatButton::Link],
45 &[
46 FormatButton::Bulleted,
47 FormatButton::Numbered,
48 FormatButton::Quote,
49 ],
50 ];
51
52 impl FormatButton {
53 fn tooltip(self) -> &'static str {
54 match self {
55 FormatButton::Bold => "Bold (Ctrl+B)",
56 FormatButton::Italic => "Italic (Ctrl+I)",
57 FormatButton::Underline => "Underline (Ctrl+U)",
58 FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",
59 FormatButton::Code => "Code (Ctrl+Shift+C)",
60 FormatButton::Link => "Link (Ctrl+K)",
61 FormatButton::Bulleted => "Bulleted list",
62 FormatButton::Numbered => "Numbered list",
63 FormatButton::Quote => "Quote",
64 }
65 }
66
67 fn content(self, color: Hsla) -> AnyElement {
68 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
69 match self {
70 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
71 FormatButton::Italic => letter("I").italic().into_any_element(),
72 FormatButton::Underline => letter("U").underline().into_any_element(),
73 FormatButton::Strike => letter("S").line_through().into_any_element(),
74 FormatButton::Code => symbol("code", 18., color).into_any_element(),
75 FormatButton::Link => symbol("link", 18., color).into_any_element(),
76 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
77 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
78 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
79 }
80 }
81 }
82
83 pub fn bar_width() -> f32 {
84 let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();
85 let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();
86 let separators = (GROUPS.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);
87 2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators
88 }
89
90 pub fn link_width() -> f32 {
91 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
92 }
93
94 #[derive(Debug, Clone, Copy, PartialEq)]
95 pub struct Placement {
96 pub left: Pixels,
97 pub bottom: Pixels,
98 pub arrow_x: Pixels,
99 }
100
101 /// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
102 pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
103 let width = px(width);
104 let (left_edge, right_edge) = edges;
105 let left = (center_x - width / 2.)
106 .min(right_edge - width)
107 .max(left_edge);
108 Placement {
109 left,
110 bottom: top - px(GAP),
111 arrow_x: (center_x - left)
112 .max(px(ARROW_MARGIN))
113 .min(width - px(ARROW_MARGIN)),
114 }
115 }
116
117 pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
118 pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
119
120 pub enum Mode<'a> {
121 Bar {
122 state: &'a dyn Fn(FormatButton) -> FormatState,
123 on_press: PressHandler,
124 },
125 Link {
126 field: &'a Entity<InputState>,
127 on_apply: ApplyHandler,
128 },
129 }
130
131 fn button(format: FormatButton, state: FormatState, on_press: PressHandler) -> impl IntoElement {
132 let on = state == FormatState::On;
133 let color = if on {
134 theme::accent_soft()
135 } else {
136 theme::text_soft()
137 };
138 div()
139 .id(ElementId::Name(format!("format-{format:?}").into()))
140 .relative()
141 .size(px(BUTTON))
142 .flex()
143 .flex_none()
144 .items_center()
145 .justify_center()
146 .rounded(px(6.))
147 .border_1()
148 .border_color(transparent_black())
149 .cursor_pointer()
150 .when(on, |button| {
151 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
152 })
153 .hover(|button| button.border_color(theme::border_strong()))
154 .tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
155 .child(format.content(color))
156 .when(state == FormatState::Mixed, |button| {
157 button.child(
158 div()
159 .absolute()
160 .bottom(px(2.))
161 .left(px(7.))
162 .w(px(BUTTON - 16.))
163 .h(px(2.))
164 .rounded(px(1.))
165 .bg(theme::accent()),
166 )
167 })
168 .on_mouse_down(MouseButton::Left, |_, window, cx| {
169 window.prevent_default();
170 cx.stop_propagation();
171 })
172 .on_click(move |_, window, cx| on_press(format, window, cx))
173 }
174
175 fn separator() -> Div {
176 div()
177 .w(px(1.))
178 .h(px(BUTTON - 8.))
179 .mx(px(SEPARATOR_MARGIN))
180 .bg(theme::border_strong())
181 }
182
183 fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> Div {
184 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
185 for (index, group) in GROUPS.iter().enumerate() {
186 if index > 0 {
187 row = row.child(separator());
188 }
189 for format in group.iter().copied() {
190 row = row.child(button(format, state(format), on_press.clone()));
191 }
192 }
193 row
194 }
195
196 fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
197 h_flex()
198 .gap(px(BUTTON_GAP * 2.))
199 .items_center()
200 .child(
201 div()
202 .w(px(LINK_FIELD_WIDTH))
203 .h(px(BUTTON))
204 .rounded(px(6.))
205 .border_1()
206 .border_color(theme::accent())
207 .bg(theme::surface())
208 .child(Input::new(field).appearance(false).bordered(false)),
209 )
210 .child(
211 div()
212 .id("format-link-apply")
213 .w(px(APPLY_WIDTH))
214 .h(px(BUTTON))
215 .flex()
216 .items_center()
217 .justify_center()
218 .rounded(px(6.))
219 .bg(theme::accent())
220 .text_color(theme::on_accent())
221 .text_size(px(13.))
222 .font_weight(FontWeight::SEMIBOLD)
223 .cursor_pointer()
224 .hover(|button| button.opacity(0.9))
225 .child("Apply")
226 .on_mouse_down(MouseButton::Left, |_, window, cx| {
227 window.prevent_default();
228 cx.stop_propagation();
229 })
230 .on_click(move |_, window, cx| on_apply(window, cx)),
231 )
232 }
233
234 fn arrow(offset: Pixels) -> impl IntoElement {
235 canvas(
236 |_, _, _| {},
237 move |bounds, _, window, _| {
238 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
239 for (inset, color) in [(0., theme::border_strong()), (1.5, theme::surface_raised())] {
240 let mut builder = PathBuilder::fill();
241 builder.move_to(point(
242 tip.x - px(ARROW_WIDTH / 2. - inset),
243 bounds.origin.y - px(1.),
244 ));
245 builder.line_to(point(
246 tip.x + px(ARROW_WIDTH / 2. - inset),
247 bounds.origin.y - px(1.),
248 ));
249 builder.line_to(point(tip.x, tip.y - px(inset)));
250 builder.close();
251 if let Ok(path) = builder.build() {
252 window.paint_path(path, color);
253 }
254 }
255 },
256 )
257 .w_full()
258 .h(px(ARROW_HEIGHT))
259 }
260
261 pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
262 let content = match mode {
263 Mode::Bar { state, on_press } => bar(state, on_press),
264 Mode::Link { field, on_apply } => link_editor(field, on_apply),
265 };
266 deferred(
267 anchored()
268 .position(point(placement.left, placement.bottom))
269 .anchor(Anchor::BottomLeft)
270 .child(
271 v_flex()
272 .id("format-toolbar")
273 .occlude()
274 .child(
275 div()
276 .p(px(PADDING))
277 .rounded(px(8.))
278 .border_1()
279 .border_color(theme::border_strong())
280 .bg(theme::surface_raised())
281 .shadow_lg()
282 .child(content),
283 )
284 .child(arrow(placement.arrow_x)),
285 ),
286 )
287 .with_priority(1)
288 .into_any_element()
289 }
290
291 #[cfg(test)]
292 mod tests {
293 use gpui_kit::px;
294
295 use super::{ARROW_MARGIN, BUTTON, GROUPS, bar_width, place};
296
297 #[test]
298 fn the_bar_centers_over_the_selection() {
299 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
300 assert_eq!(placement.left, px(300.));
301 assert_eq!(placement.bottom, px(292.));
302 assert_eq!(placement.arrow_x, px(100.));
303 }
304
305 #[test]
306 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
307 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
308 assert_eq!(near_left.left, px(100.));
309 assert_eq!(near_left.arrow_x, px(20.));
310 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
311 assert_eq!(near_right.left, px(700.));
312 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
313 }
314
315 #[test]
316 fn the_bar_holds_nine_buttons_in_three_groups() {
317 assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 9);
318 assert!(bar_width() > 9. * BUTTON);
319 }
320 }
@@ -0,0 +1,320 @@
1use std::rc::Rc;
2
3use gpui_kit::component::input::{Input, InputState};
4use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
7use teams_core::FormatState;
8
9use super::widgets::symbol;
10use crate::theme;
11
12const PADDING: f32 = 4.;
13const BUTTON: f32 = 28.;
14const BUTTON_GAP: f32 = 2.;
15const SEPARATOR_MARGIN: f32 = 4.;
16const GAP: f32 = 8.;
17const ARROW_WIDTH: f32 = 14.;
18const ARROW_HEIGHT: f32 = 7.;
19const ARROW_MARGIN: f32 = 12.;
20const LINK_FIELD_WIDTH: f32 = 240.;
21const APPLY_WIDTH: f32 = 64.;
22const ACTIVE_ALPHA: f32 = 0.22;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum FormatButton {
26 Bold,
27 Italic,
28 Underline,
29 Strike,
30 Code,
31 Link,
32 Bulleted,
33 Numbered,
34 Quote,
35}
36
37pub const GROUPS: [&[FormatButton]; 3] = [
38 &[
39 FormatButton::Bold,
40 FormatButton::Italic,
41 FormatButton::Underline,
42 FormatButton::Strike,
43 ],
44 &[FormatButton::Code, FormatButton::Link],
45 &[
46 FormatButton::Bulleted,
47 FormatButton::Numbered,
48 FormatButton::Quote,
49 ],
50];
51
52impl FormatButton {
53 fn tooltip(self) -> &'static str {
54 match self {
55 FormatButton::Bold => "Bold (Ctrl+B)",
56 FormatButton::Italic => "Italic (Ctrl+I)",
57 FormatButton::Underline => "Underline (Ctrl+U)",
58 FormatButton::Strike => "Strikethrough (Ctrl+Shift+X)",
59 FormatButton::Code => "Code (Ctrl+Shift+C)",
60 FormatButton::Link => "Link (Ctrl+K)",
61 FormatButton::Bulleted => "Bulleted list",
62 FormatButton::Numbered => "Numbered list",
63 FormatButton::Quote => "Quote",
64 }
65 }
66
67 fn content(self, color: Hsla) -> AnyElement {
68 let letter = |text: &'static str| div().text_size(px(15.)).text_color(color).child(text);
69 match self {
70 FormatButton::Bold => letter("B").font_weight(FontWeight::BOLD).into_any_element(),
71 FormatButton::Italic => letter("I").italic().into_any_element(),
72 FormatButton::Underline => letter("U").underline().into_any_element(),
73 FormatButton::Strike => letter("S").line_through().into_any_element(),
74 FormatButton::Code => symbol("code", 18., color).into_any_element(),
75 FormatButton::Link => symbol("link", 18., color).into_any_element(),
76 FormatButton::Bulleted => symbol("format_list_bulleted", 18., color).into_any_element(),
77 FormatButton::Numbered => symbol("format_list_numbered", 18., color).into_any_element(),
78 FormatButton::Quote => symbol("format_quote", 18., color).into_any_element(),
79 }
80 }
81}
82
83pub fn bar_width() -> f32 {
84 let buttons: usize = GROUPS.iter().map(|group| group.len()).sum();
85 let gaps: usize = GROUPS.iter().map(|group| group.len() - 1).sum();
86 let separators = (GROUPS.len() - 1) as f32 * (1. + 2. * SEPARATOR_MARGIN);
87 2. * PADDING + buttons as f32 * BUTTON + gaps as f32 * BUTTON_GAP + separators
88}
89
90pub fn link_width() -> f32 {
91 2. * PADDING + LINK_FIELD_WIDTH + BUTTON_GAP * 2. + APPLY_WIDTH
92}
93
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct Placement {
96 pub left: Pixels,
97 pub bottom: Pixels,
98 pub arrow_x: Pixels,
99}
100
101/// Centered over `center_x`, `GAP` above `top`, kept between the composer edges.
102pub fn place(center_x: Pixels, top: Pixels, edges: (Pixels, Pixels), width: f32) -> Placement {
103 let width = px(width);
104 let (left_edge, right_edge) = edges;
105 let left = (center_x - width / 2.)
106 .min(right_edge - width)
107 .max(left_edge);
108 Placement {
109 left,
110 bottom: top - px(GAP),
111 arrow_x: (center_x - left)
112 .max(px(ARROW_MARGIN))
113 .min(width - px(ARROW_MARGIN)),
114 }
115}
116
117pub type PressHandler = Rc<dyn Fn(FormatButton, &mut Window, &mut App)>;
118pub type ApplyHandler = Rc<dyn Fn(&mut Window, &mut App)>;
119
120pub enum Mode<'a> {
121 Bar {
122 state: &'a dyn Fn(FormatButton) -> FormatState,
123 on_press: PressHandler,
124 },
125 Link {
126 field: &'a Entity<InputState>,
127 on_apply: ApplyHandler,
128 },
129}
130
131fn button(format: FormatButton, state: FormatState, on_press: PressHandler) -> impl IntoElement {
132 let on = state == FormatState::On;
133 let color = if on {
134 theme::accent_soft()
135 } else {
136 theme::text_soft()
137 };
138 div()
139 .id(ElementId::Name(format!("format-{format:?}").into()))
140 .relative()
141 .size(px(BUTTON))
142 .flex()
143 .flex_none()
144 .items_center()
145 .justify_center()
146 .rounded(px(6.))
147 .border_1()
148 .border_color(transparent_black())
149 .cursor_pointer()
150 .when(on, |button| {
151 button.bg(theme::accent().opacity(ACTIVE_ALPHA))
152 })
153 .hover(|button| button.border_color(theme::border_strong()))
154 .tooltip(move |window, cx| Tooltip::new(format.tooltip()).build(window, cx))
155 .child(format.content(color))
156 .when(state == FormatState::Mixed, |button| {
157 button.child(
158 div()
159 .absolute()
160 .bottom(px(2.))
161 .left(px(7.))
162 .w(px(BUTTON - 16.))
163 .h(px(2.))
164 .rounded(px(1.))
165 .bg(theme::accent()),
166 )
167 })
168 .on_mouse_down(MouseButton::Left, |_, window, cx| {
169 window.prevent_default();
170 cx.stop_propagation();
171 })
172 .on_click(move |_, window, cx| on_press(format, window, cx))
173}
174
175fn separator() -> Div {
176 div()
177 .w(px(1.))
178 .h(px(BUTTON - 8.))
179 .mx(px(SEPARATOR_MARGIN))
180 .bg(theme::border_strong())
181}
182
183fn bar(state: &dyn Fn(FormatButton) -> FormatState, on_press: PressHandler) -> Div {
184 let mut row = h_flex().gap(px(BUTTON_GAP)).items_center();
185 for (index, group) in GROUPS.iter().enumerate() {
186 if index > 0 {
187 row = row.child(separator());
188 }
189 for format in group.iter().copied() {
190 row = row.child(button(format, state(format), on_press.clone()));
191 }
192 }
193 row
194}
195
196fn link_editor(field: &Entity<InputState>, on_apply: ApplyHandler) -> Div {
197 h_flex()
198 .gap(px(BUTTON_GAP * 2.))
199 .items_center()
200 .child(
201 div()
202 .w(px(LINK_FIELD_WIDTH))
203 .h(px(BUTTON))
204 .rounded(px(6.))
205 .border_1()
206 .border_color(theme::accent())
207 .bg(theme::surface())
208 .child(Input::new(field).appearance(false).bordered(false)),
209 )
210 .child(
211 div()
212 .id("format-link-apply")
213 .w(px(APPLY_WIDTH))
214 .h(px(BUTTON))
215 .flex()
216 .items_center()
217 .justify_center()
218 .rounded(px(6.))
219 .bg(theme::accent())
220 .text_color(theme::on_accent())
221 .text_size(px(13.))
222 .font_weight(FontWeight::SEMIBOLD)
223 .cursor_pointer()
224 .hover(|button| button.opacity(0.9))
225 .child("Apply")
226 .on_mouse_down(MouseButton::Left, |_, window, cx| {
227 window.prevent_default();
228 cx.stop_propagation();
229 })
230 .on_click(move |_, window, cx| on_apply(window, cx)),
231 )
232}
233
234fn arrow(offset: Pixels) -> impl IntoElement {
235 canvas(
236 |_, _, _| {},
237 move |bounds, _, window, _| {
238 let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
239 for (inset, color) in [(0., theme::border_strong()), (1.5, theme::surface_raised())] {
240 let mut builder = PathBuilder::fill();
241 builder.move_to(point(
242 tip.x - px(ARROW_WIDTH / 2. - inset),
243 bounds.origin.y - px(1.),
244 ));
245 builder.line_to(point(
246 tip.x + px(ARROW_WIDTH / 2. - inset),
247 bounds.origin.y - px(1.),
248 ));
249 builder.line_to(point(tip.x, tip.y - px(inset)));
250 builder.close();
251 if let Ok(path) = builder.build() {
252 window.paint_path(path, color);
253 }
254 }
255 },
256 )
257 .w_full()
258 .h(px(ARROW_HEIGHT))
259}
260
261pub fn render(placement: Placement, mode: Mode<'_>) -> AnyElement {
262 let content = match mode {
263 Mode::Bar { state, on_press } => bar(state, on_press),
264 Mode::Link { field, on_apply } => link_editor(field, on_apply),
265 };
266 deferred(
267 anchored()
268 .position(point(placement.left, placement.bottom))
269 .anchor(Anchor::BottomLeft)
270 .child(
271 v_flex()
272 .id("format-toolbar")
273 .occlude()
274 .child(
275 div()
276 .p(px(PADDING))
277 .rounded(px(8.))
278 .border_1()
279 .border_color(theme::border_strong())
280 .bg(theme::surface_raised())
281 .shadow_lg()
282 .child(content),
283 )
284 .child(arrow(placement.arrow_x)),
285 ),
286 )
287 .with_priority(1)
288 .into_any_element()
289}
290
291#[cfg(test)]
292mod tests {
293 use gpui_kit::px;
294
295 use super::{ARROW_MARGIN, BUTTON, GROUPS, bar_width, place};
296
297 #[test]
298 fn the_bar_centers_over_the_selection() {
299 let placement = place(px(400.), px(300.), (px(100.), px(900.)), 200.);
300 assert_eq!(placement.left, px(300.));
301 assert_eq!(placement.bottom, px(292.));
302 assert_eq!(placement.arrow_x, px(100.));
303 }
304
305 #[test]
306 fn the_bar_stays_inside_the_composer_and_the_arrow_follows_the_selection() {
307 let near_left = place(px(120.), px(300.), (px(100.), px(900.)), 200.);
308 assert_eq!(near_left.left, px(100.));
309 assert_eq!(near_left.arrow_x, px(20.));
310 let near_right = place(px(899.), px(300.), (px(100.), px(900.)), 200.);
311 assert_eq!(near_right.left, px(700.));
312 assert_eq!(near_right.arrow_x, px(200. - ARROW_MARGIN));
313 }
314
315 #[test]
316 fn the_bar_holds_nine_buttons_in_three_groups() {
317 assert_eq!(GROUPS.iter().map(|group| group.len()).sum::<usize>(), 9);
318 assert!(bar_width() > 9. * BUTTON);
319 }
320}
crates/app/src/views/mod.rs +2 −0
@@ -3,7 +3,9 @@ pub mod attachments;
3 3 pub mod avatar;
4 4 pub mod composer;
5 5 pub mod conversation;
6 pub mod draft_style;
6 7 pub mod emoji_popup;
8 pub mod format_toolbar;
7 9 pub mod message_actions;
8 10 pub mod message_row;
9 11 pub mod new_chat;
@@ -3,7 +3,9 @@ pub mod attachments;
3pub mod avatar;
3pub mod avatar;
4pub mod composer;
4pub mod composer;
5pub mod conversation;
5pub mod conversation;
6pub mod draft_style;
6pub mod emoji_popup;
7pub mod emoji_popup;
8pub mod format_toolbar;
7pub mod message_actions;
9pub mod message_actions;
8pub mod message_row;
10pub mod message_row;
9pub mod new_chat;
11pub mod new_chat;
crates/app/src/views/shell.rs +1 −0
@@ -14,6 +14,7 @@ use crate::updater::{self, IdleInputs, UpdateStatus};
14 14 actions!(teams, [OpenSwitcher, NewChat]);
15 15
16 16 pub fn bind_keys(cx: &mut App) {
17 super::composer::bind_keys(cx);
17 18 cx.bind_keys([
18 19 KeyBinding::new("ctrl-k", OpenSwitcher, None),
19 20 KeyBinding::new("ctrl-n", NewChat, None),
@@ -14,6 +14,7 @@ use crate::updater::{self, IdleInputs, UpdateStatus};
14actions!(teams, [OpenSwitcher, NewChat]);
14actions!(teams, [OpenSwitcher, NewChat]);
15
15
16pub fn bind_keys(cx: &mut App) {
16pub fn bind_keys(cx: &mut App) {
17 super::composer::bind_keys(cx);
17 cx.bind_keys([
18 cx.bind_keys([
18 KeyBinding::new("ctrl-k", OpenSwitcher, None),
19 KeyBinding::new("ctrl-k", OpenSwitcher, None),
19 KeyBinding::new("ctrl-n", NewChat, None),
20 KeyBinding::new("ctrl-n", NewChat, None),
crates/core/src/actions.rs +29 −12
@@ -31,7 +31,7 @@ impl<R: Remote> SyncEngine<R> {
31 31 ) -> Result<MessageRecord> {
32 32 self.send_message_with_extras(
33 33 conversation_id,
34 markdown,
34 &markdown_to_html(markdown),
35 35 thread_root_id,
36 36 mentions,
37 37 &MessageExtras::default(),
@@ -39,16 +39,17 @@ impl<R: Remote> SyncEngine<R> {
39 39 .await
40 40 }
41 41
42 /// `html` is the message body; mentions are matched as `@name` in it.
42 43 pub async fn send_message_with_extras(
43 44 &self,
44 45 conversation_id: &str,
45 markdown: &str,
46 html: &str,
46 47 thread_root_id: Option<&str>,
47 48 mentions: &[MentionInput],
48 49 extras: &MessageExtras,
49 50 ) -> Result<MessageRecord> {
50 51 let conversation = self.resolve(conversation_id)?;
51 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
52 let (html, mentions) = outgoing(&conversation, html, mentions)?;
52 53 let sent = match (conversation, thread_root_id) {
53 54 (Conversation::Chat, None) => {
54 55 self.remote
@@ -100,7 +101,7 @@ impl<R: Remote> SyncEngine<R> {
100 101 self.reply_to_with_extras(
101 102 conversation_id,
102 103 message_id,
103 markdown,
104 &markdown_to_html(markdown),
104 105 mentions,
105 106 &MessageExtras::default(),
106 107 )
@@ -111,12 +112,12 @@ impl<R: Remote> SyncEngine<R> {
111 112 &self,
112 113 conversation_id: &str,
113 114 message_id: &str,
114 markdown: &str,
115 html: &str,
115 116 mentions: &[MentionInput],
116 117 extras: &MessageExtras,
117 118 ) -> Result<MessageRecord> {
118 119 let conversation = self.resolve(conversation_id)?;
119 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
120 let (html, mentions) = outgoing(&conversation, html, mentions)?;
120 121 let sent = match conversation {
121 122 Conversation::Chat => {
122 123 self.remote
@@ -183,7 +184,7 @@ impl<R: Remote> SyncEngine<R> {
183 184 ) -> Result<MessageRecord> {
184 185 self.post_to_channel_with_extras(
185 186 channel_id,
186 markdown,
187 &markdown_to_html(markdown),
187 188 subject,
188 189 mentions,
189 190 &MessageExtras::default(),
@@ -194,7 +195,7 @@ impl<R: Remote> SyncEngine<R> {
194 195 pub async fn post_to_channel_with_extras(
195 196 &self,
196 197 channel_id: &str,
197 markdown: &str,
198 html: &str,
198 199 subject: Option<&str>,
199 200 mentions: &[MentionInput],
200 201 extras: &MessageExtras,
@@ -203,7 +204,7 @@ impl<R: Remote> SyncEngine<R> {
203 204 let Conversation::Channel { team_id } = &conversation else {
204 205 return Err(Error::Unsupported("posting a root message to a chat"));
205 206 };
206 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
207 let (html, mentions) = outgoing(&conversation, html, mentions)?;
207 208 let sent = self
208 209 .remote
209 210 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
@@ -385,9 +386,25 @@ impl<R: Remote> SyncEngine<R> {
385 386 message_id: &str,
386 387 markdown: &str,
387 388 mentions: &[MentionInput],
389 ) -> Result<()> {
390 self.edit_message_html(
391 conversation_id,
392 message_id,
393 &markdown_to_html(markdown),
394 mentions,
395 )
396 .await
397 }
398
399 pub async fn edit_message_html(
400 &self,
401 conversation_id: &str,
402 message_id: &str,
403 html: &str,
404 mentions: &[MentionInput],
388 405 ) -> Result<()> {
389 406 let conversation = self.resolve(conversation_id)?;
390 let (mut html, mentions) = outgoing(&conversation, markdown, mentions)?;
407 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
391 408 let target = self.message_target(conversation_id, message_id)?;
392 409 let mut extras = MessageExtras::default();
393 410 if let Some(record) = self
@@ -498,13 +515,13 @@ impl<R: Remote> SyncEngine<R> {
498 515
499 516 fn outgoing(
500 517 conversation: &Conversation,
501 markdown: &str,
518 html: &str,
502 519 mentions: &[MentionInput],
503 520 ) -> Result<(String, Vec<OutgoingMention>)> {
504 521 if matches!(conversation, Conversation::Chat) {
505 522 ensure_allowed_in_chat(mentions)?;
506 523 }
507 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
524 Ok(apply_mentions(html, mentions))
508 525 }
509 526
510 527 fn missing_attachment_id() -> Error {
@@ -31,7 +31,7 @@ impl<R: Remote> SyncEngine<R> {
31 ) -> Result<MessageRecord> {
31 ) -> Result<MessageRecord> {
32 self.send_message_with_extras(
32 self.send_message_with_extras(
33 conversation_id,
33 conversation_id,
34 markdown,
34 &markdown_to_html(markdown),
35 thread_root_id,
35 thread_root_id,
36 mentions,
36 mentions,
37 &MessageExtras::default(),
37 &MessageExtras::default(),
@@ -39,16 +39,17 @@ impl<R: Remote> SyncEngine<R> {
39 .await
39 .await
40 }
40 }
41
41
42 /// `html` is the message body; mentions are matched as `@name` in it.
42 pub async fn send_message_with_extras(
43 pub async fn send_message_with_extras(
43 &self,
44 &self,
44 conversation_id: &str,
45 conversation_id: &str,
45 markdown: &str,
46 html: &str,
46 thread_root_id: Option<&str>,
47 thread_root_id: Option<&str>,
47 mentions: &[MentionInput],
48 mentions: &[MentionInput],
48 extras: &MessageExtras,
49 extras: &MessageExtras,
49 ) -> Result<MessageRecord> {
50 ) -> Result<MessageRecord> {
50 let conversation = self.resolve(conversation_id)?;
51 let conversation = self.resolve(conversation_id)?;
51 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
52 let (html, mentions) = outgoing(&conversation, html, mentions)?;
52 let sent = match (conversation, thread_root_id) {
53 let sent = match (conversation, thread_root_id) {
53 (Conversation::Chat, None) => {
54 (Conversation::Chat, None) => {
54 self.remote
55 self.remote
@@ -100,7 +101,7 @@ impl<R: Remote> SyncEngine<R> {
100 self.reply_to_with_extras(
101 self.reply_to_with_extras(
101 conversation_id,
102 conversation_id,
102 message_id,
103 message_id,
103 markdown,
104 &markdown_to_html(markdown),
104 mentions,
105 mentions,
105 &MessageExtras::default(),
106 &MessageExtras::default(),
106 )
107 )
@@ -111,12 +112,12 @@ impl<R: Remote> SyncEngine<R> {
111 &self,
112 &self,
112 conversation_id: &str,
113 conversation_id: &str,
113 message_id: &str,
114 message_id: &str,
114 markdown: &str,
115 html: &str,
115 mentions: &[MentionInput],
116 mentions: &[MentionInput],
116 extras: &MessageExtras,
117 extras: &MessageExtras,
117 ) -> Result<MessageRecord> {
118 ) -> Result<MessageRecord> {
118 let conversation = self.resolve(conversation_id)?;
119 let conversation = self.resolve(conversation_id)?;
119 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
120 let (html, mentions) = outgoing(&conversation, html, mentions)?;
120 let sent = match conversation {
121 let sent = match conversation {
121 Conversation::Chat => {
122 Conversation::Chat => {
122 self.remote
123 self.remote
@@ -183,7 +184,7 @@ impl<R: Remote> SyncEngine<R> {
183 ) -> Result<MessageRecord> {
184 ) -> Result<MessageRecord> {
184 self.post_to_channel_with_extras(
185 self.post_to_channel_with_extras(
185 channel_id,
186 channel_id,
186 markdown,
187 &markdown_to_html(markdown),
187 subject,
188 subject,
188 mentions,
189 mentions,
189 &MessageExtras::default(),
190 &MessageExtras::default(),
@@ -194,7 +195,7 @@ impl<R: Remote> SyncEngine<R> {
194 pub async fn post_to_channel_with_extras(
195 pub async fn post_to_channel_with_extras(
195 &self,
196 &self,
196 channel_id: &str,
197 channel_id: &str,
197 markdown: &str,
198 html: &str,
198 subject: Option<&str>,
199 subject: Option<&str>,
199 mentions: &[MentionInput],
200 mentions: &[MentionInput],
200 extras: &MessageExtras,
201 extras: &MessageExtras,
@@ -203,7 +204,7 @@ impl<R: Remote> SyncEngine<R> {
203 let Conversation::Channel { team_id } = &conversation else {
204 let Conversation::Channel { team_id } = &conversation else {
204 return Err(Error::Unsupported("posting a root message to a chat"));
205 return Err(Error::Unsupported("posting a root message to a chat"));
205 };
206 };
206 let (html, mentions) = outgoing(&conversation, markdown, mentions)?;
207 let (html, mentions) = outgoing(&conversation, html, mentions)?;
207 let sent = self
208 let sent = self
208 .remote
209 .remote
209 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
210 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
@@ -385,9 +386,25 @@ impl<R: Remote> SyncEngine<R> {
385 message_id: &str,
386 message_id: &str,
386 markdown: &str,
387 markdown: &str,
387 mentions: &[MentionInput],
388 mentions: &[MentionInput],
389 ) -> Result<()> {
390 self.edit_message_html(
391 conversation_id,
392 message_id,
393 &markdown_to_html(markdown),
394 mentions,
395 )
396 .await
397 }
398
399 pub async fn edit_message_html(
400 &self,
401 conversation_id: &str,
402 message_id: &str,
403 html: &str,
404 mentions: &[MentionInput],
388 ) -> Result<()> {
405 ) -> Result<()> {
389 let conversation = self.resolve(conversation_id)?;
406 let conversation = self.resolve(conversation_id)?;
390 let (mut html, mentions) = outgoing(&conversation, markdown, mentions)?;
407 let (mut html, mentions) = outgoing(&conversation, html, mentions)?;
391 let target = self.message_target(conversation_id, message_id)?;
408 let target = self.message_target(conversation_id, message_id)?;
392 let mut extras = MessageExtras::default();
409 let mut extras = MessageExtras::default();
393 if let Some(record) = self
410 if let Some(record) = self
@@ -498,13 +515,13 @@ impl<R: Remote> SyncEngine<R> {
498
515
499fn outgoing(
516fn outgoing(
500 conversation: &Conversation,
517 conversation: &Conversation,
501 markdown: &str,
518 html: &str,
502 mentions: &[MentionInput],
519 mentions: &[MentionInput],
503) -> Result<(String, Vec<OutgoingMention>)> {
520) -> Result<(String, Vec<OutgoingMention>)> {
504 if matches!(conversation, Conversation::Chat) {
521 if matches!(conversation, Conversation::Chat) {
505 ensure_allowed_in_chat(mentions)?;
522 ensure_allowed_in_chat(mentions)?;
506 }
523 }
507 Ok(apply_mentions(&markdown_to_html(markdown), mentions))
524 Ok(apply_mentions(html, mentions))
508}
525}
509
526
510fn missing_attachment_id() -> Error {
527fn missing_attachment_id() -> Error {
crates/core/src/draft.rs +21 −1
@@ -757,7 +757,10 @@ impl Draft {
757 757 let content = self.content_range(index);
758 758 let start = range.start.max(content.start);
759 759 let range = start..range.end.max(start);
760 let line_was_empty = self.lines[index] == LineKind::Text && content.is_empty();
760 let tail_end = self.line_ranges()[self.line_at(range.end)].end;
761 let line_was_empty = self.lines[index] == LineKind::Text
762 && range.start == content.start
763 && range.end >= tail_end;
761 764 let joined = lines
762 765 .iter()
763 766 .map(|line| line.content.as_str())
@@ -1969,6 +1972,23 @@ mod tests {
1969 1972 );
1970 1973 }
1971 1974
1975 #[test]
1976 fn markdown_pasted_on_its_own_line_converts_from_the_first_line() {
1977 let raw = "- a\n- b";
1978 let mut draft = Draft::plain("");
1979 draft.apply_edit(raw, raw.len(), None);
1980 let lines = Draft::from_markdown(raw).slice(0..usize::MAX);
1981 let cursor = draft.insert_lines(0..raw.len(), &lines);
1982 assert_eq!(draft.text(), "• a\n• b");
1983 assert_eq!(cursor, draft.text().len());
1984 let mut inline = Draft::plain("x ");
1985 inline.apply_edit("x **b**", 7, None);
1986 let lines = Draft::from_markdown("**b**").slice(0..usize::MAX);
1987 inline.insert_lines(2..7, &lines);
1988 assert_eq!(inline.text(), "x b");
1989 assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
1990 }
1991
1972 1992 #[test]
1973 1993 fn journal_merges_edits_into_ranges_of_the_old_text() {
1974 1994 let mut draft = Draft::plain("a **b** c");
@@ -757,7 +757,10 @@ impl Draft {
757 let content = self.content_range(index);
757 let content = self.content_range(index);
758 let start = range.start.max(content.start);
758 let start = range.start.max(content.start);
759 let range = start..range.end.max(start);
759 let range = start..range.end.max(start);
760 let line_was_empty = self.lines[index] == LineKind::Text && content.is_empty();
760 let tail_end = self.line_ranges()[self.line_at(range.end)].end;
761 let line_was_empty = self.lines[index] == LineKind::Text
762 && range.start == content.start
763 && range.end >= tail_end;
761 let joined = lines
764 let joined = lines
762 .iter()
765 .iter()
763 .map(|line| line.content.as_str())
766 .map(|line| line.content.as_str())
@@ -1969,6 +1972,23 @@ mod tests {
1969 );
1972 );
1970 }
1973 }
1971
1974
1975 #[test]
1976 fn markdown_pasted_on_its_own_line_converts_from_the_first_line() {
1977 let raw = "- a\n- b";
1978 let mut draft = Draft::plain("");
1979 draft.apply_edit(raw, raw.len(), None);
1980 let lines = Draft::from_markdown(raw).slice(0..usize::MAX);
1981 let cursor = draft.insert_lines(0..raw.len(), &lines);
1982 assert_eq!(draft.text(), "• a\n• b");
1983 assert_eq!(cursor, draft.text().len());
1984 let mut inline = Draft::plain("x ");
1985 inline.apply_edit("x **b**", 7, None);
1986 let lines = Draft::from_markdown("**b**").slice(0..usize::MAX);
1987 inline.insert_lines(2..7, &lines);
1988 assert_eq!(inline.text(), "x b");
1989 assert_eq!(inline.marks(), [mark(2..3, MarkKind::Bold)]);
1990 }
1991
1972 #[test]
1992 #[test]
1973 fn journal_merges_edits_into_ranges_of_the_old_text() {
1993 fn journal_merges_edits_into_ranges_of_the_old_text() {
1974 let mut draft = Draft::plain("a **b** c");
1994 let mut draft = Draft::plain("a **b** c");