BlueGit

ict rusty-teams

feat(channels): posts feed like Teams, newest on top, replies in the card

- Feed sorted by last activity, newest post on top, load older at the bottom
- Post card: subject, last 3 replies inline, "N replies from ..." opens the full conversation
- Reply box inside each card, "New post" at the top with optional subject
- Full conversation view with Back to channel (Esc), fetches every reply of the root
- Store keeps the post subject; channel delta links reset once to backfill it
- Sidebar: all teams start expanded, collapsed teams persist across restarts

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
5872f6bed946529e22673cd8183272aa15060356
Parent
28c20d68
31 files changed +2205 −687
README.md +1 −0
@@ -34,6 +34,7 @@
34 34
35 35 **Chats and channels**
36 36 - Teams pin order, chat folders, hidden teams
37 - Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view
37 38 - Chat menu: pin, move to folder, mark as unread, mute, hide, leave
38 39 - Read receipts, typing indicator with faces, presence, unread jump
39 40 - Activity bell: new messages, @mentions and reactions, kept for 14 days
@@ -34,6 +34,7 @@
34
34
35**Chats and channels**
35**Chats and channels**
36- Teams pin order, chat folders, hidden teams
36- Teams pin order, chat folders, hidden teams
37- Channel posts like Teams: one card per post, newest activity on top, last 3 replies, inline reply, new post with a subject, full conversation view
37- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
38- Chat menu: pin, move to folder, mark as unread, mute, hide, leave
38- Read receipts, typing indicator with faces, presence, unread jump
39- Read receipts, typing indicator with faces, presence, unread jump
39- Activity bell: new messages, @mentions and reactions, kept for 14 days
40- Activity bell: new messages, @mentions and reactions, kept for 14 days
ROADMAP.md +10 −10
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 72 %** (60 done, 3 partial, 22 missing of 85). Partial counts half.
5 **Parity: 74 %** (63 done, 2 partial, 21 missing of 86). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -13,9 +13,9 @@ Feature parity with the Microsoft Teams desktop client.
13 13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
14 14 | [Writing](#writing) | 100 % | 14 | 0 | 0 |
15 15 | [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16 | [Channels](#channels) | 36 % | 2 | 1 | 4 |
16 | [Channels](#channels) | 57 % | 4 | 0 | 3 |
17 17 | [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18 | [Search and navigation](#search-and-navigation) | 75 % | 3 | 0 | 1 |
18 | [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19 19 | [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |
20 20 | [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21 21 | [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |
@@ -24,9 +24,8 @@ Feature parity with the Microsoft Teams desktop client.
24 24
25 25 | # | Feature | Note |
26 26 |---|---|---|
27 | 1 | Channel: new post with subject, post cards | |
28 | 2 | Sign in on Linux without Chrome on a debug port | |
29 | 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
27 | 1 | Sign in on Linux without Chrome on a debug port | |
28 | 2 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30 29
31 30 ## Sign-in and app
32 31
@@ -111,9 +110,9 @@ Feature parity with the Microsoft Teams desktop client.
111 110 | Feature | State | Note |
112 111 |---|---|---|
113 112 | Teams and channels tree | Done | |
114 | Thread list, open a thread, reply | Done | |
115 | New post with subject | Partial | Backend takes a subject, UI sends none |
116 | Post cards like Teams | Missing | |
113 | Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
114 | New post with subject | Done | Subject is stored with the message |
115 | Post cards like Teams | Done | One card per post: root and the last 3 replies |
117 116 | Follow a channel, per-channel notifications | Missing | |
118 117 | Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
119 118 | Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
@@ -138,7 +137,8 @@ Feature parity with the Microsoft Teams desktop client.
138 137 | Ctrl+K switcher over chats, channels, people | Done | |
139 138 | Full-text search over cached messages | Done | |
140 139 | Jump to a message from search | Done | |
141 | Keyboard: Ctrl+1..9, Alt+Up/Down, Esc closes thread | Missing | |
140 | Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
141 | Keyboard: Ctrl+1..9, Alt+Up/Down | Missing | |
142 142
143 143 ## Presence and people
144 144
@@ -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: 72 %** (60 done, 3 partial, 22 missing of 85). Partial counts half.
5**Parity: 74 %** (63 done, 2 partial, 21 missing of 86). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -13,9 +13,9 @@ Feature parity with the Microsoft Teams desktop client.
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14| [Writing](#writing) | 100 % | 14 | 0 | 0 |
14| [Writing](#writing) | 100 % | 14 | 0 | 0 |
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) | 57 % | 4 | 0 | 3 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
17| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18| [Search and navigation](#search-and-navigation) | 75 % | 3 | 0 | 1 |
18| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
19| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |
19| [Presence and people](#presence-and-people) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21| [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |
21| [Calls and meetings](#calls-and-meetings) | 0 % | 0 | 0 | 5 |
@@ -24,9 +24,8 @@ Feature parity with the Microsoft Teams desktop client.
24
24
25| # | Feature | Note |
25| # | Feature | Note |
26|---|---|---|
26|---|---|---|
27| 1 | Channel: new post with subject, post cards | |
27| 1 | Sign in on Linux without Chrome on a debug port | |
28| 2 | Sign in on Linux without Chrome on a debug port | |
28| 2 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
29| 3 | Keyboard: Ctrl+1..9, Alt+Up/Down | |
30
29
31## Sign-in and app
30## Sign-in and app
32
31
@@ -111,9 +110,9 @@ Feature parity with the Microsoft Teams desktop client.
111| Feature | State | Note |
110| Feature | State | Note |
112|---|---|---|
111|---|---|---|
113| Teams and channels tree | Done | |
112| Teams and channels tree | Done | |
114| Thread list, open a thread, reply | Done | |
113| Posts feed, open a conversation, reply | Done | Newest activity on top, inline reply in the card |
115| New post with subject | Partial | Backend takes a subject, UI sends none |
114| New post with subject | Done | Subject is stored with the message |
116| Post cards like Teams | Missing | |
115| Post cards like Teams | Done | One card per post: root and the last 3 replies |
117| Follow a channel, per-channel notifications | Missing | |
116| Follow a channel, per-channel notifications | Missing | |
118| Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
117| Channel tabs: tab bar, website and app tabs | Missing | Plan: each tab's Teams Web page in a WebView2 |
119| Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
118| Files tab | Missing | Plan: native, the channel's SharePoint folder via Graph |
@@ -138,7 +137,8 @@ Feature parity with the Microsoft Teams desktop client.
138| Ctrl+K switcher over chats, channels, people | Done | |
137| Ctrl+K switcher over chats, channels, people | Done | |
139| Full-text search over cached messages | Done | |
138| Full-text search over cached messages | Done | |
140| Jump to a message from search | Done | |
139| Jump to a message from search | Done | |
141| Keyboard: Ctrl+1..9, Alt+Up/Down, Esc closes thread | Missing | |
140| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
141| Keyboard: Ctrl+1..9, Alt+Up/Down | Missing | |
142
142
143## Presence and people
143## Presence and people
144
144
crates/app/src/demo.rs +65 −14
@@ -10,8 +10,7 @@ use store::{
10 10 };
11 11 use teams_core::{
12 12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 TaskDialog,
14 TaskDialogKind,
13 TaskDialog, TaskDialogKind,
15 14 };
16 15
17 16 use crate::activity::{Actor, Entry, Kind};
@@ -713,9 +712,15 @@ fn message(
713 712 attachments_json: "[]".to_owned(),
714 713 reactions_json: reactions_json.to_owned(),
715 714 mentions_json: "[]".to_owned(),
715 subject: None,
716 716 }
717 717 }
718 718
719 fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
720 record.subject = Some(subject.to_owned());
721 record
722 }
723
719 724 fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
720 725 record.attachments_json = attachments_json.to_owned();
721 726 record
@@ -1231,11 +1236,52 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1231 1236 .collect()
1232 1237 }
1233 1238
1239 const ROLLOUT_REPLIES: [(&str, &str); 12] = [
1240 (MARA_ID, "Staging looks good on my side."),
1241 (JONAS_ID, "Smoke tests passed, no regressions."),
1242 (PRIYA_ID, "Docs for the new settings page are merged."),
1243 (LEA_ID, "Support is briefed, nothing blocking."),
1244 (MARA_ID, "Can we keep the old export for one more release?"),
1245 (JONAS_ID, "Yes, behind a flag. I will add it today."),
1246 (PRIYA_ID, "Changelog draft is ready for review."),
1247 (LEA_ID, "Customer success wants a heads-up the day before."),
1248 (MARA_ID, "I will send that mail on Thursday."),
1249 (JONAS_ID, "Flag is in, rebuilding staging now."),
1250 (PRIYA_ID, "Rollback steps are in the runbook."),
1251 (LEA_ID, "All green from QA. Go for Friday."),
1252 ];
1253
1234 1254 fn channel_messages() -> Vec<MessageRecord> {
1235 1255 let channel = "demo-channel-1-1";
1236 1256 let mara = (MARA_ID, "Mara Lindqvist");
1237 1257 let tobias = (TOBIAS_ID, "Tobias Klein");
1238 vec![
1258 let people = [
1259 (MARA_ID, "Mara Lindqvist"),
1260 (JONAS_ID, "Jonas Ortega"),
1261 (PRIYA_ID, "Priya Nair"),
1262 (LEA_ID, "Lea Schneider"),
1263 ];
1264 let rollout_replies = ROLLOUT_REPLIES
1265 .iter()
1266 .enumerate()
1267 .map(|(index, (sender, text))| {
1268 let sender = people
1269 .iter()
1270 .copied()
1271 .find(|(id, _)| id == sender)
1272 .expect("known person");
1273 message(
1274 channel,
1275 &format!("t3r{}", index + 1),
1276 Some("t3"),
1277 sender,
1278 at(0, 9, 40) + Duration::minutes(6 * index as i64),
1279 &format!("<p>{text}</p>"),
1280 "[]",
1281 false,
1282 )
1283 });
1284 let mut records = vec![
1239 1285 message(
1240 1286 channel,
1241 1287 "t1",
@@ -1256,22 +1302,25 @@ fn channel_messages() -> Vec<MessageRecord> {
1256 1302 "[]",
1257 1303 false,
1258 1304 ),
1259 message(
1260 channel,
1261 "t3",
1262 None,
1263 tobias,
1264 at(0, 11, 30),
1265 "<p>Release build 42 is green, deploying to staging now.</p>",
1266 "[]",
1267 false,
1305 with_subject(
1306 message(
1307 channel,
1308 "t3",
1309 None,
1310 tobias,
1311 at(0, 9, 30),
1312 "<p>Release build 42 is green, deploying to staging now.</p>",
1313 "[]",
1314 false,
1315 ),
1316 "Release 42 rollout",
1268 1317 ),
1269 1318 message(
1270 1319 channel,
1271 1320 "t2",
1272 1321 None,
1273 1322 tobias,
1274 at(0, 11, 0),
1323 at(0, 10, 0),
1275 1324 "<p>Who owns the on-call handover?</p>",
1276 1325 "[]",
1277 1326 false,
@@ -1296,7 +1345,9 @@ fn channel_messages() -> Vec<MessageRecord> {
1296 1345 "[]",
1297 1346 false,
1298 1347 ),
1299 ]
1348 ];
1349 records.extend(rollout_replies);
1350 records
1300 1351 }
1301 1352
1302 1353 fn crc32(bytes: &[u8]) -> u32 {
@@ -10,8 +10,7 @@ use store::{
10};
10};
11use teams_core::{
11use teams_core::{
12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
12 CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13 TaskDialog,
13 TaskDialog, TaskDialogKind,
14 TaskDialogKind,
15};
14};
16
15
17use crate::activity::{Actor, Entry, Kind};
16use crate::activity::{Actor, Entry, Kind};
@@ -713,9 +712,15 @@ fn message(
713 attachments_json: "[]".to_owned(),
712 attachments_json: "[]".to_owned(),
714 reactions_json: reactions_json.to_owned(),
713 reactions_json: reactions_json.to_owned(),
715 mentions_json: "[]".to_owned(),
714 mentions_json: "[]".to_owned(),
715 subject: None,
716 }
716 }
717}
717}
718
718
719fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
720 record.subject = Some(subject.to_owned());
721 record
722}
723
719fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
724fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
720 record.attachments_json = attachments_json.to_owned();
725 record.attachments_json = attachments_json.to_owned();
721 record
726 record
@@ -1231,11 +1236,52 @@ fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1231 .collect()
1236 .collect()
1232}
1237}
1233
1238
1239const ROLLOUT_REPLIES: [(&str, &str); 12] = [
1240 (MARA_ID, "Staging looks good on my side."),
1241 (JONAS_ID, "Smoke tests passed, no regressions."),
1242 (PRIYA_ID, "Docs for the new settings page are merged."),
1243 (LEA_ID, "Support is briefed, nothing blocking."),
1244 (MARA_ID, "Can we keep the old export for one more release?"),
1245 (JONAS_ID, "Yes, behind a flag. I will add it today."),
1246 (PRIYA_ID, "Changelog draft is ready for review."),
1247 (LEA_ID, "Customer success wants a heads-up the day before."),
1248 (MARA_ID, "I will send that mail on Thursday."),
1249 (JONAS_ID, "Flag is in, rebuilding staging now."),
1250 (PRIYA_ID, "Rollback steps are in the runbook."),
1251 (LEA_ID, "All green from QA. Go for Friday."),
1252];
1253
1234fn channel_messages() -> Vec<MessageRecord> {
1254fn channel_messages() -> Vec<MessageRecord> {
1235 let channel = "demo-channel-1-1";
1255 let channel = "demo-channel-1-1";
1236 let mara = (MARA_ID, "Mara Lindqvist");
1256 let mara = (MARA_ID, "Mara Lindqvist");
1237 let tobias = (TOBIAS_ID, "Tobias Klein");
1257 let tobias = (TOBIAS_ID, "Tobias Klein");
1238 vec![
1258 let people = [
1259 (MARA_ID, "Mara Lindqvist"),
1260 (JONAS_ID, "Jonas Ortega"),
1261 (PRIYA_ID, "Priya Nair"),
1262 (LEA_ID, "Lea Schneider"),
1263 ];
1264 let rollout_replies = ROLLOUT_REPLIES
1265 .iter()
1266 .enumerate()
1267 .map(|(index, (sender, text))| {
1268 let sender = people
1269 .iter()
1270 .copied()
1271 .find(|(id, _)| id == sender)
1272 .expect("known person");
1273 message(
1274 channel,
1275 &format!("t3r{}", index + 1),
1276 Some("t3"),
1277 sender,
1278 at(0, 9, 40) + Duration::minutes(6 * index as i64),
1279 &format!("<p>{text}</p>"),
1280 "[]",
1281 false,
1282 )
1283 });
1284 let mut records = vec![
1239 message(
1285 message(
1240 channel,
1286 channel,
1241 "t1",
1287 "t1",
@@ -1256,22 +1302,25 @@ fn channel_messages() -> Vec<MessageRecord> {
1256 "[]",
1302 "[]",
1257 false,
1303 false,
1258 ),
1304 ),
1259 message(
1305 with_subject(
1260 channel,
1306 message(
1261 "t3",
1307 channel,
1262 None,
1308 "t3",
1263 tobias,
1309 None,
1264 at(0, 11, 30),
1310 tobias,
1265 "<p>Release build 42 is green, deploying to staging now.</p>",
1311 at(0, 9, 30),
1266 "[]",
1312 "<p>Release build 42 is green, deploying to staging now.</p>",
1267 false,
1313 "[]",
1314 false,
1315 ),
1316 "Release 42 rollout",
1268 ),
1317 ),
1269 message(
1318 message(
1270 channel,
1319 channel,
1271 "t2",
1320 "t2",
1272 None,
1321 None,
1273 tobias,
1322 tobias,
1274 at(0, 11, 0),
1323 at(0, 10, 0),
1275 "<p>Who owns the on-call handover?</p>",
1324 "<p>Who owns the on-call handover?</p>",
1276 "[]",
1325 "[]",
1277 false,
1326 false,
@@ -1296,7 +1345,9 @@ fn channel_messages() -> Vec<MessageRecord> {
1296 "[]",
1345 "[]",
1297 false,
1346 false,
1298 ),
1347 ),
1299 ]
1348 ];
1349 records.extend(rollout_replies);
1350 records
1300}
1351}
1301
1352
1302fn crc32(bytes: &[u8]) -> u32 {
1353fn crc32(bytes: &[u8]) -> u32 {
crates/app/src/notify/incoming.rs +1 −0
@@ -265,6 +265,7 @@ mod tests {
265 265
266 266 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
267 267 MessageRecord {
268 subject: None,
268 269 conversation_id: conversation.into(),
269 270 message_id: format!("{conversation}-{}", at.timestamp_millis()),
270 271 reply_to_id: None,
@@ -265,6 +265,7 @@ mod tests {
265
265
266 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
266 fn record(conversation: &str, sender: &str, at: DateTime<Utc>, html: &str) -> MessageRecord {
267 MessageRecord {
267 MessageRecord {
268 subject: None,
268 conversation_id: conversation.into(),
269 conversation_id: conversation.into(),
269 message_id: format!("{conversation}-{}", at.timestamp_millis()),
270 message_id: format!("{conversation}-{}", at.timestamp_millis()),
270 reply_to_id: None,
271 reply_to_id: None,
crates/app/src/outbox.rs +7 −1
@@ -74,7 +74,13 @@ pub async fn deliver(
74 74 }
75 75 (OutboxTarget::Post, None) => {
76 76 engine
77 .post_to_channel_with_extras(conversation_id, &html, None, mentions, &extras)
77 .post_to_channel_with_extras(
78 conversation_id,
79 &html,
80 outgoing.subject.as_deref(),
81 mentions,
82 &extras,
83 )
78 84 .await
79 85 }
80 86 (OutboxTarget::Thread, None) => {
@@ -74,7 +74,13 @@ pub async fn deliver(
74 }
74 }
75 (OutboxTarget::Post, None) => {
75 (OutboxTarget::Post, None) => {
76 engine
76 engine
77 .post_to_channel_with_extras(conversation_id, &html, None, mentions, &extras)
77 .post_to_channel_with_extras(
78 conversation_id,
79 &html,
80 outgoing.subject.as_deref(),
81 mentions,
82 &extras,
83 )
78 .await
84 .await
79 }
85 }
80 (OutboxTarget::Thread, None) => {
86 (OutboxTarget::Thread, None) => {
crates/app/src/pending_rows.rs +2 −6
@@ -22,7 +22,6 @@ pub fn pending_row(
22 22 application_id: None,
23 23 created_at,
24 24 series: Series::default(),
25 card: false,
26 25 time: created_at.with_timezone(&Local).format("%H:%M").to_string(),
27 26 day_header: None,
28 27 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
@@ -65,12 +64,9 @@ pub fn pending_row(
65 64 open_url: file.reference.content_url.clone(),
66 65 })
67 66 .collect(),
68 reply_count: None,
67 subject: outgoing.subject.clone(),
69 68 new_marker: false,
70 reply_faces: Vec::new(),
71 last_reply_time: None,
72 open_thread: None,
73 is_reply: false,
69 reply_root: None,
74 70 delivery,
75 71 receipt: Receipt::Hidden,
76 72 own: true,
@@ -22,7 +22,6 @@ pub fn pending_row(
22 application_id: None,
22 application_id: None,
23 created_at,
23 created_at,
24 series: Series::default(),
24 series: Series::default(),
25 card: false,
26 time: created_at.with_timezone(&Local).format("%H:%M").to_string(),
25 time: created_at.with_timezone(&Local).format("%H:%M").to_string(),
27 day_header: None,
26 day_header: None,
28 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
27 blocks: if outgoing.draft.is_blank() && outgoing.images.is_empty() {
@@ -65,12 +64,9 @@ pub fn pending_row(
65 open_url: file.reference.content_url.clone(),
64 open_url: file.reference.content_url.clone(),
66 })
65 })
67 .collect(),
66 .collect(),
68 reply_count: None,
67 subject: outgoing.subject.clone(),
69 new_marker: false,
68 new_marker: false,
70 reply_faces: Vec::new(),
69 reply_root: None,
71 last_reply_time: None,
72 open_thread: None,
73 is_reply: false,
74 delivery,
70 delivery,
75 receipt: Receipt::Hidden,
71 receipt: Receipt::Hidden,
76 own: true,
72 own: true,
crates/app/src/rows.rs +275 −80
@@ -15,9 +15,8 @@ use crate::format;
15 15 use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
16 16 use crate::render::blocks::{Inline, strip_image_placeholders};
17 17 use crate::render::{Block, layout_blocks};
18 use crate::sidebar_model::Face;
19 18
20 const REPLY_FACE_LIMIT: usize = 3;
19 const POST_VISIBLE_REPLIES: usize = 3;
21 20
22 21 pub const LOAD_OLDER_KEY: &str = "load-older";
23 22 const UNKNOWN_AUTHOR: &str = "Unknown";
@@ -127,7 +126,6 @@ pub struct MessageRow {
127 126 pub application_id: Option<String>,
128 127 pub created_at: DateTime<Utc>,
129 128 pub series: Series,
130 pub card: bool,
131 129 pub time: String,
132 130 pub day_header: Option<String>,
133 131 pub blocks: Vec<Block>,
@@ -139,12 +137,9 @@ pub struct MessageRow {
139 137 pub files: Vec<FileCard>,
140 138 pub link_preview: Option<LinkPreview>,
141 139 pub adaptive_cards: Vec<AdaptiveCard>,
142 pub reply_count: Option<usize>,
140 pub subject: Option<String>,
143 141 pub new_marker: bool,
144 pub reply_faces: Vec<Face>,
145 pub last_reply_time: Option<String>,
146 pub open_thread: Option<String>,
147 pub is_reply: bool,
142 pub reply_root: Option<String>,
148 143 pub delivery: Delivery,
149 144 pub own: bool,
150 145 pub receipt: Receipt,
@@ -164,6 +159,7 @@ pub enum Row {
164 159 Start(StartInfo),
165 160 Skeleton(Skeleton),
166 161 Message(Box<MessageRow>),
162 Post(Box<PostRow>),
167 163 }
168 164
169 165 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -213,9 +209,7 @@ fn sender_key(row: &MessageRow) -> &str {
213 209 }
214 210
215 211 fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
216 !previous.card
217 && !next.card
218 && next.day_header.is_none()
212 next.day_header.is_none()
219 213 && !next.new_marker
220 214 && sender_key(previous) == sender_key(next)
221 215 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
@@ -254,8 +248,67 @@ impl Row {
254 248 Row::Start(_) => START_KEY,
255 249 Row::Skeleton(skeleton) => skeleton.key,
256 250 Row::Message(message) => &message.key,
251 Row::Post(post) => &post.root.key,
257 252 }
258 253 }
254
255 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
256 match self {
257 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
258 Row::Post(post) => Box::new(post.messages()),
259 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
260 }
261 }
262 }
263
264 #[derive(Debug, Clone, PartialEq)]
265 pub struct PostRow {
266 pub root: MessageRow,
267 pub replies: Vec<MessageRow>,
268 pub hidden_reply_count: usize,
269 pub hidden_repliers: Vec<String>,
270 }
271
272 impl PostRow {
273 pub fn local(root: MessageRow) -> Self {
274 PostRow {
275 root,
276 replies: Vec::new(),
277 hidden_reply_count: 0,
278 hidden_repliers: Vec::new(),
279 }
280 }
281
282 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
283 std::iter::once(&self.root).chain(&self.replies)
284 }
285
286 pub fn hidden_replies_label(&self) -> Option<String> {
287 (self.hidden_reply_count > 0)
288 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
289 }
290 }
291
292 fn first_name(name: &str) -> &str {
293 name.split_whitespace().next().unwrap_or(name)
294 }
295
296 pub fn replies_label(count: usize, repliers: &[String]) -> String {
297 let noun = if count == 1 { "reply" } else { "replies" };
298 let mut names: Vec<&str> = Vec::new();
299 for name in repliers.iter().map(|name| first_name(name)) {
300 if !names.contains(&name) {
301 names.push(name);
302 }
303 }
304 let people = match names.as_slice() {
305 [] => return format!("{count} {noun}"),
306 [only] => (*only).to_owned(),
307 [first, second] => format!("{first} and {second}"),
308 [first, second, third] => format!("{first}, {second} and {third}"),
309 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
310 };
311 format!("{count} {noun} from {people}")
259 312 }
260 313
261 314 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -488,7 +541,6 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
488 541 application_id: record.sender_application_id.clone(),
489 542 created_at: record.created_at,
490 543 series: Series::default(),
491 card: false,
492 544 author: record
493 545 .sender_name
494 546 .clone()
@@ -507,12 +559,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
507 559 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
508 560 _ => adaptive_cards(record),
509 561 },
510 reply_count: None,
562 subject: record.subject.clone(),
511 563 new_marker: false,
512 reply_faces: Vec::new(),
513 last_reply_time: None,
514 open_thread: None,
515 is_reply: record.reply_to_id.is_some(),
564 reply_root: record.reply_to_id.clone(),
516 565 delivery: Delivery::Delivered,
517 566 receipt: Receipt::Hidden,
518 567 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
@@ -573,6 +622,45 @@ fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> Dat
573 622 .unwrap_or_default()
574 623 }
575 624
625 fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
626 let mut row = message_row(record, context);
627 row.day_header = None;
628 row.time = format::post_time_label(record.created_at, context.today, context.offset);
629 row
630 }
631
632 fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
633 let mut names: Vec<String> = Vec::new();
634 for record in records {
635 let name = record
636 .sender_name
637 .clone()
638 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
639 if !names.contains(&name) {
640 names.push(name);
641 }
642 }
643 names
644 }
645
646 fn post_row(
647 root: &MessageRecord,
648 mut replies: Vec<&MessageRecord>,
649 context: &RowContext,
650 ) -> PostRow {
651 replies.sort_by_key(|reply| reply.created_at);
652 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
653 PostRow {
654 root: post_message_row(root, context),
655 hidden_reply_count: hidden,
656 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
657 replies: replies[hidden..]
658 .iter()
659 .map(|reply| post_message_row(reply, context))
660 .collect(),
661 }
662 }
663
576 664 pub fn thread_list_rows(
577 665 records: &[MessageRecord],
578 666 context: &RowContext,
@@ -583,58 +671,42 @@ pub fn thread_list_rows(
583 671 .map(|record| (record.message_id.as_str(), record))
584 672 .collect();
585 673 let mut threads = group_threads(records);
586 threads.sort_by_key(|thread| last_activity(thread, &by_id));
587 let mut rows = Vec::with_capacity(threads.len() + 1);
674 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id)));
675 let mut rows: Vec<Row> = threads
676 .iter()
677 .filter_map(|thread| {
678 let root = by_id.get(thread.root_id.as_str())?;
679 let replies = thread
680 .reply_ids
681 .iter()
682 .filter_map(|id| by_id.get(id.as_str()).copied())
683 .collect();
684 Some(Row::Post(Box::new(post_row(root, replies, context))))
685 })
686 .collect();
588 687 if has_older {
589 688 rows.push(Row::LoadOlder);
590 689 }
591 let mut previous_day: Option<NaiveDate> = None;
592 for thread in threads {
593 let Some(root) = by_id.get(thread.root_id.as_str()) else {
690 rows
691 }
692
693 pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
694 for message in local {
695 let Some(root_id) = message.reply_root.clone() else {
696 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
594 697 continue;
595 698 };
596 let mut row = message_row(root, context);
597 let day = last_activity(&thread, &by_id)
598 .with_timezone(&context.offset)
599 .date_naive();
600 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
601 previous_day = Some(day);
602 row.card = true;
603 row.time = format::post_time_label(root.created_at, context.today, context.offset);
604 row.reply_count = Some(thread.reply_ids.len());
605 let replies: Vec<&&MessageRecord> = thread
606 .reply_ids
699 let position = rows
607 700 .iter()
608 .filter_map(|id| by_id.get(id.as_str()))
609 .collect();
610 for reply in &replies {
611 let face = Face {
612 user_id: reply.sender_id.clone(),
613 name: reply
614 .sender_name
615 .clone()
616 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
617 };
618 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
619 row.reply_faces.push(face);
701 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
702 if let Some(position) = position {
703 let mut row = rows.remove(position);
704 if let Row::Post(post) = &mut row {
705 post.replies.push(message);
620 706 }
707 rows.insert(0, row);
621 708 }
622 row.last_reply_time = replies
623 .iter()
624 .map(|reply| reply.created_at)
625 .max()
626 .map(|time| {
627 let local = time.with_timezone(&context.offset);
628 format!(
629 "{} {}",
630 format::day_label(local.date_naive(), context.today),
631 clock_label(time, context.offset)
632 )
633 });
634 row.open_thread = Some(thread.root_id.clone());
635 rows.push(Row::Message(Box::new(row)));
636 709 }
637 rows
638 710 }
639 711
640 712 pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
@@ -720,6 +792,7 @@ mod tests {
720 792 attachments_json: "[]".into(),
721 793 reactions_json: "[]".into(),
722 794 mentions_json: "[]".into(),
795 subject: None,
723 796 }
724 797 }
725 798
@@ -860,7 +933,7 @@ mod tests {
860 933 .iter()
861 934 .map(|row| match row {
862 935 Row::Message(message) => message.day_header.clone(),
863 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
936 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
864 937 })
865 938 .collect();
866 939 assert_eq!(
@@ -894,20 +967,152 @@ mod tests {
894 967 assert!(threads[1].reply_ids.is_empty());
895 968 }
896 969
970 fn post_of(row: &Row) -> &PostRow {
971 let Row::Post(post) = row else {
972 panic!("post expected")
973 };
974 post
975 }
976
977 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
978 let mut reply = record(id, Some(root), hour, 6);
979 reply.sender_name = Some(sender.into());
980 reply
981 }
982
897 983 #[test]
898 fn thread_list_orders_by_last_activity_with_reply_count() {
984 fn feed_orders_posts_by_last_activity_newest_first() {
899 985 let records = vec![
900 986 record("r1", None, 8, 6),
901 987 record("r2", None, 9, 6),
902 record("x1", Some("r1"), 10, 6),
988 record("r3", None, 10, 6),
989 record("x1", Some("r1"), 11, 6),
903 990 ];
904 991 let rows = thread_list_rows(&records, &context(), false);
905 assert_eq!(keys(&rows), vec!["r2", "r1"]);
906 let Row::Message(last) = &rows[1] else {
907 panic!("message expected")
908 };
909 assert_eq!(last.reply_count, Some(1));
910 assert_eq!(last.open_thread.as_deref(), Some("r1"));
992 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
993 }
994
995 #[test]
996 fn feed_puts_load_older_at_the_bottom() {
997 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
998 let rows = thread_list_rows(&records, &context(), true);
999 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1000 }
1001
1002 #[test]
1003 fn post_shows_the_last_three_replies_oldest_first() {
1004 let mut records = vec![record("r1", None, 1, 6)];
1005 for hour in 2..=6 {
1006 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1007 }
1008 records.reverse();
1009 let rows = thread_list_rows(&records, &context(), false);
1010 let post = post_of(&rows[0]);
1011 let shown: Vec<&str> = post
1012 .replies
1013 .iter()
1014 .map(|reply| reply.key.as_str())
1015 .collect();
1016 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1017 assert_eq!(post.hidden_reply_count, 2);
1018 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1019 }
1020
1021 #[test]
1022 fn post_without_hidden_replies_has_no_link() {
1023 let records = vec![
1024 record("r1", None, 1, 6),
1025 reply_by("x1", "r1", "Ada", 2),
1026 reply_by("x2", "r1", "Ben", 3),
1027 reply_by("x3", "r1", "Cy", 4),
1028 ];
1029 let rows = thread_list_rows(&records, &context(), false);
1030 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1031 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1032 }
1033
1034 fn label_for(repliers: &[&str]) -> String {
1035 let mut records = vec![record("r1", None, 1, 6)];
1036 for (index, name) in repliers.iter().enumerate() {
1037 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1038 }
1039 for index in 0..POST_VISIBLE_REPLIES {
1040 records.push(reply_by(
1041 &format!("v{index}"),
1042 "r1",
1043 "Shown",
1044 20 + index as u32,
1045 ));
1046 }
1047 let rows = thread_list_rows(&records, &context(), false);
1048 post_of(&rows[0]).hidden_replies_label().unwrap()
1049 }
1050
1051 #[test]
1052 fn replies_label_names_one_to_three_people() {
1053 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1054 assert_eq!(
1055 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1056 "3 replies from Anna and Ben"
1057 );
1058 assert_eq!(
1059 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1060 "4 replies from Anna, Ben and Clara"
1061 );
1062 }
1063
1064 #[test]
1065 fn replies_label_counts_the_others_beyond_three_people() {
1066 assert_eq!(
1067 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1068 "5 replies from Anna, Ben and 3 others"
1069 );
1070 assert_eq!(
1071 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1072 "4 replies from Anna, Ben and 2 others"
1073 );
1074 }
1075
1076 #[test]
1077 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1078 let records = vec![
1079 record("r1", None, 8, 6),
1080 record("r2", None, 9, 6),
1081 reply_by("x1", "r1", "Ada", 10),
1082 ];
1083 let mut rows = thread_list_rows(&records, &context(), true);
1084 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1085 pending_reply.reply_root = Some("r2".into());
1086 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1087 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1088 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1089 let replies: Vec<&str> = post_of(&rows[1])
1090 .replies
1091 .iter()
1092 .map(|reply| reply.key.as_str())
1093 .collect();
1094 assert_eq!(replies, vec!["pending-1"]);
1095 }
1096
1097 #[test]
1098 fn local_reply_to_an_unloaded_post_is_not_shown() {
1099 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1100 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1101 orphan.reply_root = Some("gone".into());
1102 place_local_rows(&mut rows, vec![orphan]);
1103 assert_eq!(keys(&rows), vec!["r1"]);
1104 }
1105
1106 #[test]
1107 fn subject_reaches_the_post_root() {
1108 let mut with_subject = record("r1", None, 8, 6);
1109 with_subject.subject = Some("Release plan".into());
1110 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1111 assert_eq!(
1112 post_of(&rows[0]).root.subject.as_deref(),
1113 Some("Release plan")
1114 );
1115 assert_eq!(post_of(&rows[1]).root.subject, None);
911 1116 }
912 1117
913 1118 #[test]
@@ -989,7 +1194,7 @@ mod tests {
989 1194 rows.iter()
990 1195 .filter_map(|row| match row {
991 1196 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
992 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
1197 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
993 1198 })
994 1199 .collect()
995 1200 }
@@ -1041,16 +1246,6 @@ mod tests {
1041 1246 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1042 1247 }
1043 1248
1044 #[test]
1045 fn thread_list_rows_never_join() {
1046 let records = vec![
1047 record_by("a", "ada", 9, 0, 7),
1048 record_by("b", "ada", 9, 1, 7),
1049 ];
1050 let rows = thread_list_rows(&records, &context(), false);
1051 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1052 }
1053
1054 1249 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1055 1250 let corners = bubble_corners(own, Series { has_prev, has_next });
1056 1251 [
@@ -15,9 +15,8 @@ use crate::format;
15use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
15use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
16use crate::render::blocks::{Inline, strip_image_placeholders};
16use crate::render::blocks::{Inline, strip_image_placeholders};
17use crate::render::{Block, layout_blocks};
17use crate::render::{Block, layout_blocks};
18use crate::sidebar_model::Face;
19
18
20const REPLY_FACE_LIMIT: usize = 3;
19const POST_VISIBLE_REPLIES: usize = 3;
21
20
22pub const LOAD_OLDER_KEY: &str = "load-older";
21pub const LOAD_OLDER_KEY: &str = "load-older";
23const UNKNOWN_AUTHOR: &str = "Unknown";
22const UNKNOWN_AUTHOR: &str = "Unknown";
@@ -127,7 +126,6 @@ pub struct MessageRow {
127 pub application_id: Option<String>,
126 pub application_id: Option<String>,
128 pub created_at: DateTime<Utc>,
127 pub created_at: DateTime<Utc>,
129 pub series: Series,
128 pub series: Series,
130 pub card: bool,
131 pub time: String,
129 pub time: String,
132 pub day_header: Option<String>,
130 pub day_header: Option<String>,
133 pub blocks: Vec<Block>,
131 pub blocks: Vec<Block>,
@@ -139,12 +137,9 @@ pub struct MessageRow {
139 pub files: Vec<FileCard>,
137 pub files: Vec<FileCard>,
140 pub link_preview: Option<LinkPreview>,
138 pub link_preview: Option<LinkPreview>,
141 pub adaptive_cards: Vec<AdaptiveCard>,
139 pub adaptive_cards: Vec<AdaptiveCard>,
142 pub reply_count: Option<usize>,
140 pub subject: Option<String>,
143 pub new_marker: bool,
141 pub new_marker: bool,
144 pub reply_faces: Vec<Face>,
142 pub reply_root: Option<String>,
145 pub last_reply_time: Option<String>,
146 pub open_thread: Option<String>,
147 pub is_reply: bool,
148 pub delivery: Delivery,
143 pub delivery: Delivery,
149 pub own: bool,
144 pub own: bool,
150 pub receipt: Receipt,
145 pub receipt: Receipt,
@@ -164,6 +159,7 @@ pub enum Row {
164 Start(StartInfo),
159 Start(StartInfo),
165 Skeleton(Skeleton),
160 Skeleton(Skeleton),
166 Message(Box<MessageRow>),
161 Message(Box<MessageRow>),
162 Post(Box<PostRow>),
167}
163}
168
164
169#[derive(Debug, Clone, Copy, PartialEq)]
165#[derive(Debug, Clone, Copy, PartialEq)]
@@ -213,9 +209,7 @@ fn sender_key(row: &MessageRow) -> &str {
213}
209}
214
210
215fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
211fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
216 !previous.card
212 next.day_header.is_none()
217 && !next.card
218 && next.day_header.is_none()
219 && !next.new_marker
213 && !next.new_marker
220 && sender_key(previous) == sender_key(next)
214 && sender_key(previous) == sender_key(next)
221 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
215 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
@@ -254,8 +248,67 @@ impl Row {
254 Row::Start(_) => START_KEY,
248 Row::Start(_) => START_KEY,
255 Row::Skeleton(skeleton) => skeleton.key,
249 Row::Skeleton(skeleton) => skeleton.key,
256 Row::Message(message) => &message.key,
250 Row::Message(message) => &message.key,
251 Row::Post(post) => &post.root.key,
257 }
252 }
258 }
253 }
254
255 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
256 match self {
257 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
258 Row::Post(post) => Box::new(post.messages()),
259 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => Box::new(std::iter::empty()),
260 }
261 }
262}
263
264#[derive(Debug, Clone, PartialEq)]
265pub struct PostRow {
266 pub root: MessageRow,
267 pub replies: Vec<MessageRow>,
268 pub hidden_reply_count: usize,
269 pub hidden_repliers: Vec<String>,
270}
271
272impl PostRow {
273 pub fn local(root: MessageRow) -> Self {
274 PostRow {
275 root,
276 replies: Vec::new(),
277 hidden_reply_count: 0,
278 hidden_repliers: Vec::new(),
279 }
280 }
281
282 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
283 std::iter::once(&self.root).chain(&self.replies)
284 }
285
286 pub fn hidden_replies_label(&self) -> Option<String> {
287 (self.hidden_reply_count > 0)
288 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
289 }
290}
291
292fn first_name(name: &str) -> &str {
293 name.split_whitespace().next().unwrap_or(name)
294}
295
296pub fn replies_label(count: usize, repliers: &[String]) -> String {
297 let noun = if count == 1 { "reply" } else { "replies" };
298 let mut names: Vec<&str> = Vec::new();
299 for name in repliers.iter().map(|name| first_name(name)) {
300 if !names.contains(&name) {
301 names.push(name);
302 }
303 }
304 let people = match names.as_slice() {
305 [] => return format!("{count} {noun}"),
306 [only] => (*only).to_owned(),
307 [first, second] => format!("{first} and {second}"),
308 [first, second, third] => format!("{first}, {second} and {third}"),
309 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
310 };
311 format!("{count} {noun} from {people}")
259}
312}
260
313
261#[derive(Debug, Clone, PartialEq, Eq)]
314#[derive(Debug, Clone, PartialEq, Eq)]
@@ -488,7 +541,6 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
488 application_id: record.sender_application_id.clone(),
541 application_id: record.sender_application_id.clone(),
489 created_at: record.created_at,
542 created_at: record.created_at,
490 series: Series::default(),
543 series: Series::default(),
491 card: false,
492 author: record
544 author: record
493 .sender_name
545 .sender_name
494 .clone()
546 .clone()
@@ -507,12 +559,9 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
507 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
559 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
508 _ => adaptive_cards(record),
560 _ => adaptive_cards(record),
509 },
561 },
510 reply_count: None,
562 subject: record.subject.clone(),
511 new_marker: false,
563 new_marker: false,
512 reply_faces: Vec::new(),
564 reply_root: record.reply_to_id.clone(),
513 last_reply_time: None,
514 open_thread: None,
515 is_reply: record.reply_to_id.is_some(),
516 delivery: Delivery::Delivered,
565 delivery: Delivery::Delivered,
517 receipt: Receipt::Hidden,
566 receipt: Receipt::Hidden,
518 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
567 own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
@@ -573,6 +622,45 @@ fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> Dat
573 .unwrap_or_default()
622 .unwrap_or_default()
574}
623}
575
624
625fn post_message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
626 let mut row = message_row(record, context);
627 row.day_header = None;
628 row.time = format::post_time_label(record.created_at, context.today, context.offset);
629 row
630}
631
632fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
633 let mut names: Vec<String> = Vec::new();
634 for record in records {
635 let name = record
636 .sender_name
637 .clone()
638 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
639 if !names.contains(&name) {
640 names.push(name);
641 }
642 }
643 names
644}
645
646fn post_row(
647 root: &MessageRecord,
648 mut replies: Vec<&MessageRecord>,
649 context: &RowContext,
650) -> PostRow {
651 replies.sort_by_key(|reply| reply.created_at);
652 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
653 PostRow {
654 root: post_message_row(root, context),
655 hidden_reply_count: hidden,
656 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
657 replies: replies[hidden..]
658 .iter()
659 .map(|reply| post_message_row(reply, context))
660 .collect(),
661 }
662}
663
576pub fn thread_list_rows(
664pub fn thread_list_rows(
577 records: &[MessageRecord],
665 records: &[MessageRecord],
578 context: &RowContext,
666 context: &RowContext,
@@ -583,58 +671,42 @@ pub fn thread_list_rows(
583 .map(|record| (record.message_id.as_str(), record))
671 .map(|record| (record.message_id.as_str(), record))
584 .collect();
672 .collect();
585 let mut threads = group_threads(records);
673 let mut threads = group_threads(records);
586 threads.sort_by_key(|thread| last_activity(thread, &by_id));
674 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &by_id)));
587 let mut rows = Vec::with_capacity(threads.len() + 1);
675 let mut rows: Vec<Row> = threads
676 .iter()
677 .filter_map(|thread| {
678 let root = by_id.get(thread.root_id.as_str())?;
679 let replies = thread
680 .reply_ids
681 .iter()
682 .filter_map(|id| by_id.get(id.as_str()).copied())
683 .collect();
684 Some(Row::Post(Box::new(post_row(root, replies, context))))
685 })
686 .collect();
588 if has_older {
687 if has_older {
589 rows.push(Row::LoadOlder);
688 rows.push(Row::LoadOlder);
590 }
689 }
591 let mut previous_day: Option<NaiveDate> = None;
690 rows
592 for thread in threads {
691}
593 let Some(root) = by_id.get(thread.root_id.as_str()) else {
692
693pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
694 for message in local {
695 let Some(root_id) = message.reply_root.clone() else {
696 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
594 continue;
697 continue;
595 };
698 };
596 let mut row = message_row(root, context);
699 let position = rows
597 let day = last_activity(&thread, &by_id)
598 .with_timezone(&context.offset)
599 .date_naive();
600 row.day_header = (previous_day != Some(day)).then(|| format::day_label(day, context.today));
601 previous_day = Some(day);
602 row.card = true;
603 row.time = format::post_time_label(root.created_at, context.today, context.offset);
604 row.reply_count = Some(thread.reply_ids.len());
605 let replies: Vec<&&MessageRecord> = thread
606 .reply_ids
607 .iter()
700 .iter()
608 .filter_map(|id| by_id.get(id.as_str()))
701 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
609 .collect();
702 if let Some(position) = position {
610 for reply in &replies {
703 let mut row = rows.remove(position);
611 let face = Face {
704 if let Row::Post(post) = &mut row {
612 user_id: reply.sender_id.clone(),
705 post.replies.push(message);
613 name: reply
614 .sender_name
615 .clone()
616 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
617 };
618 if row.reply_faces.len() < REPLY_FACE_LIMIT && !row.reply_faces.contains(&face) {
619 row.reply_faces.push(face);
620 }
706 }
707 rows.insert(0, row);
621 }
708 }
622 row.last_reply_time = replies
623 .iter()
624 .map(|reply| reply.created_at)
625 .max()
626 .map(|time| {
627 let local = time.with_timezone(&context.offset);
628 format!(
629 "{} {}",
630 format::day_label(local.date_naive(), context.today),
631 clock_label(time, context.offset)
632 )
633 });
634 row.open_thread = Some(thread.root_id.clone());
635 rows.push(Row::Message(Box::new(row)));
636 }
709 }
637 rows
638}
710}
639
711
640pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
712pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
@@ -720,6 +792,7 @@ mod tests {
720 attachments_json: "[]".into(),
792 attachments_json: "[]".into(),
721 reactions_json: "[]".into(),
793 reactions_json: "[]".into(),
722 mentions_json: "[]".into(),
794 mentions_json: "[]".into(),
795 subject: None,
723 }
796 }
724 }
797 }
725
798
@@ -860,7 +933,7 @@ mod tests {
860 .iter()
933 .iter()
861 .map(|row| match row {
934 .map(|row| match row {
862 Row::Message(message) => message.day_header.clone(),
935 Row::Message(message) => message.day_header.clone(),
863 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
936 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
864 })
937 })
865 .collect();
938 .collect();
866 assert_eq!(
939 assert_eq!(
@@ -894,20 +967,152 @@ mod tests {
894 assert!(threads[1].reply_ids.is_empty());
967 assert!(threads[1].reply_ids.is_empty());
895 }
968 }
896
969
970 fn post_of(row: &Row) -> &PostRow {
971 let Row::Post(post) = row else {
972 panic!("post expected")
973 };
974 post
975 }
976
977 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
978 let mut reply = record(id, Some(root), hour, 6);
979 reply.sender_name = Some(sender.into());
980 reply
981 }
982
897 #[test]
983 #[test]
898 fn thread_list_orders_by_last_activity_with_reply_count() {
984 fn feed_orders_posts_by_last_activity_newest_first() {
899 let records = vec![
985 let records = vec![
900 record("r1", None, 8, 6),
986 record("r1", None, 8, 6),
901 record("r2", None, 9, 6),
987 record("r2", None, 9, 6),
902 record("x1", Some("r1"), 10, 6),
988 record("r3", None, 10, 6),
989 record("x1", Some("r1"), 11, 6),
903 ];
990 ];
904 let rows = thread_list_rows(&records, &context(), false);
991 let rows = thread_list_rows(&records, &context(), false);
905 assert_eq!(keys(&rows), vec!["r2", "r1"]);
992 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
906 let Row::Message(last) = &rows[1] else {
993 }
907 panic!("message expected")
994
908 };
995 #[test]
909 assert_eq!(last.reply_count, Some(1));
996 fn feed_puts_load_older_at_the_bottom() {
910 assert_eq!(last.open_thread.as_deref(), Some("r1"));
997 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
998 let rows = thread_list_rows(&records, &context(), true);
999 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1000 }
1001
1002 #[test]
1003 fn post_shows_the_last_three_replies_oldest_first() {
1004 let mut records = vec![record("r1", None, 1, 6)];
1005 for hour in 2..=6 {
1006 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1007 }
1008 records.reverse();
1009 let rows = thread_list_rows(&records, &context(), false);
1010 let post = post_of(&rows[0]);
1011 let shown: Vec<&str> = post
1012 .replies
1013 .iter()
1014 .map(|reply| reply.key.as_str())
1015 .collect();
1016 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1017 assert_eq!(post.hidden_reply_count, 2);
1018 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1019 }
1020
1021 #[test]
1022 fn post_without_hidden_replies_has_no_link() {
1023 let records = vec![
1024 record("r1", None, 1, 6),
1025 reply_by("x1", "r1", "Ada", 2),
1026 reply_by("x2", "r1", "Ben", 3),
1027 reply_by("x3", "r1", "Cy", 4),
1028 ];
1029 let rows = thread_list_rows(&records, &context(), false);
1030 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1031 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1032 }
1033
1034 fn label_for(repliers: &[&str]) -> String {
1035 let mut records = vec![record("r1", None, 1, 6)];
1036 for (index, name) in repliers.iter().enumerate() {
1037 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1038 }
1039 for index in 0..POST_VISIBLE_REPLIES {
1040 records.push(reply_by(
1041 &format!("v{index}"),
1042 "r1",
1043 "Shown",
1044 20 + index as u32,
1045 ));
1046 }
1047 let rows = thread_list_rows(&records, &context(), false);
1048 post_of(&rows[0]).hidden_replies_label().unwrap()
1049 }
1050
1051 #[test]
1052 fn replies_label_names_one_to_three_people() {
1053 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1054 assert_eq!(
1055 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1056 "3 replies from Anna and Ben"
1057 );
1058 assert_eq!(
1059 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1060 "4 replies from Anna, Ben and Clara"
1061 );
1062 }
1063
1064 #[test]
1065 fn replies_label_counts_the_others_beyond_three_people() {
1066 assert_eq!(
1067 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1068 "5 replies from Anna, Ben and 3 others"
1069 );
1070 assert_eq!(
1071 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1072 "4 replies from Anna, Ben and 2 others"
1073 );
1074 }
1075
1076 #[test]
1077 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1078 let records = vec![
1079 record("r1", None, 8, 6),
1080 record("r2", None, 9, 6),
1081 reply_by("x1", "r1", "Ada", 10),
1082 ];
1083 let mut rows = thread_list_rows(&records, &context(), true);
1084 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1085 pending_reply.reply_root = Some("r2".into());
1086 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1087 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1088 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1089 let replies: Vec<&str> = post_of(&rows[1])
1090 .replies
1091 .iter()
1092 .map(|reply| reply.key.as_str())
1093 .collect();
1094 assert_eq!(replies, vec!["pending-1"]);
1095 }
1096
1097 #[test]
1098 fn local_reply_to_an_unloaded_post_is_not_shown() {
1099 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1100 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1101 orphan.reply_root = Some("gone".into());
1102 place_local_rows(&mut rows, vec![orphan]);
1103 assert_eq!(keys(&rows), vec!["r1"]);
1104 }
1105
1106 #[test]
1107 fn subject_reaches_the_post_root() {
1108 let mut with_subject = record("r1", None, 8, 6);
1109 with_subject.subject = Some("Release plan".into());
1110 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1111 assert_eq!(
1112 post_of(&rows[0]).root.subject.as_deref(),
1113 Some("Release plan")
1114 );
1115 assert_eq!(post_of(&rows[1]).root.subject, None);
911 }
1116 }
912
1117
913 #[test]
1118 #[test]
@@ -989,7 +1194,7 @@ mod tests {
989 rows.iter()
1194 rows.iter()
990 .filter_map(|row| match row {
1195 .filter_map(|row| match row {
991 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1196 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
992 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) => None,
1197 Row::LoadOlder | Row::Start(_) | Row::Skeleton(_) | Row::Post(_) => None,
993 })
1198 })
994 .collect()
1199 .collect()
995 }
1200 }
@@ -1041,16 +1246,6 @@ mod tests {
1041 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1246 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1042 }
1247 }
1043
1248
1044 #[test]
1045 fn thread_list_rows_never_join() {
1046 let records = vec![
1047 record_by("a", "ada", 9, 0, 7),
1048 record_by("b", "ada", 9, 1, 7),
1049 ];
1050 let rows = thread_list_rows(&records, &context(), false);
1051 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1052 }
1053
1054 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1249 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1055 let corners = bubble_corners(own, Series { has_prev, has_next });
1250 let corners = bubble_corners(own, Series { has_prev, has_next });
1056 [
1251 [
crates/app/src/scheduled_rows.rs +57 −1
@@ -4,6 +4,7 @@ use teams_core::{Draft, ScheduledDraft, html_to_spans};
4 4 use crate::pending_rows::pending_row;
5 5 use crate::rows::{Delivery, MessageRow, ScheduledState};
6 6 use crate::schedule_time::describe;
7 use crate::scheduled::{conversation_of, thread_root_of};
7 8 use crate::views::composer::Outgoing;
8 9
9 10 pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
@@ -27,6 +28,7 @@ pub fn draft_id_of(key: &str) -> Option<&str> {
27 28 pub fn scheduled_outgoing(html: &str) -> Outgoing {
28 29 Outgoing {
29 30 draft: Draft::from_spans(&html_to_spans(html)).trimmed(),
31 subject: None,
30 32 mentions: Vec::new(),
31 33 reply: None,
32 34 edit: None,
@@ -51,10 +53,45 @@ pub fn scheduled_rows(
51 53 my_user_id: Option<&str>,
52 54 now: DateTime<Utc>,
53 55 change_failed: Option<&str>,
56 ) -> Vec<MessageRow> {
57 rows_where(
58 drafts,
59 |draft| draft.inner_thread_id == inner_thread_id,
60 conversation_id,
61 my_user_id,
62 now,
63 change_failed,
64 )
65 }
66
67 pub fn scheduled_feed_rows(
68 drafts: &[ScheduledDraft],
69 conversation_id: &str,
70 my_user_id: Option<&str>,
71 now: DateTime<Utc>,
72 change_failed: Option<&str>,
73 ) -> Vec<MessageRow> {
74 rows_where(
75 drafts,
76 |draft| conversation_of(&draft.inner_thread_id) == conversation_id,
77 conversation_id,
78 my_user_id,
79 now,
80 change_failed,
81 )
82 }
83
84 fn rows_where(
85 drafts: &[ScheduledDraft],
86 keep: impl Fn(&ScheduledDraft) -> bool,
87 conversation_id: &str,
88 my_user_id: Option<&str>,
89 now: DateTime<Utc>,
90 change_failed: Option<&str>,
54 91 ) -> Vec<MessageRow> {
55 92 let mut shown: Vec<&ScheduledDraft> = drafts
56 93 .iter()
57 .filter(|draft| draft.inner_thread_id == inner_thread_id && is_visible(draft, now))
94 .filter(|draft| keep(draft) && is_visible(draft, now))
58 95 .collect();
59 96 shown.sort_by_key(|draft| draft.send_at);
60 97 shown
@@ -76,6 +113,7 @@ pub fn scheduled_rows(
76 113 Delivery::Scheduled(state),
77 114 );
78 115 row.time = format!("Scheduled {}", scheduled_label(draft.send_at, now));
116 row.reply_root = thread_root_of(&draft.inner_thread_id).map(str::to_owned);
79 117 row
80 118 })
81 119 .collect()
@@ -123,6 +161,24 @@ mod tests {
123 161 assert_eq!(replies.len(), 1);
124 162 }
125 163
164 #[test]
165 fn feed_rows_cover_posts_and_replies_of_the_channel_only() {
166 let drafts = [
167 draft("post", "chan", 60, false),
168 draft("reply", "chan;messageid=m1", 30, false),
169 draft("elsewhere", "other;messageid=m1", 30, false),
170 ];
171 let shown = scheduled_feed_rows(&drafts, "chan", Some("me"), now(), None);
172 let roots: Vec<_> = shown
173 .iter()
174 .map(|row| (row.key.as_str(), row.reply_root.as_deref()))
175 .collect();
176 assert_eq!(
177 roots,
178 [("scheduled-reply", Some("m1")), ("scheduled-post", None)]
179 );
180 }
181
126 182 #[test]
127 183 fn a_passed_time_hides_the_draft_unless_delivery_failed() {
128 184 let drafts = [
@@ -4,6 +4,7 @@ use teams_core::{Draft, ScheduledDraft, html_to_spans};
4use crate::pending_rows::pending_row;
4use crate::pending_rows::pending_row;
5use crate::rows::{Delivery, MessageRow, ScheduledState};
5use crate::rows::{Delivery, MessageRow, ScheduledState};
6use crate::schedule_time::describe;
6use crate::schedule_time::describe;
7use crate::scheduled::{conversation_of, thread_root_of};
7use crate::views::composer::Outgoing;
8use crate::views::composer::Outgoing;
8
9
9pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
10pub const SCHEDULED_KEY_PREFIX: &str = "scheduled-";
@@ -27,6 +28,7 @@ pub fn draft_id_of(key: &str) -> Option<&str> {
27pub fn scheduled_outgoing(html: &str) -> Outgoing {
28pub fn scheduled_outgoing(html: &str) -> Outgoing {
28 Outgoing {
29 Outgoing {
29 draft: Draft::from_spans(&html_to_spans(html)).trimmed(),
30 draft: Draft::from_spans(&html_to_spans(html)).trimmed(),
31 subject: None,
30 mentions: Vec::new(),
32 mentions: Vec::new(),
31 reply: None,
33 reply: None,
32 edit: None,
34 edit: None,
@@ -51,10 +53,45 @@ pub fn scheduled_rows(
51 my_user_id: Option<&str>,
53 my_user_id: Option<&str>,
52 now: DateTime<Utc>,
54 now: DateTime<Utc>,
53 change_failed: Option<&str>,
55 change_failed: Option<&str>,
56) -> Vec<MessageRow> {
57 rows_where(
58 drafts,
59 |draft| draft.inner_thread_id == inner_thread_id,
60 conversation_id,
61 my_user_id,
62 now,
63 change_failed,
64 )
65}
66
67pub fn scheduled_feed_rows(
68 drafts: &[ScheduledDraft],
69 conversation_id: &str,
70 my_user_id: Option<&str>,
71 now: DateTime<Utc>,
72 change_failed: Option<&str>,
73) -> Vec<MessageRow> {
74 rows_where(
75 drafts,
76 |draft| conversation_of(&draft.inner_thread_id) == conversation_id,
77 conversation_id,
78 my_user_id,
79 now,
80 change_failed,
81 )
82}
83
84fn rows_where(
85 drafts: &[ScheduledDraft],
86 keep: impl Fn(&ScheduledDraft) -> bool,
87 conversation_id: &str,
88 my_user_id: Option<&str>,
89 now: DateTime<Utc>,
90 change_failed: Option<&str>,
54) -> Vec<MessageRow> {
91) -> Vec<MessageRow> {
55 let mut shown: Vec<&ScheduledDraft> = drafts
92 let mut shown: Vec<&ScheduledDraft> = drafts
56 .iter()
93 .iter()
57 .filter(|draft| draft.inner_thread_id == inner_thread_id && is_visible(draft, now))
94 .filter(|draft| keep(draft) && is_visible(draft, now))
58 .collect();
95 .collect();
59 shown.sort_by_key(|draft| draft.send_at);
96 shown.sort_by_key(|draft| draft.send_at);
60 shown
97 shown
@@ -76,6 +113,7 @@ pub fn scheduled_rows(
76 Delivery::Scheduled(state),
113 Delivery::Scheduled(state),
77 );
114 );
78 row.time = format!("Scheduled {}", scheduled_label(draft.send_at, now));
115 row.time = format!("Scheduled {}", scheduled_label(draft.send_at, now));
116 row.reply_root = thread_root_of(&draft.inner_thread_id).map(str::to_owned);
79 row
117 row
80 })
118 })
81 .collect()
119 .collect()
@@ -123,6 +161,24 @@ mod tests {
123 assert_eq!(replies.len(), 1);
161 assert_eq!(replies.len(), 1);
124 }
162 }
125
163
164 #[test]
165 fn feed_rows_cover_posts_and_replies_of_the_channel_only() {
166 let drafts = [
167 draft("post", "chan", 60, false),
168 draft("reply", "chan;messageid=m1", 30, false),
169 draft("elsewhere", "other;messageid=m1", 30, false),
170 ];
171 let shown = scheduled_feed_rows(&drafts, "chan", Some("me"), now(), None);
172 let roots: Vec<_> = shown
173 .iter()
174 .map(|row| (row.key.as_str(), row.reply_root.as_deref()))
175 .collect();
176 assert_eq!(
177 roots,
178 [("scheduled-reply", Some("m1")), ("scheduled-post", None)]
179 );
180 }
181
126 #[test]
182 #[test]
127 fn a_passed_time_hides_the_draft_unless_delivery_failed() {
183 fn a_passed_time_hides_the_draft_unless_delivery_failed() {
128 let drafts = [
184 let drafts = [
crates/app/src/stored_outgoing.rs +7 −0
@@ -49,6 +49,8 @@ struct StoredPreview {
49 49 #[derive(Serialize, Deserialize)]
50 50 struct Payload {
51 51 lines: Vec<DraftLine>,
52 #[serde(default)]
53 subject: Option<String>,
52 54 mentions: Vec<MentionInput>,
53 55 reply: Option<ReplyPreview>,
54 56 files: Vec<OutgoingFile>,
@@ -92,6 +94,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
92 94 }
93 95 let payload = serde_json::to_string(&Payload {
94 96 lines: outgoing.draft.to_lines(),
97 subject: outgoing.subject.clone(),
95 98 mentions: outgoing.mentions.clone(),
96 99 reply: outgoing.reply.clone(),
97 100 files: outgoing.files.clone(),
@@ -133,6 +136,7 @@ fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
133 136 pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
134 137 let Payload {
135 138 lines,
139 subject,
136 140 mentions,
137 141 reply,
138 142 files,
@@ -150,6 +154,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
150 154 .collect();
151 155 Some(Outgoing {
152 156 draft: Draft::from_lines(&lines),
157 subject,
153 158 mentions,
154 159 reply,
155 160 edit: None,
@@ -178,6 +183,7 @@ mod tests {
178 183 draft.take_edits();
179 184 Outgoing {
180 185 draft,
186 subject: Some("Release plan".to_owned()),
181 187 mentions: vec![MentionInput::user("user-1", "Ada Lovelace")],
182 188 reply: Some(ReplyPreview {
183 189 message_id: "message-1".to_owned(),
@@ -229,6 +235,7 @@ mod tests {
229 235 assert_eq!(restored.draft.text(), original.draft.text());
230 236 assert_eq!(restored.draft.to_html(), original.draft.to_html());
231 237 assert!(restored.draft.to_html().contains("<b>"));
238 assert_eq!(restored.subject, original.subject);
232 239 assert_eq!(restored.mentions, original.mentions);
233 240 assert_eq!(restored.reply, original.reply);
234 241 assert_eq!(restored.images, original.images);
@@ -49,6 +49,8 @@ struct StoredPreview {
49#[derive(Serialize, Deserialize)]
49#[derive(Serialize, Deserialize)]
50struct Payload {
50struct Payload {
51 lines: Vec<DraftLine>,
51 lines: Vec<DraftLine>,
52 #[serde(default)]
53 subject: Option<String>,
52 mentions: Vec<MentionInput>,
54 mentions: Vec<MentionInput>,
53 reply: Option<ReplyPreview>,
55 reply: Option<ReplyPreview>,
54 files: Vec<OutgoingFile>,
56 files: Vec<OutgoingFile>,
@@ -92,6 +94,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
92 }
94 }
93 let payload = serde_json::to_string(&Payload {
95 let payload = serde_json::to_string(&Payload {
94 lines: outgoing.draft.to_lines(),
96 lines: outgoing.draft.to_lines(),
97 subject: outgoing.subject.clone(),
95 mentions: outgoing.mentions.clone(),
98 mentions: outgoing.mentions.clone(),
96 reply: outgoing.reply.clone(),
99 reply: outgoing.reply.clone(),
97 files: outgoing.files.clone(),
100 files: outgoing.files.clone(),
@@ -133,6 +136,7 @@ fn remote_image(kind: RemoteKind, stored: StoredRemote) -> OutgoingImage {
133pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
136pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
134 let Payload {
137 let Payload {
135 lines,
138 lines,
139 subject,
136 mentions,
140 mentions,
137 reply,
141 reply,
138 files,
142 files,
@@ -150,6 +154,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
150 .collect();
154 .collect();
151 Some(Outgoing {
155 Some(Outgoing {
152 draft: Draft::from_lines(&lines),
156 draft: Draft::from_lines(&lines),
157 subject,
153 mentions,
158 mentions,
154 reply,
159 reply,
155 edit: None,
160 edit: None,
@@ -178,6 +183,7 @@ mod tests {
178 draft.take_edits();
183 draft.take_edits();
179 Outgoing {
184 Outgoing {
180 draft,
185 draft,
186 subject: Some("Release plan".to_owned()),
181 mentions: vec![MentionInput::user("user-1", "Ada Lovelace")],
187 mentions: vec![MentionInput::user("user-1", "Ada Lovelace")],
182 reply: Some(ReplyPreview {
188 reply: Some(ReplyPreview {
183 message_id: "message-1".to_owned(),
189 message_id: "message-1".to_owned(),
@@ -229,6 +235,7 @@ mod tests {
229 assert_eq!(restored.draft.text(), original.draft.text());
235 assert_eq!(restored.draft.text(), original.draft.text());
230 assert_eq!(restored.draft.to_html(), original.draft.to_html());
236 assert_eq!(restored.draft.to_html(), original.draft.to_html());
231 assert!(restored.draft.to_html().contains("<b>"));
237 assert!(restored.draft.to_html().contains("<b>"));
238 assert_eq!(restored.subject, original.subject);
232 assert_eq!(restored.mentions, original.mentions);
239 assert_eq!(restored.mentions, original.mentions);
233 assert_eq!(restored.reply, original.reply);
240 assert_eq!(restored.reply, original.reply);
234 assert_eq!(restored.images, original.images);
241 assert_eq!(restored.images, original.images);
crates/app/src/views/composer.rs +21 −4
@@ -127,6 +127,7 @@ pub struct EditPreview {
127 127 #[derive(Debug, Clone, PartialEq, Eq)]
128 128 pub struct Outgoing {
129 129 pub draft: Draft,
130 pub subject: Option<String>,
130 131 pub mentions: Vec<MentionInput>,
131 132 pub reply: Option<ReplyPreview>,
132 133 pub edit: Option<EditPreview>,
@@ -266,6 +267,7 @@ pub struct Composer {
266 267 app: Entity<AppState>,
267 268 input: Entity<TextareaState>,
268 269 conversation_id: Option<String>,
270 inline: bool,
269 271 reply: Option<ReplyPreview>,
270 272 editing: Option<EditPreview>,
271 273 mention_inputs: HashMap<String, MentionInput>,
@@ -457,6 +459,7 @@ impl Composer {
457 459 app,
458 460 input,
459 461 conversation_id: None,
462 inline: false,
460 463 reply: None,
461 464 editing: None,
462 465 mention_inputs: HashMap::new(),
@@ -1456,6 +1459,11 @@ impl Composer {
1456 1459 cx.notify();
1457 1460 }
1458 1461
1462 pub fn inline(mut self) -> Self {
1463 self.inline = true;
1464 self
1465 }
1466
1459 1467 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1460 1468 let text = text.to_owned();
1461 1469 self.input
@@ -1522,7 +1530,7 @@ impl Composer {
1522 1530 self.focus(window, cx);
1523 1531 }
1524 1532
1525 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1533 pub fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1526 1534 self.editing = None;
1527 1535 self.set_text("", window, cx);
1528 1536 }
@@ -1569,6 +1577,7 @@ impl Composer {
1569 1577 .collect();
1570 1578 Outgoing {
1571 1579 draft,
1580 subject: None,
1572 1581 mentions,
1573 1582 reply: self.reply.clone(),
1574 1583 edit: self.editing.clone(),
@@ -2569,12 +2578,17 @@ impl Render for Composer {
2569 2578 .child(notice.to_owned())
2570 2579 });
2571 2580 let composer_bounds = self.composer_bounds.clone();
2581 let (inset, top, bottom) = if self.inline {
2582 (0., 0., 0.)
2583 } else {
2584 (24., 8., 12.)
2585 };
2572 2586 v_flex()
2573 2587 .w_full()
2574 2588 .flex_none()
2575 .px(px(24.))
2576 .pt(px(8.))
2577 .pb(px(12.))
2589 .px(px(inset))
2590 .pt(px(top))
2591 .pb(px(bottom))
2578 2592 .key_context(KEY_CONTEXT)
2579 2593 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2580 2594 if this.link_editor.is_none() {
@@ -2888,6 +2902,7 @@ mod tests {
2888 2902
2889 2903 let outgoing = Outgoing {
2890 2904 draft: teams_core::Draft::default(),
2905 subject: None,
2891 2906 mentions: Vec::new(),
2892 2907 link_preview: None,
2893 2908 reply: None,
@@ -2941,6 +2956,7 @@ mod tests {
2941 2956 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2942 2957 super::Outgoing {
2943 2958 draft: teams_core::Draft::plain(text),
2959 subject: None,
2944 2960 mentions: Vec::new(),
2945 2961 link_preview: None,
2946 2962 reply: None,
@@ -4003,6 +4019,7 @@ mod tests {
4003 4019 composer.update(cx, |composer, cx| {
4004 4020 let draft = Outgoing {
4005 4021 draft: teams_core::Draft::plain("old"),
4022 subject: None,
4006 4023 mentions: Vec::new(),
4007 4024 link_preview: None,
4008 4025 reply: None,
@@ -127,6 +127,7 @@ pub struct EditPreview {
127#[derive(Debug, Clone, PartialEq, Eq)]
127#[derive(Debug, Clone, PartialEq, Eq)]
128pub struct Outgoing {
128pub struct Outgoing {
129 pub draft: Draft,
129 pub draft: Draft,
130 pub subject: Option<String>,
130 pub mentions: Vec<MentionInput>,
131 pub mentions: Vec<MentionInput>,
131 pub reply: Option<ReplyPreview>,
132 pub reply: Option<ReplyPreview>,
132 pub edit: Option<EditPreview>,
133 pub edit: Option<EditPreview>,
@@ -266,6 +267,7 @@ pub struct Composer {
266 app: Entity<AppState>,
267 app: Entity<AppState>,
267 input: Entity<TextareaState>,
268 input: Entity<TextareaState>,
268 conversation_id: Option<String>,
269 conversation_id: Option<String>,
270 inline: bool,
269 reply: Option<ReplyPreview>,
271 reply: Option<ReplyPreview>,
270 editing: Option<EditPreview>,
272 editing: Option<EditPreview>,
271 mention_inputs: HashMap<String, MentionInput>,
273 mention_inputs: HashMap<String, MentionInput>,
@@ -457,6 +459,7 @@ impl Composer {
457 app,
459 app,
458 input,
460 input,
459 conversation_id: None,
461 conversation_id: None,
462 inline: false,
460 reply: None,
463 reply: None,
461 editing: None,
464 editing: None,
462 mention_inputs: HashMap::new(),
465 mention_inputs: HashMap::new(),
@@ -1456,6 +1459,11 @@ impl Composer {
1456 cx.notify();
1459 cx.notify();
1457 }
1460 }
1458
1461
1462 pub fn inline(mut self) -> Self {
1463 self.inline = true;
1464 self
1465 }
1466
1459 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1467 pub fn set_placeholder(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1460 let text = text.to_owned();
1468 let text = text.to_owned();
1461 self.input
1469 self.input
@@ -1522,7 +1530,7 @@ impl Composer {
1522 self.focus(window, cx);
1530 self.focus(window, cx);
1523 }
1531 }
1524
1532
1525 fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1533 pub fn cancel_edit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1526 self.editing = None;
1534 self.editing = None;
1527 self.set_text("", window, cx);
1535 self.set_text("", window, cx);
1528 }
1536 }
@@ -1569,6 +1577,7 @@ impl Composer {
1569 .collect();
1577 .collect();
1570 Outgoing {
1578 Outgoing {
1571 draft,
1579 draft,
1580 subject: None,
1572 mentions,
1581 mentions,
1573 reply: self.reply.clone(),
1582 reply: self.reply.clone(),
1574 edit: self.editing.clone(),
1583 edit: self.editing.clone(),
@@ -2569,12 +2578,17 @@ impl Render for Composer {
2569 .child(notice.to_owned())
2578 .child(notice.to_owned())
2570 });
2579 });
2571 let composer_bounds = self.composer_bounds.clone();
2580 let composer_bounds = self.composer_bounds.clone();
2581 let (inset, top, bottom) = if self.inline {
2582 (0., 0., 0.)
2583 } else {
2584 (24., 8., 12.)
2585 };
2572 v_flex()
2586 v_flex()
2573 .w_full()
2587 .w_full()
2574 .flex_none()
2588 .flex_none()
2575 .px(px(24.))
2589 .px(px(inset))
2576 .pt(px(8.))
2590 .pt(px(top))
2577 .pb(px(12.))
2591 .pb(px(bottom))
2578 .key_context(KEY_CONTEXT)
2592 .key_context(KEY_CONTEXT)
2579 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2593 .on_action(cx.listener(|this, _: &ToggleBold, _, cx| {
2580 if this.link_editor.is_none() {
2594 if this.link_editor.is_none() {
@@ -2888,6 +2902,7 @@ mod tests {
2888
2902
2889 let outgoing = Outgoing {
2903 let outgoing = Outgoing {
2890 draft: teams_core::Draft::default(),
2904 draft: teams_core::Draft::default(),
2905 subject: None,
2891 mentions: Vec::new(),
2906 mentions: Vec::new(),
2892 link_preview: None,
2907 link_preview: None,
2893 reply: None,
2908 reply: None,
@@ -2941,6 +2956,7 @@ mod tests {
2941 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2956 fn outgoing_with(text: &str, images: Vec<super::OutgoingImage>) -> super::Outgoing {
2942 super::Outgoing {
2957 super::Outgoing {
2943 draft: teams_core::Draft::plain(text),
2958 draft: teams_core::Draft::plain(text),
2959 subject: None,
2944 mentions: Vec::new(),
2960 mentions: Vec::new(),
2945 link_preview: None,
2961 link_preview: None,
2946 reply: None,
2962 reply: None,
@@ -4003,6 +4019,7 @@ mod tests {
4003 composer.update(cx, |composer, cx| {
4019 composer.update(cx, |composer, cx| {
4004 let draft = Outgoing {
4020 let draft = Outgoing {
4005 draft: teams_core::Draft::plain("old"),
4021 draft: teams_core::Draft::plain("old"),
4022 subject: None,
4006 mentions: Vec::new(),
4023 mentions: Vec::new(),
4007 link_preview: None,
4024 link_preview: None,
4008 reply: None,
4025 reply: None,
crates/app/src/views/composer/drafts.rs +2 −2
@@ -55,7 +55,7 @@ impl Composer {
55 55 self.conversation_id
56 56 .clone()
57 57 .filter(|conversation_id| !conversation_id.is_empty())
58 .filter(|_| self.editing.is_none())
58 .filter(|_| self.editing.is_none() && !self.inline)
59 59 }
60 60
61 61 fn storable_draft(&self, cx: &App) -> Option<Outgoing> {
@@ -117,7 +117,7 @@ impl Composer {
117 117 cx: &mut Context<Self>,
118 118 ) {
119 119 let stored = Some(conversation_id)
120 .filter(|conversation_id| !conversation_id.is_empty())
120 .filter(|conversation_id| !conversation_id.is_empty() && !self.inline)
121 121 .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok())
122 122 .flatten()
123 123 .and_then(|record| decode(&record.payload, &record.images));
@@ -55,7 +55,7 @@ impl Composer {
55 self.conversation_id
55 self.conversation_id
56 .clone()
56 .clone()
57 .filter(|conversation_id| !conversation_id.is_empty())
57 .filter(|conversation_id| !conversation_id.is_empty())
58 .filter(|_| self.editing.is_none())
58 .filter(|_| self.editing.is_none() && !self.inline)
59 }
59 }
60
60
61 fn storable_draft(&self, cx: &App) -> Option<Outgoing> {
61 fn storable_draft(&self, cx: &App) -> Option<Outgoing> {
@@ -117,7 +117,7 @@ impl Composer {
117 cx: &mut Context<Self>,
117 cx: &mut Context<Self>,
118 ) {
118 ) {
119 let stored = Some(conversation_id)
119 let stored = Some(conversation_id)
120 .filter(|conversation_id| !conversation_id.is_empty())
120 .filter(|conversation_id| !conversation_id.is_empty() && !self.inline)
121 .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok())
121 .and_then(|conversation_id| self.app.read(cx).store.draft(conversation_id).ok())
122 .flatten()
122 .flatten()
123 .and_then(|record| decode(&record.payload, &record.images));
123 .and_then(|record| decode(&record.payload, &record.images));
crates/app/src/views/composer/schedule.rs +2 −0
@@ -75,6 +75,8 @@ impl Composer {
75 75 let outgoing = self.compose(cx);
76 76 if state.mode.read_only && !state.mode.demo {
77 77 Some("Read-only mode")
78 } else if self.inline {
79 Some("Open the conversation to schedule a reply")
78 80 } else if conversation_id == NOTES_CHAT_ID {
79 81 Some("Not available in your notes")
80 82 } else if conversation_id.is_empty() {
@@ -75,6 +75,8 @@ impl Composer {
75 let outgoing = self.compose(cx);
75 let outgoing = self.compose(cx);
76 if state.mode.read_only && !state.mode.demo {
76 if state.mode.read_only && !state.mode.demo {
77 Some("Read-only mode")
77 Some("Read-only mode")
78 } else if self.inline {
79 Some("Open the conversation to schedule a reply")
78 } else if conversation_id == NOTES_CHAT_ID {
80 } else if conversation_id == NOTES_CHAT_ID {
79 Some("Not available in your notes")
81 Some("Not available in your notes")
80 } else if conversation_id.is_empty() {
82 } else if conversation_id.is_empty() {
crates/app/src/views/conversation.rs +358 −348
@@ -1,4 +1,4 @@
1 use std::cell::RefCell;
1 use std::cell::{Cell, RefCell};
2 2 use std::collections::{HashMap, HashSet};
3 3 use std::path::{Path, PathBuf};
4 4 use std::rc::Rc;
@@ -9,7 +9,7 @@ use gpui_kit::assets::IconName;
9 9 use gpui_kit::component::{
10 10 button::{Button, ButtonVariants as _},
11 11 h_flex,
12 input::Escape,
12 input::{Escape, InputState},
13 13 message_scroller::{MessageScroller, MessageScrollerState},
14 14 tooltip::Tooltip,
15 15 v_flex,
@@ -17,17 +17,19 @@ use gpui_kit::component::{
17 17 use gpui_kit::prelude::FluentBuilder as _;
18 18 use gpui_kit::*;
19 19 use store::{MessageRecord, OutboxState, OutboxTarget};
20 use teams_core::{FileCard, ImageRef, LinkPreview};
20 use teams_core::{FileCard, LinkPreview};
21 21
22 mod feed;
23 mod render_env;
22 24 mod scheduled;
23 25
24 use super::adaptive_card::ensure_cards_inputs;
25 26 use super::attachments::FileActions;
26 27 use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
27 28 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
28 29 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
29 use super::message_row::{DeliveryActions, RowActions, render_message_row, render_skeleton_row};
30 use super::message_row::{render_message_row, render_skeleton_row};
30 31 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
32 use super::post_card::render_post;
31 33 use super::reaction_picker::{PickHandler, ReactionPicker};
32 34 use super::reaction_pills::{ReactionControls, ReactionPopover};
33 35 use super::widgets::{icon, symbol};
@@ -45,13 +47,15 @@ use crate::read_state::{ReadTrigger, plan_read};
45 47 use crate::rows::{
46 48 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
47 49 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
48 has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph, reply_excerpt,
49 set_own_reaction, thread_list_rows, thread_rows,
50 has_own_reaction, message_draft, message_text, place_local_rows, placeholder_rows,
51 reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
50 52 };
51 53 use crate::runtime;
52 54 use crate::sidebar_model::{AvatarSpec, Face};
53 55 use crate::theme;
54 56 use crate::typing::typing_tooltip;
57 use feed::{FeedStash, subject_input};
58 use render_env::RenderEnv;
55 59
56 60 const CHAT_OPEN_LIMIT: usize = 60;
57 61 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -129,6 +133,13 @@ pub struct ConversationView {
129 133 app: Entity<AppState>,
130 134 scroller: Entity<MessageScrollerState>,
131 135 composer: Entity<Composer>,
136 subject: Entity<InputState>,
137 new_post_open: bool,
138 reply_composer: Option<Entity<Composer>>,
139 reply_root: Option<String>,
140 feed_stash: Option<FeedStash>,
141 feed_rows_seen: Rc<Cell<usize>>,
142 feed_at_top: bool,
132 143 draft: Entity<NewChatDraft>,
133 144 draft_active: bool,
134 145 draft_created: Option<(Vec<String>, String)>,
@@ -195,6 +206,17 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
195 206 }
196 207 }
197 208
209 fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
210 match mode {
211 ViewMode::Flat => record.target == OutboxTarget::Flat,
212 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
213 ViewMode::Thread(root_id) => {
214 record.target == OutboxTarget::Thread
215 && record.thread_root_id.as_deref() == Some(root_id.as_str())
216 }
217 }
218 }
219
198 220 enum DownloadEvent {
199 221 Progress(u8),
200 222 Finished(Result<PathBuf, String>),
@@ -334,6 +356,7 @@ impl ConversationView {
334 356 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
335 357 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
336 358 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
359 let subject = subject_input(window, cx);
337 360 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
338 361 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
339 362 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
@@ -341,6 +364,7 @@ impl ConversationView {
341 364 cx.subscribe_in(&app, window, Self::on_app_event),
342 365 cx.subscribe_in(&composer, window, Self::on_composer_event),
343 366 cx.subscribe_in(&draft, window, Self::on_draft_event),
367 cx.subscribe_in(&subject, window, Self::on_subject_event),
344 368 cx.observe_window_activation(window, Self::on_window_activation),
345 369 cx.on_app_quit(|this, cx| {
346 370 this.composer
@@ -357,6 +381,13 @@ impl ConversationView {
357 381 app,
358 382 scroller,
359 383 composer,
384 subject,
385 new_post_open: false,
386 reply_composer: None,
387 reply_root: None,
388 feed_stash: None,
389 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
390 feed_at_top: true,
360 391 draft,
361 392 draft_active: false,
362 393 draft_created: None,
@@ -510,21 +541,7 @@ impl ConversationView {
510 541 cx: &mut Context<Self>,
511 542 ) {
512 543 match event {
513 ComposerEvent::Submit(outgoing) if self.draft_active => {
514 self.send_new_chat((**outgoing).clone(), window, cx)
515 }
516 ComposerEvent::Submit(outgoing)
517 if outgoing
518 .edit
519 .as_ref()
520 .is_some_and(|edit| edit.scheduled.is_some()) =>
521 {
522 self.send_scheduled_edit((**outgoing).clone(), window, cx)
523 }
524 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
525 self.send_edit((**outgoing).clone(), window, cx)
526 }
527 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
544 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
528 545 ComposerEvent::Schedule { outgoing, send_at } => {
529 546 self.schedule((**outgoing).clone(), *send_at, window, cx)
530 547 }
@@ -533,25 +550,43 @@ impl ConversationView {
533 550 }
534 551 }
535 552
536 fn typing_target(&self) -> Option<(String, Option<String>)> {
537 let current = self.current.as_ref().filter(|_| !self.draft_active)?;
538 let thread_root_id = match &current.mode {
539 ViewMode::Thread(root_id) => Some(root_id.clone()),
540 ViewMode::Flat | ViewMode::ThreadList => None,
541 };
542 Some((
543 current.selection.conversation_id().to_owned(),
544 thread_root_id,
545 ))
553 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
554 if self.draft_active {
555 return self.send_new_chat(outgoing, window, cx);
556 }
557 let in_feed = self.in_feed();
558 if in_feed && outgoing.edit.is_none() {
559 outgoing.subject = self.take_subject(window, cx);
560 }
561 if in_feed {
562 self.close_new_post(cx);
563 }
564 match &outgoing.edit {
565 Some(edit) if edit.scheduled.is_some() => {
566 self.send_scheduled_edit(outgoing, window, cx)
567 }
568 Some(_) => self.send_edit(outgoing, window, cx),
569 None => self.send(outgoing, window, cx),
570 }
571 }
572
573 fn typing_root(&self) -> Option<String> {
574 match self.current.as_ref().map(|current| &current.mode) {
575 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
576 _ => None,
577 }
546 578 }
547 579
548 580 fn send_typing(&self, active: bool, cx: &App) {
581 self.send_typing_in(self.typing_root(), active, cx);
582 }
583
584 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
549 585 let state = self.app.read(cx);
550 if state.mode.demo || state.mode.read_only {
586 if state.mode.demo || state.mode.read_only || self.draft_active {
551 587 return;
552 588 }
553 let (Some(engine), Some((conversation_id, thread_root_id))) =
554 (state.engine.clone(), self.typing_target())
589 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
555 590 else {
556 591 return;
557 592 };
@@ -611,6 +646,11 @@ impl ConversationView {
611 646
612 647 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
613 648 self.stop_typing(cx);
649 self.stop_reply_typing(cx);
650 self.new_post_open = false;
651 self.feed_stash = None;
652 self.feed_at_top = true;
653 self.restore_subject(None, window, cx);
614 654 self.toolbar_hovered = None;
615 655 self.toolbar_pinned = None;
616 656 self.toolbar_suppressed = None;
@@ -655,7 +695,8 @@ impl ConversationView {
655 695 self.composer.update(cx, |composer, cx| {
656 696 composer.set_conversation(&target.0, &target.1, window, cx);
657 697 });
658 if !self.draft_active {
698 self.sync_reply_composer(window, cx);
699 if !self.draft_active && !self.in_feed() {
659 700 self.composer
660 701 .update(cx, |composer, cx| composer.focus(window, cx));
661 702 }
@@ -767,19 +808,17 @@ impl ConversationView {
767 808 .borrow()
768 809 .iter()
769 810 .enumerate()
770 .filter_map(|(index, row)| match row {
771 Row::Message(message)
772 if message.images.iter().any(|image| keys.contains(&image.url))
811 .filter(|(_, row)| {
812 row.messages().any(|message| {
813 message.images.iter().any(|image| keys.contains(&image.url))
773 814 || message
774 815 .link_preview
775 816 .as_ref()
776 817 .and_then(LinkPreview::image)
777 .is_some_and(|image| keys.contains(&image.url)) =>
778 {
779 Some(index)
780 }
781 _ => None,
818 .is_some_and(|image| keys.contains(&image.url))
819 })
782 820 })
821 .map(|(index, _)| index)
783 822 .collect();
784 823 self.scroller.update(cx, |scroller, cx| {
785 824 for index in indices {
@@ -803,10 +842,11 @@ impl ConversationView {
803 842 .borrow()
804 843 .iter()
805 844 .enumerate()
806 .filter_map(|(index, row)| match row {
807 Row::Message(message) if !message.adaptive_cards.is_empty() => Some(index),
808 _ => None,
845 .filter(|(_, row)| {
846 row.messages()
847 .any(|message| !message.adaptive_cards.is_empty())
809 848 })
849 .map(|(index, _)| index)
810 850 .collect();
811 851 self.scroller.update(cx, |scroller, cx| {
812 852 for index in indices {
@@ -867,13 +907,23 @@ impl ConversationView {
867 907 .loaded_limit
868 908 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
869 909 current.first_unread = None;
870 if matches!(current.selection, Selection::Channel(_)) {
871 current.mode = match record.reply_to_id {
872 Some(root_id) => ViewMode::Thread(root_id),
873 None => ViewMode::ThreadList,
874 };
910 let in_channel = matches!(current.selection, Selection::Channel(_));
911 if in_channel {
912 match record.reply_to_id.clone() {
913 Some(root_id) => {
914 self.enter_thread_mode(root_id.clone(), cx);
915 self.refresh_thread(root_id, cx);
916 }
917 None => {
918 self.enter_feed_mode();
919 }
920 }
875 921 }
876 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
922 let in_thread = self
923 .current
924 .as_ref()
925 .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_)));
926 let target_key = if in_thread {
877 927 message_id.to_owned()
878 928 } else {
879 929 row_key
@@ -916,10 +966,14 @@ impl ConversationView {
916 966 }
917 967
918 968 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
919 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
920 Row::Message(message) if !message.own => Some(message.key.clone()),
921 _ => None,
922 });
969 let key = self
970 .rows
971 .borrow()
972 .iter()
973 .rev()
974 .flat_map(Row::messages)
975 .find(|message| !message.own)
976 .map(|message| message.key.clone());
923 977 if let Some(key) = key {
924 978 self.begin_reply(&key, window, cx);
925 979 }
@@ -956,6 +1010,15 @@ impl ConversationView {
956 1010 .unwrap_or_else(|| "Unknown".to_owned()),
957 1011 excerpt: reply_excerpt(&record),
958 1012 };
1013 if self.in_feed() {
1014 let root_id = record
1015 .reply_to_id
1016 .clone()
1017 .unwrap_or_else(|| record.message_id.clone());
1018 let quote = record.reply_to_id.is_some().then_some(preview);
1019 self.open_reply_editor(root_id, quote, window, cx);
1020 return;
1021 }
959 1022 self.composer.update(cx, |composer, cx| {
960 1023 composer.set_reply(Some(preview), cx);
961 1024 composer.focus(window, cx);
@@ -996,10 +1059,7 @@ impl ConversationView {
996 1059 self.rows
997 1060 .borrow()
998 1061 .iter()
999 .filter_map(|row| match row {
1000 Row::Message(message) => Some(message),
1001 _ => None,
1002 })
1062 .flat_map(Row::messages)
1003 1063 .flat_map(|message| message.reactions.iter())
1004 1064 .flat_map(|chip| chip.reactors.iter())
1005 1065 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
@@ -1025,19 +1085,30 @@ impl ConversationView {
1025 1085 let Some(details) = self.reaction_details.as_ref() else {
1026 1086 return;
1027 1087 };
1028 let present = self.rows.borrow().iter().any(|row| {
1029 matches!(row, Row::Message(message) if message.key == details.message_key
1030 && message.reactions.iter().any(|chip| chip.glyph() == details.anchor_glyph))
1031 });
1088 let present = self
1089 .rows
1090 .borrow()
1091 .iter()
1092 .flat_map(Row::messages)
1093 .any(|message| {
1094 message.key == details.message_key
1095 && message
1096 .reactions
1097 .iter()
1098 .any(|chip| chip.glyph() == details.anchor_glyph)
1099 });
1032 1100 if !present {
1033 1101 self.reaction_details = None;
1034 1102 }
1035 1103 }
1036 1104
1037 1105 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1038 let multiple_kinds = self.rows.borrow().iter().any(|row| {
1039 matches!(row, Row::Message(message) if message.key == message_key && message.reactions.len() > 1)
1040 });
1106 let multiple_kinds = self
1107 .rows
1108 .borrow()
1109 .iter()
1110 .flat_map(Row::messages)
1111 .any(|message| message.key == message_key && message.reactions.len() > 1);
1041 1112 self.reaction_details = Some(ReactionDetails {
1042 1113 message_key: message_key.to_owned(),
1043 1114 anchor_glyph: glyph.to_owned(),
@@ -1135,9 +1206,15 @@ impl ConversationView {
1135 1206 .max(current.loaded_count + GROWTH_HEADROOM)
1136 1207 };
1137 1208 let store = self.app.read(cx).store.clone();
1138 let records: Vec<MessageRecord> = store
1139 .messages(&conversation_id, None, limit)
1140 .unwrap_or_default();
1209 let thread_root = match &current.mode {
1210 ViewMode::Thread(root_id) => Some(root_id.clone()),
1211 ViewMode::Flat | ViewMode::ThreadList => None,
1212 };
1213 let records: Vec<MessageRecord> = match &thread_root {
1214 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1215 None => store.messages(&conversation_id, None, limit),
1216 }
1217 .unwrap_or_default();
1141 1218 let sync_has_more = store
1142 1219 .sync_state(&conversation_id)
1143 1220 .ok()
@@ -1167,11 +1244,14 @@ impl ConversationView {
1167 1244 let current = self.current.as_mut().expect("checked above");
1168 1245 let first_unread = current.first_unread.clone();
1169 1246 current.loaded_limit = limit;
1170 current.loaded_count = records.len();
1247 if thread_root.is_none() {
1248 current.loaded_count = records.len();
1249 }
1171 1250 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1172 1251 let placeholders = current.sync.messages
1173 1252 && records.is_empty()
1174 1253 && !matches!(current.mode, ViewMode::Thread(_));
1254 let in_feed = current.mode == ViewMode::ThreadList;
1175 1255 let mut rows = match &current.mode {
1176 1256 _ if placeholders => {
1177 1257 current.has_older = false;
@@ -1194,13 +1274,17 @@ impl ConversationView {
1194 1274 thread_rows(&records, root_id, &context)
1195 1275 }
1196 1276 };
1197 rows.extend(
1198 self.pending
1199 .iter()
1200 .cloned()
1201 .map(|row| Row::Message(Box::new(row))),
1202 );
1203 rows.extend(self.scheduled_rows(context.my_user_id.as_deref(), cx));
1277 let local: Vec<MessageRow> = self
1278 .pending
1279 .iter()
1280 .cloned()
1281 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1282 .collect();
1283 if in_feed {
1284 place_local_rows(&mut rows, local);
1285 } else {
1286 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1287 }
1204 1288 let receipts = self.receipts(&records, cx);
1205 1289 for row in rows.iter_mut() {
1206 1290 if let Row::Message(message) = row
@@ -1226,14 +1310,20 @@ impl ConversationView {
1226 1310 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1227 1311 self.drop_stale_reaction_details();
1228 1312 let new_len = self.rows.borrow().len();
1313 let in_feed = self.in_feed();
1229 1314 if reset {
1230 1315 let marker_index = self
1231 1316 .rows
1232 1317 .borrow()
1233 1318 .iter()
1234 1319 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1320 self.feed_at_top = true;
1235 1321 self.scroller.update(cx, |scroller, cx| {
1236 1322 scroller.reset(new_len, cx);
1323 if in_feed {
1324 scroller.scroll_to_item(0, cx);
1325 return;
1326 }
1237 1327 match marker_index {
1238 1328 Some(index) if !scroller.scroll_to_item(index, cx) => {
1239 1329 scroller.scroll_to_end(cx)
@@ -1254,12 +1344,19 @@ impl ConversationView {
1254 1344 changed_indices(&old_rows, &new_rows),
1255 1345 )
1256 1346 };
1347 let top_changed = splice
1348 .as_ref()
1349 .is_some_and(|splice| splice.range.start == 0);
1350 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1257 1351 self.scroller.update(cx, |scroller, cx| {
1258 1352 if let Some(splice) = splice
1259 1353 && !scroller.splice(splice.range, splice.count, cx)
1260 1354 {
1261 1355 scroller.reset(new_len, cx);
1262 1356 }
1357 if keep_top {
1358 scroller.scroll_to_item(0, cx);
1359 }
1263 1360 for index in changed {
1264 1361 scroller.remeasure_items(index..index + 1, cx);
1265 1362 }
@@ -1281,12 +1378,14 @@ impl ConversationView {
1281 1378 }
1282 1379 current.fetched = true;
1283 1380 let is_chat = matches!(current.selection, Selection::Chat(_));
1284 let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
1285 Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
1286 Some(message.created_at)
1287 }
1288 _ => None,
1289 });
1381 let newest_cached = self
1382 .rows
1383 .borrow()
1384 .iter()
1385 .flat_map(Row::messages)
1386 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1387 .map(|message| message.created_at)
1388 .max();
1290 1389 let current = self.current.as_mut().expect("checked above");
1291 1390 if current.sync.failed {
1292 1391 self.notice = None;
@@ -1632,7 +1731,10 @@ impl ConversationView {
1632 1731 self.pending_outgoing.clear();
1633 1732 }
1634 1733
1635 fn outbox_route(&self) -> (OutboxTarget, Option<String>) {
1734 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
1735 if let Some(root_id) = reply_root {
1736 return (OutboxTarget::Thread, Some(root_id));
1737 }
1636 1738 match self.current.as_ref().map(|current| &current.mode) {
1637 1739 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1638 1740 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
@@ -1654,9 +1756,9 @@ impl ConversationView {
1654 1756 return;
1655 1757 };
1656 1758 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1657 let route = self.outbox_route();
1759 let mut pending = Vec::new();
1658 1760 for record in records {
1659 if (record.target, record.thread_root_id.clone()) != route {
1761 if !shown_in_view(&current.mode, &record) {
1660 1762 continue;
1661 1763 }
1662 1764 let Some(outgoing) = outgoing_of(&record) else {
@@ -1666,15 +1768,20 @@ impl ConversationView {
1666 1768 OutboxState::Sending => Delivery::Sending,
1667 1769 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1668 1770 };
1669 self.pending.push(pending_row(
1771 let mut row = pending_row(
1670 1772 record.id.clone(),
1671 1773 conversation_id.clone(),
1672 1774 my_user_id.clone(),
1673 1775 record.created_at,
1674 1776 &outgoing,
1675 1777 delivery,
1676 ));
1677 self.pending_outgoing.insert(record.id, outgoing);
1778 );
1779 row.reply_root = record.thread_root_id.clone();
1780 pending.push((row, record.id, outgoing));
1781 }
1782 for (row, id, outgoing) in pending {
1783 self.pending.push(row);
1784 self.pending_outgoing.insert(id, outgoing);
1678 1785 }
1679 1786 }
1680 1787
@@ -1691,32 +1798,25 @@ impl ConversationView {
1691 1798 self.rebuild(false, cx);
1692 1799 }
1693 1800
1694 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1695 self.stop_typing(cx);
1696 if let Some(current) = self.current.as_mut() {
1697 current.mode = ViewMode::Thread(root_id);
1698 }
1699 self.reload_pending(cx);
1700 self.rebuild(true, cx);
1701 }
1702
1703 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1704 self.stop_typing(cx);
1705 if let Some(current) = self.current.as_mut() {
1706 current.mode = ViewMode::ThreadList;
1707 }
1708 self.reload_pending(cx);
1709 self.rebuild(true, cx);
1801 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1802 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1710 1803 }
1711 1804
1712 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1713 self.send_as(new_outbox_id(), outgoing, window, cx);
1805 fn send_in_thread(
1806 &mut self,
1807 root_id: String,
1808 outgoing: Outgoing,
1809 window: &mut Window,
1810 cx: &mut Context<Self>,
1811 ) {
1812 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
1714 1813 }
1715 1814
1716 1815 fn send_as(
1717 1816 &mut self,
1718 1817 id: String,
1719 1818 outgoing: Outgoing,
1819 reply_root: Option<String>,
1720 1820 window: &mut Window,
1721 1821 cx: &mut Context<Self>,
1722 1822 ) {
@@ -1726,18 +1826,36 @@ impl ConversationView {
1726 1826 return;
1727 1827 };
1728 1828 if mode.read_only || mode.demo {
1729 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1829 self.restore_unsent(
1830 "Read-only mode: nothing was sent",
1831 &outgoing,
1832 reply_root.as_deref(),
1833 window,
1834 cx,
1835 );
1730 1836 return;
1731 1837 }
1732 1838 let Some(engine) = engine else {
1733 1839 self.discard_outbox_row(&id, cx);
1734 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1840 self.restore_unsent(
1841 "Not connected yet: nothing was sent",
1842 &outgoing,
1843 reply_root.as_deref(),
1844 window,
1845 cx,
1846 );
1735 1847 return;
1736 1848 };
1737 1849 let conversation_id = current.selection.conversation_id().to_owned();
1738 let (target, thread_root_id) = self.outbox_route();
1850 let (target, thread_root_id) = self.outbox_route(reply_root);
1739 1851 let created_at = Utc::now();
1740 self.push_pending(id.clone(), created_at, &outgoing, cx);
1852 self.push_pending(
1853 id.clone(),
1854 created_at,
1855 &outgoing,
1856 thread_root_id.clone(),
1857 cx,
1858 );
1741 1859 if let Some(record) = outbox_record(
1742 1860 &id,
1743 1861 &conversation_id,
@@ -1750,8 +1868,13 @@ impl ConversationView {
1750 1868 }
1751 1869 self.notice = None;
1752 1870 self.rebuild(false, cx);
1753 self.scroller
1754 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1871 if self.in_feed() {
1872 self.scroller
1873 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
1874 } else {
1875 self.scroller
1876 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1877 }
1755 1878
1756 1879 let receiver = runtime::spawn(async move {
1757 1880 deliver(
@@ -1775,12 +1898,22 @@ impl ConversationView {
1775 1898 &mut self,
1776 1899 message: &str,
1777 1900 outgoing: &Outgoing,
1901 reply_root: Option<&str>,
1778 1902 window: &mut Window,
1779 1903 cx: &mut Context<Self>,
1780 1904 ) {
1781 1905 self.notice = Some(message.to_owned());
1782 self.composer
1783 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1906 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
1907 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
1908 if let Some(composer) = self.reply_composer.clone() {
1909 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1910 }
1911 } else {
1912 self.show_main_composer(cx);
1913 self.restore_subject(outgoing.subject.as_deref(), window, cx);
1914 self.composer
1915 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1916 }
1784 1917 cx.notify();
1785 1918 }
1786 1919
@@ -1794,6 +1927,7 @@ impl ConversationView {
1794 1927 key: String,
1795 1928 created_at: DateTime<Utc>,
1796 1929 outgoing: &Outgoing,
1930 reply_root: Option<String>,
1797 1931 cx: &App,
1798 1932 ) {
1799 1933 let my_user_id = self.row_context(cx).my_user_id;
@@ -1802,14 +1936,16 @@ impl ConversationView {
1802 1936 .as_ref()
1803 1937 .map(|current| current.selection.conversation_id().to_owned())
1804 1938 .unwrap_or_default();
1805 self.pending.push(pending_row(
1939 let mut row = pending_row(
1806 1940 key.clone(),
1807 1941 conversation_id,
1808 1942 my_user_id,
1809 1943 created_at,
1810 1944 outgoing,
1811 1945 Delivery::Sending,
1812 ));
1946 );
1947 row.reply_root = reply_root;
1948 self.pending.push(row);
1813 1949 self.pending_outgoing.insert(key, outgoing.clone());
1814 1950 }
1815 1951
@@ -1820,7 +1956,7 @@ impl ConversationView {
1820 1956 (draft.chips().to_vec(), topic)
1821 1957 };
1822 1958 if recipients.is_empty() {
1823 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1959 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
1824 1960 self.draft
1825 1961 .update(cx, |draft, cx| draft.focus_query(window, cx));
1826 1962 return;
@@ -1830,17 +1966,29 @@ impl ConversationView {
1830 1966 .iter()
1831 1967 .any(|row| matches!(row.delivery, Delivery::Sending))
1832 1968 {
1833 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1969 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
1834 1970 return;
1835 1971 }
1836 1972 let state = self.app.read(cx);
1837 1973 let (mode, engine) = (state.mode, state.engine.clone());
1838 1974 if mode.read_only {
1839 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1975 self.restore_unsent(
1976 "Read-only mode: nothing was sent",
1977 &outgoing,
1978 None,
1979 window,
1980 cx,
1981 );
1840 1982 return;
1841 1983 }
1842 1984 if mode.demo && outgoing.has_attachments() {
1843 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1985 self.restore_unsent(
1986 "Read-only mode: nothing was sent",
1987 &outgoing,
1988 None,
1989 window,
1990 cx,
1991 );
1844 1992 return;
1845 1993 }
1846 1994 if mode.demo {
@@ -1848,7 +1996,13 @@ impl ConversationView {
1848 1996 return;
1849 1997 }
1850 1998 let Some(engine) = engine else {
1851 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1999 self.restore_unsent(
2000 "Not connected yet: nothing was sent",
2001 &outgoing,
2002 None,
2003 window,
2004 cx,
2005 );
1852 2006 return;
1853 2007 };
1854 2008 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
@@ -1863,7 +2017,7 @@ impl ConversationView {
1863 2017 self.draft_error = None;
1864 2018 self.notice = None;
1865 2019 let key = self.next_pending_key();
1866 self.push_pending(key.clone(), Utc::now(), &outgoing, cx);
2020 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
1867 2021 self.rebuild(true, cx);
1868 2022 let recipients_for_finish = user_ids.clone();
1869 2023 let receiver = runtime::spawn(async move {
@@ -2202,6 +2356,7 @@ impl ConversationView {
2202 2356 };
2203 2357 let draft = Outgoing {
2204 2358 draft: message_draft(&record),
2359 subject: None,
2205 2360 mentions,
2206 2361 reply: None,
2207 2362 edit: Some(edit),
@@ -2209,6 +2364,7 @@ impl ConversationView {
2209 2364 files: Vec::new(),
2210 2365 link_preview: None,
2211 2366 };
2367 self.show_main_composer(cx);
2212 2368 self.composer
2213 2369 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2214 2370 }
@@ -2217,16 +2373,16 @@ impl ConversationView {
2217 2373 if self.draft_active {
2218 2374 return;
2219 2375 }
2220 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
2221 Row::Message(message)
2222 if message.own
2223 && !message.deleted
2224 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
2225 {
2226 Some(message.key.clone())
2227 }
2228 _ => None,
2229 });
2376 let key = self
2377 .rows
2378 .borrow()
2379 .iter()
2380 .flat_map(Row::messages)
2381 .filter(|message| {
2382 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2383 })
2384 .max_by_key(|message| message.created_at)
2385 .map(|message| message.key.clone());
2230 2386 if let Some(key) = key {
2231 2387 self.begin_edit(&key, window, cx);
2232 2388 }
@@ -2252,6 +2408,7 @@ impl ConversationView {
2252 2408 }
2253 2409 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2254 2410 self.notice = Some("Read-only mode: edit not saved".to_owned());
2411 self.show_main_composer(cx);
2255 2412 self.composer
2256 2413 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2257 2414 cx.notify();
@@ -2272,6 +2429,7 @@ impl ConversationView {
2272 2429 let failed = !matches!(receiver.await, Ok(Ok(())));
2273 2430 this.update_in(cx, |this, window, cx| {
2274 2431 if failed {
2432 this.show_main_composer(cx);
2275 2433 if this.composer.read(cx).is_empty(cx) {
2276 2434 this.notice =
2277 2435 Some("Edit failed: your text is back in the composer".to_owned());
@@ -2414,11 +2572,16 @@ impl ConversationView {
2414 2572 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2415 2573 return;
2416 2574 };
2575 let reply_root = self
2576 .pending
2577 .iter()
2578 .find(|row| row.key == key)
2579 .and_then(|row| row.reply_root.clone());
2417 2580 self.pending.retain(|row| row.key != key);
2418 2581 if self.draft_active {
2419 2582 self.send_new_chat(outgoing, window, cx);
2420 2583 } else {
2421 self.send_as(key.to_owned(), outgoing, window, cx);
2584 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
2422 2585 }
2423 2586 }
2424 2587
@@ -2624,17 +2787,29 @@ impl ConversationView {
2624 2787 .border_color(theme::border());
2625 2788 if matches!(current.mode, ViewMode::Thread(_)) {
2626 2789 header = header.child(
2627 Button::new("back-to-threads")
2628 .ghost()
2629 .compact()
2630 .label("Threads")
2631 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
2790 h_flex()
2791 .id("back-to-channel")
2792 .flex_none()
2793 .gap(px(2.))
2794 .pl(px(4.))
2795 .pr(px(8.))
2796 .py(px(4.))
2797 .items_center()
2798 .rounded(px(6.))
2799 .cursor_pointer()
2800 .text_size(px(13.))
2801 .font_weight(FontWeight::SEMIBOLD)
2802 .text_color(theme::accent_text())
2803 .hover(|button| button.bg(theme::row_hover()))
2804 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
2805 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
2806 .child("Back to channel"),
2632 2807 );
2633 2808 }
2634 2809 let channel_note = match current.mode {
2635 2810 ViewMode::Flat => None,
2636 ViewMode::ThreadList => Some("Threads"),
2637 ViewMode::Thread(_) => Some("Thread"),
2811 ViewMode::ThreadList => Some("Posts"),
2812 ViewMode::Thread(_) => Some("Conversation"),
2638 2813 };
2639 2814 if let Some(note) = channel_note {
2640 2815 subline = note.to_owned();
@@ -2686,7 +2861,7 @@ impl ConversationView {
2686 2861 }
2687 2862
2688 2863 impl Render for ConversationView {
2689 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2864 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2690 2865 let background = theme::background();
2691 2866 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2692 2867 let drafting = self.draft_active;
@@ -2698,209 +2873,40 @@ impl Render for ConversationView {
2698 2873 .child("Select a chat or channel")
2699 2874 .into_any_element();
2700 2875 }
2876 let in_feed = self.in_feed();
2877 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
2878 if in_feed && rows_seen != usize::MAX {
2879 self.feed_at_top = rows_seen == 0;
2880 }
2701 2881 let rows = self.rows.clone();
2702 let view = cx.weak_entity();
2703 let app = self.app.clone();
2704 let highlighted = self.highlighted_message.clone();
2882 let rows_seen = self.feed_rows_seen.clone();
2883 let env = RenderEnv {
2884 view: cx.weak_entity(),
2885 app: self.app.clone(),
2886 highlighted: self.highlighted_message.clone(),
2887 drafting,
2888 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
2889 };
2705 2890 let scroller = MessageScroller::new(
2706 2891 "messages",
2707 2892 self.scroller.clone(),
2708 2893 move |index, window, cx| {
2894 rows_seen.set(rows_seen.get().min(index));
2709 2895 let rows = rows.borrow();
2710 2896 match rows.get(index) {
2711 2897 Some(Row::Message(message)) => {
2712 let open_thread = message.open_thread.clone().map(|root_id| {
2713 let view = view.clone();
2714 Box::new(move |cx: &mut App| {
2715 let root_id = root_id.clone();
2716 view.update(cx, |this, cx| this.open_thread(root_id, cx))
2717 .ok();
2718 }) as Box<dyn Fn(&mut App)>
2719 });
2720 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2721 let (view, key, handle) =
2722 (view.clone(), message.key.clone(), window.window_handle());
2723 Box::new(move |cx: &mut App| {
2724 let (view, key) = (view.clone(), key.clone());
2725 handle
2726 .update(cx, move |_, window, cx| {
2727 view.update(cx, |this, cx| this.retry(&key, window, cx))
2728 .ok();
2729 })
2730 .ok();
2731 }) as Box<dyn Fn(&mut App)>
2732 });
2733 let scheduled = view.upgrade().and_then(|entity| {
2734 entity
2735 .read(cx)
2736 .scheduled_row_actions(message, &view, window, cx)
2737 });
2738 let delete = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2739 let (view, key) = (view.clone(), message.key.clone());
2740 Box::new(move |cx: &mut App| {
2741 view.update(cx, |this, cx| this.delete_pending(&key, cx))
2742 .ok();
2743 }) as Box<dyn Fn(&mut App)>
2744 });
2745 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2746 .then(|| message.sender_id.clone())
2747 .flatten()
2748 .into_iter()
2749 .chain(
2750 message
2751 .reactions
2752 .iter()
2753 .flat_map(|chip| chip.reactors.iter())
2754 .filter_map(|reactor| reactor.user_id.clone()),
2755 )
2756 .filter(|sender| app.read(cx).directory.avatar(sender).is_none())
2757 .collect();
2758 if !senders.is_empty() {
2759 let app = app.clone();
2760 cx.defer(move |cx| {
2761 app.update(cx, |state, cx| state.request_avatars(senders, cx));
2762 });
2763 }
2764 let missing_images: Vec<ImageRef> = message
2765 .images
2766 .iter()
2767 .cloned()
2768 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
2769 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2770 .collect();
2771 if !missing_images.is_empty() {
2772 let app = app.clone();
2773 cx.defer(move |cx| {
2774 app.update(cx, |state, cx| {
2775 state.request_images(missing_images, cx)
2776 });
2777 });
2778 }
2779 let is_real = !drafting
2780 && !message.key.starts_with(PENDING_KEY_PREFIX)
2781 && scheduled.is_none();
2782 let hovered = is_real.then(|| {
2783 let (view, key) = (view.clone(), message.key.clone());
2784 Rc::new(move |hovered: bool, cx: &mut App| {
2785 view.update(cx, |this, cx| {
2786 this.set_hover(HoverSlot::Row, &key, hovered, cx)
2787 })
2788 .ok();
2789 }) as Rc<dyn Fn(bool, &mut App)>
2790 });
2791 let (delivery, scheduled_menu, hovered) = match scheduled {
2792 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
2793 None => (
2794 DeliveryActions {
2795 retry,
2796 delete,
2797 send_now: None,
2798 },
2799 None,
2800 hovered,
2801 ),
2802 };
2803 let actionable = is_real && !message.deleted && !message.card;
2804 let (menu, react, reaction_controls) = view
2805 .upgrade()
2806 .filter(|_| actionable)
2807 .map(|entity| {
2808 let this = entity.read(cx);
2809 let mine = message
2810 .reactions
2811 .iter()
2812 .filter(|chip| chip.mine)
2813 .map(|chip| chip.glyph())
2814 .collect();
2815 let menu = this.message_menu(
2816 &message.key,
2817 message.own,
2818 mine,
2819 view.clone(),
2820 cx,
2821 );
2822 let react = menu.react.clone();
2823 let visible = this.toolbar_visible(&message.key);
2824 let controls = (!message.reactions.is_empty())
2825 .then(|| this.reaction_controls(&message.key, view.clone()));
2826 (visible.then_some(menu), Some(react), controls)
2827 })
2828 .unwrap_or((None, None, None));
2829 let reply = (is_real && !message.deleted).then(|| {
2830 let (view, key, handle) =
2831 (view.clone(), message.key.clone(), window.window_handle());
2832 Box::new(move |cx: &mut App| {
2833 let (view, key) = (view.clone(), key.clone());
2834 handle
2835 .update(cx, move |_, window, cx| {
2836 view.update(cx, |this, cx| {
2837 this.begin_reply(&key, window, cx)
2838 })
2839 .ok();
2840 })
2841 .ok();
2842 }) as Box<dyn Fn(&mut App)>
2843 });
2844 let files = (is_real && !message.deleted && !message.files.is_empty())
2845 .then(|| view.upgrade())
2846 .flatten()
2847 .map(|entity| {
2848 entity.read(cx).file_actions(
2849 &message.key,
2850 &message.files,
2851 view.clone(),
2852 )
2853 });
2854 let bot = message
2855 .application_id
2856 .as_deref()
2857 .and_then(|application_id| {
2858 let known = app
2859 .read(cx)
2860 .bot_identity(&message.conversation_id, application_id);
2861 if known.is_none() {
2862 let (app, conversation_id) =
2863 (app.clone(), message.conversation_id.clone());
2864 cx.defer(move |cx| {
2865 app.update(cx, |state, cx| {
2866 state.request_chat_apps(&conversation_id, cx)
2867 });
2868 });
2869 }
2870 known
2871 });
2872 ensure_cards_inputs(
2873 &app,
2874 &message.adaptive_cards,
2875 &message.conversation_id,
2876 &message.key,
2877 window,
2878 cx,
2879 );
2880 let state = app.read(cx);
2881 render_message_row(
2882 message,
2883 index,
2884 RowActions {
2885 bot,
2886 open_thread,
2887 delivery,
2888 reply,
2889 hovered,
2890 menu,
2891 scheduled_menu,
2892 react,
2893 reaction_controls,
2894 files,
2895 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2896 },
2897 &state.directory,
2898 cx,
2899 )
2898 let actions = env.message_actions(message, window, cx);
2899 let state = env.app.read(cx);
2900 render_message_row(message, index, actions, &state.directory, cx)
2901 }
2902 Some(Row::Post(post)) => {
2903 let actions = env.post_actions(post, window, cx);
2904 let state = env.app.read(cx);
2905 render_post(post, index, actions, &state.directory, cx)
2900 2906 }
2901 2907 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
2902 2908 Some(Row::LoadOlder) => {
2903 let view = view.clone();
2909 let view = env.view.clone();
2904 2910 cx.defer(move |cx| {
2905 2911 view.update(cx, |this, cx| this.request_older(cx)).ok();
2906 2912 });
@@ -2916,7 +2922,7 @@ impl Render for ConversationView {
2916 2922 .into_any_element()
2917 2923 }
2918 2924 Some(Row::Start(start)) => {
2919 let state = app.read(cx);
2925 let state = env.app.read(cx);
2920 2926 v_flex()
2921 2927 .w_full()
2922 2928 .items_center()
@@ -2949,6 +2955,7 @@ impl Render for ConversationView {
2949 2955 },
2950 2956 )
2951 2957 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2958 .jump_button(!in_feed)
2952 2959 .with_bottom_fade(background);
2953 2960
2954 2961 root = match self.current.as_ref().filter(|_| !drafting) {
@@ -2981,11 +2988,8 @@ impl Render for ConversationView {
2981 2988 }),
2982 2989 );
2983 2990 }
2984 let empty_channel = self
2985 .current
2986 .as_ref()
2987 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2988 && self.rows.borrow().is_empty();
2991 let empty_channel = in_feed && self.rows.borrow().is_empty();
2992 let new_post = self.render_new_post(window, cx);
2989 2993 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2990 2994 let draft = self.draft.read(cx);
2991 2995 let group_name = draft.group_name(cx);
@@ -3008,6 +3012,7 @@ impl Render for ConversationView {
3008 3012 .relative()
3009 3013 .flex_1()
3010 3014 .min_h_0()
3015 .children(new_post)
3011 3016 .child(
3012 3017 div()
3013 3018 .flex_1()
@@ -3018,8 +3023,11 @@ impl Render for ConversationView {
3018 3023 .child(body),
3019 3024 )
3020 3025 .children(self.render_draft_error(cx))
3021 .child(self.render_typing_line(cx))
3022 .child(self.composer.clone())
3026 .when(!in_feed, |column| {
3027 column
3028 .child(self.render_typing_line(cx))
3029 .child(self.composer.clone())
3030 })
3023 3031 .child(self.render_drop_overlay(cx)),
3024 3032 )
3025 3033 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
@@ -3028,13 +3036,15 @@ impl Render for ConversationView {
3028 3036 cx.stop_propagation();
3029 3037 }
3030 3038 }))
3031 .when(drafting, |root| {
3032 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
3039 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3040 if this.draft_active {
3033 3041 if this.draft.read(cx).has_focus(window, cx) {
3034 3042 this.draft.update(cx, |draft, cx| draft.escape(cx));
3035 3043 }
3036 }))
3037 })
3044 } else if !this.on_escape(window, cx) {
3045 cx.propagate();
3046 }
3047 }))
3038 3048 .into_any_element()
3039 3049 }
3040 3050 }
@@ -1,4 +1,4 @@
1use std::cell::RefCell;
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
4use std::rc::Rc;
@@ -9,7 +9,7 @@ use gpui_kit::assets::IconName;
9use gpui_kit::component::{
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
10 button::{Button, ButtonVariants as _},
11 h_flex,
11 h_flex,
12 input::Escape,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
14 tooltip::Tooltip,
15 v_flex,
15 v_flex,
@@ -17,17 +17,19 @@ use gpui_kit::component::{
17use gpui_kit::prelude::FluentBuilder as _;
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
18use gpui_kit::*;
19use store::{MessageRecord, OutboxState, OutboxTarget};
19use store::{MessageRecord, OutboxState, OutboxTarget};
20use teams_core::{FileCard, ImageRef, LinkPreview};
20use teams_core::{FileCard, LinkPreview};
21
21
22mod feed;
23mod render_env;
22mod scheduled;
24mod scheduled;
23
25
24use super::adaptive_card::ensure_cards_inputs;
25use super::attachments::FileActions;
26use super::attachments::FileActions;
26use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
27use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, with_presence};
27use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
28use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
28use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
29use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
29use super::message_row::{DeliveryActions, RowActions, render_message_row, render_skeleton_row};
30use super::message_row::{render_message_row, render_skeleton_row};
30use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
31use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
32use super::post_card::render_post;
31use super::reaction_picker::{PickHandler, ReactionPicker};
33use super::reaction_picker::{PickHandler, ReactionPicker};
32use super::reaction_pills::{ReactionControls, ReactionPopover};
34use super::reaction_pills::{ReactionControls, ReactionPopover};
33use super::widgets::{icon, symbol};
35use super::widgets::{icon, symbol};
@@ -45,13 +47,15 @@ use crate::read_state::{ReadTrigger, plan_read};
45use crate::rows::{
47use crate::rows::{
46 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
48 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
47 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
49 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
48 has_own_reaction, message_draft, message_text, placeholder_rows, reaction_glyph, reply_excerpt,
50 has_own_reaction, message_draft, message_text, place_local_rows, placeholder_rows,
49 set_own_reaction, thread_list_rows, thread_rows,
51 reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
50};
52};
51use crate::runtime;
53use crate::runtime;
52use crate::sidebar_model::{AvatarSpec, Face};
54use crate::sidebar_model::{AvatarSpec, Face};
53use crate::theme;
55use crate::theme;
54use crate::typing::typing_tooltip;
56use crate::typing::typing_tooltip;
57use feed::{FeedStash, subject_input};
58use render_env::RenderEnv;
55
59
56const CHAT_OPEN_LIMIT: usize = 60;
60const CHAT_OPEN_LIMIT: usize = 60;
57const CHANNEL_OPEN_LIMIT: usize = 300;
61const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -129,6 +133,13 @@ pub struct ConversationView {
129 app: Entity<AppState>,
133 app: Entity<AppState>,
130 scroller: Entity<MessageScrollerState>,
134 scroller: Entity<MessageScrollerState>,
131 composer: Entity<Composer>,
135 composer: Entity<Composer>,
136 subject: Entity<InputState>,
137 new_post_open: bool,
138 reply_composer: Option<Entity<Composer>>,
139 reply_root: Option<String>,
140 feed_stash: Option<FeedStash>,
141 feed_rows_seen: Rc<Cell<usize>>,
142 feed_at_top: bool,
132 draft: Entity<NewChatDraft>,
143 draft: Entity<NewChatDraft>,
133 draft_active: bool,
144 draft_active: bool,
134 draft_created: Option<(Vec<String>, String)>,
145 draft_created: Option<(Vec<String>, String)>,
@@ -195,6 +206,17 @@ fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String,
195 }
206 }
196}
207}
197
208
209fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
210 match mode {
211 ViewMode::Flat => record.target == OutboxTarget::Flat,
212 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
213 ViewMode::Thread(root_id) => {
214 record.target == OutboxTarget::Thread
215 && record.thread_root_id.as_deref() == Some(root_id.as_str())
216 }
217 }
218}
219
198enum DownloadEvent {
220enum DownloadEvent {
199 Progress(u8),
221 Progress(u8),
200 Finished(Result<PathBuf, String>),
222 Finished(Result<PathBuf, String>),
@@ -334,6 +356,7 @@ impl ConversationView {
334 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
356 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
335 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
357 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
336 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
358 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
359 let subject = subject_input(window, cx);
337 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
360 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
338 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
361 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
339 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
362 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
@@ -341,6 +364,7 @@ impl ConversationView {
341 cx.subscribe_in(&app, window, Self::on_app_event),
364 cx.subscribe_in(&app, window, Self::on_app_event),
342 cx.subscribe_in(&composer, window, Self::on_composer_event),
365 cx.subscribe_in(&composer, window, Self::on_composer_event),
343 cx.subscribe_in(&draft, window, Self::on_draft_event),
366 cx.subscribe_in(&draft, window, Self::on_draft_event),
367 cx.subscribe_in(&subject, window, Self::on_subject_event),
344 cx.observe_window_activation(window, Self::on_window_activation),
368 cx.observe_window_activation(window, Self::on_window_activation),
345 cx.on_app_quit(|this, cx| {
369 cx.on_app_quit(|this, cx| {
346 this.composer
370 this.composer
@@ -357,6 +381,13 @@ impl ConversationView {
357 app,
381 app,
358 scroller,
382 scroller,
359 composer,
383 composer,
384 subject,
385 new_post_open: false,
386 reply_composer: None,
387 reply_root: None,
388 feed_stash: None,
389 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
390 feed_at_top: true,
360 draft,
391 draft,
361 draft_active: false,
392 draft_active: false,
362 draft_created: None,
393 draft_created: None,
@@ -510,21 +541,7 @@ impl ConversationView {
510 cx: &mut Context<Self>,
541 cx: &mut Context<Self>,
511 ) {
542 ) {
512 match event {
543 match event {
513 ComposerEvent::Submit(outgoing) if self.draft_active => {
544 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
514 self.send_new_chat((**outgoing).clone(), window, cx)
515 }
516 ComposerEvent::Submit(outgoing)
517 if outgoing
518 .edit
519 .as_ref()
520 .is_some_and(|edit| edit.scheduled.is_some()) =>
521 {
522 self.send_scheduled_edit((**outgoing).clone(), window, cx)
523 }
524 ComposerEvent::Submit(outgoing) if outgoing.edit.is_some() => {
525 self.send_edit((**outgoing).clone(), window, cx)
526 }
527 ComposerEvent::Submit(outgoing) => self.send((**outgoing).clone(), window, cx),
528 ComposerEvent::Schedule { outgoing, send_at } => {
545 ComposerEvent::Schedule { outgoing, send_at } => {
529 self.schedule((**outgoing).clone(), *send_at, window, cx)
546 self.schedule((**outgoing).clone(), *send_at, window, cx)
530 }
547 }
@@ -533,25 +550,43 @@ impl ConversationView {
533 }
550 }
534 }
551 }
535
552
536 fn typing_target(&self) -> Option<(String, Option<String>)> {
553 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
537 let current = self.current.as_ref().filter(|_| !self.draft_active)?;
554 if self.draft_active {
538 let thread_root_id = match &current.mode {
555 return self.send_new_chat(outgoing, window, cx);
539 ViewMode::Thread(root_id) => Some(root_id.clone()),
556 }
540 ViewMode::Flat | ViewMode::ThreadList => None,
557 let in_feed = self.in_feed();
541 };
558 if in_feed && outgoing.edit.is_none() {
542 Some((
559 outgoing.subject = self.take_subject(window, cx);
543 current.selection.conversation_id().to_owned(),
560 }
544 thread_root_id,
561 if in_feed {
545 ))
562 self.close_new_post(cx);
563 }
564 match &outgoing.edit {
565 Some(edit) if edit.scheduled.is_some() => {
566 self.send_scheduled_edit(outgoing, window, cx)
567 }
568 Some(_) => self.send_edit(outgoing, window, cx),
569 None => self.send(outgoing, window, cx),
570 }
571 }
572
573 fn typing_root(&self) -> Option<String> {
574 match self.current.as_ref().map(|current| &current.mode) {
575 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
576 _ => None,
577 }
546 }
578 }
547
579
548 fn send_typing(&self, active: bool, cx: &App) {
580 fn send_typing(&self, active: bool, cx: &App) {
581 self.send_typing_in(self.typing_root(), active, cx);
582 }
583
584 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
549 let state = self.app.read(cx);
585 let state = self.app.read(cx);
550 if state.mode.demo || state.mode.read_only {
586 if state.mode.demo || state.mode.read_only || self.draft_active {
551 return;
587 return;
552 }
588 }
553 let (Some(engine), Some((conversation_id, thread_root_id))) =
589 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
554 (state.engine.clone(), self.typing_target())
555 else {
590 else {
556 return;
591 return;
557 };
592 };
@@ -611,6 +646,11 @@ impl ConversationView {
611
646
612 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
647 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
613 self.stop_typing(cx);
648 self.stop_typing(cx);
649 self.stop_reply_typing(cx);
650 self.new_post_open = false;
651 self.feed_stash = None;
652 self.feed_at_top = true;
653 self.restore_subject(None, window, cx);
614 self.toolbar_hovered = None;
654 self.toolbar_hovered = None;
615 self.toolbar_pinned = None;
655 self.toolbar_pinned = None;
616 self.toolbar_suppressed = None;
656 self.toolbar_suppressed = None;
@@ -655,7 +695,8 @@ impl ConversationView {
655 self.composer.update(cx, |composer, cx| {
695 self.composer.update(cx, |composer, cx| {
656 composer.set_conversation(&target.0, &target.1, window, cx);
696 composer.set_conversation(&target.0, &target.1, window, cx);
657 });
697 });
658 if !self.draft_active {
698 self.sync_reply_composer(window, cx);
699 if !self.draft_active && !self.in_feed() {
659 self.composer
700 self.composer
660 .update(cx, |composer, cx| composer.focus(window, cx));
701 .update(cx, |composer, cx| composer.focus(window, cx));
661 }
702 }
@@ -767,19 +808,17 @@ impl ConversationView {
767 .borrow()
808 .borrow()
768 .iter()
809 .iter()
769 .enumerate()
810 .enumerate()
770 .filter_map(|(index, row)| match row {
811 .filter(|(_, row)| {
771 Row::Message(message)
812 row.messages().any(|message| {
772 if message.images.iter().any(|image| keys.contains(&image.url))
813 message.images.iter().any(|image| keys.contains(&image.url))
773 || message
814 || message
774 .link_preview
815 .link_preview
775 .as_ref()
816 .as_ref()
776 .and_then(LinkPreview::image)
817 .and_then(LinkPreview::image)
777 .is_some_and(|image| keys.contains(&image.url)) =>
818 .is_some_and(|image| keys.contains(&image.url))
778 {
819 })
779 Some(index)
780 }
781 _ => None,
782 })
820 })
821 .map(|(index, _)| index)
783 .collect();
822 .collect();
784 self.scroller.update(cx, |scroller, cx| {
823 self.scroller.update(cx, |scroller, cx| {
785 for index in indices {
824 for index in indices {
@@ -803,10 +842,11 @@ impl ConversationView {
803 .borrow()
842 .borrow()
804 .iter()
843 .iter()
805 .enumerate()
844 .enumerate()
806 .filter_map(|(index, row)| match row {
845 .filter(|(_, row)| {
807 Row::Message(message) if !message.adaptive_cards.is_empty() => Some(index),
846 row.messages()
808 _ => None,
847 .any(|message| !message.adaptive_cards.is_empty())
809 })
848 })
849 .map(|(index, _)| index)
810 .collect();
850 .collect();
811 self.scroller.update(cx, |scroller, cx| {
851 self.scroller.update(cx, |scroller, cx| {
812 for index in indices {
852 for index in indices {
@@ -867,13 +907,23 @@ impl ConversationView {
867 .loaded_limit
907 .loaded_limit
868 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
908 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
869 current.first_unread = None;
909 current.first_unread = None;
870 if matches!(current.selection, Selection::Channel(_)) {
910 let in_channel = matches!(current.selection, Selection::Channel(_));
871 current.mode = match record.reply_to_id {
911 if in_channel {
872 Some(root_id) => ViewMode::Thread(root_id),
912 match record.reply_to_id.clone() {
873 None => ViewMode::ThreadList,
913 Some(root_id) => {
874 };
914 self.enter_thread_mode(root_id.clone(), cx);
915 self.refresh_thread(root_id, cx);
916 }
917 None => {
918 self.enter_feed_mode();
919 }
920 }
875 }
921 }
876 let target_key = if matches!(current.mode, ViewMode::Thread(_)) {
922 let in_thread = self
923 .current
924 .as_ref()
925 .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_)));
926 let target_key = if in_thread {
877 message_id.to_owned()
927 message_id.to_owned()
878 } else {
928 } else {
879 row_key
929 row_key
@@ -916,10 +966,14 @@ impl ConversationView {
916 }
966 }
917
967
918 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
968 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
919 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
969 let key = self
920 Row::Message(message) if !message.own => Some(message.key.clone()),
970 .rows
921 _ => None,
971 .borrow()
922 });
972 .iter()
973 .rev()
974 .flat_map(Row::messages)
975 .find(|message| !message.own)
976 .map(|message| message.key.clone());
923 if let Some(key) = key {
977 if let Some(key) = key {
924 self.begin_reply(&key, window, cx);
978 self.begin_reply(&key, window, cx);
925 }
979 }
@@ -956,6 +1010,15 @@ impl ConversationView {
956 .unwrap_or_else(|| "Unknown".to_owned()),
1010 .unwrap_or_else(|| "Unknown".to_owned()),
957 excerpt: reply_excerpt(&record),
1011 excerpt: reply_excerpt(&record),
958 };
1012 };
1013 if self.in_feed() {
1014 let root_id = record
1015 .reply_to_id
1016 .clone()
1017 .unwrap_or_else(|| record.message_id.clone());
1018 let quote = record.reply_to_id.is_some().then_some(preview);
1019 self.open_reply_editor(root_id, quote, window, cx);
1020 return;
1021 }
959 self.composer.update(cx, |composer, cx| {
1022 self.composer.update(cx, |composer, cx| {
960 composer.set_reply(Some(preview), cx);
1023 composer.set_reply(Some(preview), cx);
961 composer.focus(window, cx);
1024 composer.focus(window, cx);
@@ -996,10 +1059,7 @@ impl ConversationView {
996 self.rows
1059 self.rows
997 .borrow()
1060 .borrow()
998 .iter()
1061 .iter()
999 .filter_map(|row| match row {
1062 .flat_map(Row::messages)
1000 Row::Message(message) => Some(message),
1001 _ => None,
1002 })
1003 .flat_map(|message| message.reactions.iter())
1063 .flat_map(|message| message.reactions.iter())
1004 .flat_map(|chip| chip.reactors.iter())
1064 .flat_map(|chip| chip.reactors.iter())
1005 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
1065 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
@@ -1025,19 +1085,30 @@ impl ConversationView {
1025 let Some(details) = self.reaction_details.as_ref() else {
1085 let Some(details) = self.reaction_details.as_ref() else {
1026 return;
1086 return;
1027 };
1087 };
1028 let present = self.rows.borrow().iter().any(|row| {
1088 let present = self
1029 matches!(row, Row::Message(message) if message.key == details.message_key
1089 .rows
1030 && message.reactions.iter().any(|chip| chip.glyph() == details.anchor_glyph))
1090 .borrow()
1031 });
1091 .iter()
1092 .flat_map(Row::messages)
1093 .any(|message| {
1094 message.key == details.message_key
1095 && message
1096 .reactions
1097 .iter()
1098 .any(|chip| chip.glyph() == details.anchor_glyph)
1099 });
1032 if !present {
1100 if !present {
1033 self.reaction_details = None;
1101 self.reaction_details = None;
1034 }
1102 }
1035 }
1103 }
1036
1104
1037 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1105 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1038 let multiple_kinds = self.rows.borrow().iter().any(|row| {
1106 let multiple_kinds = self
1039 matches!(row, Row::Message(message) if message.key == message_key && message.reactions.len() > 1)
1107 .rows
1040 });
1108 .borrow()
1109 .iter()
1110 .flat_map(Row::messages)
1111 .any(|message| message.key == message_key && message.reactions.len() > 1);
1041 self.reaction_details = Some(ReactionDetails {
1112 self.reaction_details = Some(ReactionDetails {
1042 message_key: message_key.to_owned(),
1113 message_key: message_key.to_owned(),
1043 anchor_glyph: glyph.to_owned(),
1114 anchor_glyph: glyph.to_owned(),
@@ -1135,9 +1206,15 @@ impl ConversationView {
1135 .max(current.loaded_count + GROWTH_HEADROOM)
1206 .max(current.loaded_count + GROWTH_HEADROOM)
1136 };
1207 };
1137 let store = self.app.read(cx).store.clone();
1208 let store = self.app.read(cx).store.clone();
1138 let records: Vec<MessageRecord> = store
1209 let thread_root = match &current.mode {
1139 .messages(&conversation_id, None, limit)
1210 ViewMode::Thread(root_id) => Some(root_id.clone()),
1140 .unwrap_or_default();
1211 ViewMode::Flat | ViewMode::ThreadList => None,
1212 };
1213 let records: Vec<MessageRecord> = match &thread_root {
1214 Some(root_id) => store.thread_messages(&conversation_id, root_id),
1215 None => store.messages(&conversation_id, None, limit),
1216 }
1217 .unwrap_or_default();
1141 let sync_has_more = store
1218 let sync_has_more = store
1142 .sync_state(&conversation_id)
1219 .sync_state(&conversation_id)
1143 .ok()
1220 .ok()
@@ -1167,11 +1244,14 @@ impl ConversationView {
1167 let current = self.current.as_mut().expect("checked above");
1244 let current = self.current.as_mut().expect("checked above");
1168 let first_unread = current.first_unread.clone();
1245 let first_unread = current.first_unread.clone();
1169 current.loaded_limit = limit;
1246 current.loaded_limit = limit;
1170 current.loaded_count = records.len();
1247 if thread_root.is_none() {
1248 current.loaded_count = records.len();
1249 }
1171 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1250 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1172 let placeholders = current.sync.messages
1251 let placeholders = current.sync.messages
1173 && records.is_empty()
1252 && records.is_empty()
1174 && !matches!(current.mode, ViewMode::Thread(_));
1253 && !matches!(current.mode, ViewMode::Thread(_));
1254 let in_feed = current.mode == ViewMode::ThreadList;
1175 let mut rows = match &current.mode {
1255 let mut rows = match &current.mode {
1176 _ if placeholders => {
1256 _ if placeholders => {
1177 current.has_older = false;
1257 current.has_older = false;
@@ -1194,13 +1274,17 @@ impl ConversationView {
1194 thread_rows(&records, root_id, &context)
1274 thread_rows(&records, root_id, &context)
1195 }
1275 }
1196 };
1276 };
1197 rows.extend(
1277 let local: Vec<MessageRow> = self
1198 self.pending
1278 .pending
1199 .iter()
1279 .iter()
1200 .cloned()
1280 .cloned()
1201 .map(|row| Row::Message(Box::new(row))),
1281 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1202 );
1282 .collect();
1203 rows.extend(self.scheduled_rows(context.my_user_id.as_deref(), cx));
1283 if in_feed {
1284 place_local_rows(&mut rows, local);
1285 } else {
1286 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1287 }
1204 let receipts = self.receipts(&records, cx);
1288 let receipts = self.receipts(&records, cx);
1205 for row in rows.iter_mut() {
1289 for row in rows.iter_mut() {
1206 if let Row::Message(message) = row
1290 if let Row::Message(message) = row
@@ -1226,14 +1310,20 @@ impl ConversationView {
1226 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1310 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1227 self.drop_stale_reaction_details();
1311 self.drop_stale_reaction_details();
1228 let new_len = self.rows.borrow().len();
1312 let new_len = self.rows.borrow().len();
1313 let in_feed = self.in_feed();
1229 if reset {
1314 if reset {
1230 let marker_index = self
1315 let marker_index = self
1231 .rows
1316 .rows
1232 .borrow()
1317 .borrow()
1233 .iter()
1318 .iter()
1234 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1319 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1320 self.feed_at_top = true;
1235 self.scroller.update(cx, |scroller, cx| {
1321 self.scroller.update(cx, |scroller, cx| {
1236 scroller.reset(new_len, cx);
1322 scroller.reset(new_len, cx);
1323 if in_feed {
1324 scroller.scroll_to_item(0, cx);
1325 return;
1326 }
1237 match marker_index {
1327 match marker_index {
1238 Some(index) if !scroller.scroll_to_item(index, cx) => {
1328 Some(index) if !scroller.scroll_to_item(index, cx) => {
1239 scroller.scroll_to_end(cx)
1329 scroller.scroll_to_end(cx)
@@ -1254,12 +1344,19 @@ impl ConversationView {
1254 changed_indices(&old_rows, &new_rows),
1344 changed_indices(&old_rows, &new_rows),
1255 )
1345 )
1256 };
1346 };
1347 let top_changed = splice
1348 .as_ref()
1349 .is_some_and(|splice| splice.range.start == 0);
1350 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1257 self.scroller.update(cx, |scroller, cx| {
1351 self.scroller.update(cx, |scroller, cx| {
1258 if let Some(splice) = splice
1352 if let Some(splice) = splice
1259 && !scroller.splice(splice.range, splice.count, cx)
1353 && !scroller.splice(splice.range, splice.count, cx)
1260 {
1354 {
1261 scroller.reset(new_len, cx);
1355 scroller.reset(new_len, cx);
1262 }
1356 }
1357 if keep_top {
1358 scroller.scroll_to_item(0, cx);
1359 }
1263 for index in changed {
1360 for index in changed {
1264 scroller.remeasure_items(index..index + 1, cx);
1361 scroller.remeasure_items(index..index + 1, cx);
1265 }
1362 }
@@ -1281,12 +1378,14 @@ impl ConversationView {
1281 }
1378 }
1282 current.fetched = true;
1379 current.fetched = true;
1283 let is_chat = matches!(current.selection, Selection::Chat(_));
1380 let is_chat = matches!(current.selection, Selection::Chat(_));
1284 let newest_cached = self.rows.borrow().iter().rev().find_map(|row| match row {
1381 let newest_cached = self
1285 Row::Message(message) if !message.key.starts_with(PENDING_KEY_PREFIX) => {
1382 .rows
1286 Some(message.created_at)
1383 .borrow()
1287 }
1384 .iter()
1288 _ => None,
1385 .flat_map(Row::messages)
1289 });
1386 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1387 .map(|message| message.created_at)
1388 .max();
1290 let current = self.current.as_mut().expect("checked above");
1389 let current = self.current.as_mut().expect("checked above");
1291 if current.sync.failed {
1390 if current.sync.failed {
1292 self.notice = None;
1391 self.notice = None;
@@ -1632,7 +1731,10 @@ impl ConversationView {
1632 self.pending_outgoing.clear();
1731 self.pending_outgoing.clear();
1633 }
1732 }
1634
1733
1635 fn outbox_route(&self) -> (OutboxTarget, Option<String>) {
1734 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
1735 if let Some(root_id) = reply_root {
1736 return (OutboxTarget::Thread, Some(root_id));
1737 }
1636 match self.current.as_ref().map(|current| &current.mode) {
1738 match self.current.as_ref().map(|current| &current.mode) {
1637 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1739 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
1638 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
1740 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
@@ -1654,9 +1756,9 @@ impl ConversationView {
1654 return;
1756 return;
1655 };
1757 };
1656 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1758 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
1657 let route = self.outbox_route();
1759 let mut pending = Vec::new();
1658 for record in records {
1760 for record in records {
1659 if (record.target, record.thread_root_id.clone()) != route {
1761 if !shown_in_view(&current.mode, &record) {
1660 continue;
1762 continue;
1661 }
1763 }
1662 let Some(outgoing) = outgoing_of(&record) else {
1764 let Some(outgoing) = outgoing_of(&record) else {
@@ -1666,15 +1768,20 @@ impl ConversationView {
1666 OutboxState::Sending => Delivery::Sending,
1768 OutboxState::Sending => Delivery::Sending,
1667 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1769 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
1668 };
1770 };
1669 self.pending.push(pending_row(
1771 let mut row = pending_row(
1670 record.id.clone(),
1772 record.id.clone(),
1671 conversation_id.clone(),
1773 conversation_id.clone(),
1672 my_user_id.clone(),
1774 my_user_id.clone(),
1673 record.created_at,
1775 record.created_at,
1674 &outgoing,
1776 &outgoing,
1675 delivery,
1777 delivery,
1676 ));
1778 );
1677 self.pending_outgoing.insert(record.id, outgoing);
1779 row.reply_root = record.thread_root_id.clone();
1780 pending.push((row, record.id, outgoing));
1781 }
1782 for (row, id, outgoing) in pending {
1783 self.pending.push(row);
1784 self.pending_outgoing.insert(id, outgoing);
1678 }
1785 }
1679 }
1786 }
1680
1787
@@ -1691,32 +1798,25 @@ impl ConversationView {
1691 self.rebuild(false, cx);
1798 self.rebuild(false, cx);
1692 }
1799 }
1693
1800
1694 fn open_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
1801 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1695 self.stop_typing(cx);
1802 self.send_as(new_outbox_id(), outgoing, None, window, cx);
1696 if let Some(current) = self.current.as_mut() {
1697 current.mode = ViewMode::Thread(root_id);
1698 }
1699 self.reload_pending(cx);
1700 self.rebuild(true, cx);
1701 }
1702
1703 fn back_to_threads(&mut self, cx: &mut Context<Self>) {
1704 self.stop_typing(cx);
1705 if let Some(current) = self.current.as_mut() {
1706 current.mode = ViewMode::ThreadList;
1707 }
1708 self.reload_pending(cx);
1709 self.rebuild(true, cx);
1710 }
1803 }
1711
1804
1712 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
1805 fn send_in_thread(
1713 self.send_as(new_outbox_id(), outgoing, window, cx);
1806 &mut self,
1807 root_id: String,
1808 outgoing: Outgoing,
1809 window: &mut Window,
1810 cx: &mut Context<Self>,
1811 ) {
1812 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
1714 }
1813 }
1715
1814
1716 fn send_as(
1815 fn send_as(
1717 &mut self,
1816 &mut self,
1718 id: String,
1817 id: String,
1719 outgoing: Outgoing,
1818 outgoing: Outgoing,
1819 reply_root: Option<String>,
1720 window: &mut Window,
1820 window: &mut Window,
1721 cx: &mut Context<Self>,
1821 cx: &mut Context<Self>,
1722 ) {
1822 ) {
@@ -1726,18 +1826,36 @@ impl ConversationView {
1726 return;
1826 return;
1727 };
1827 };
1728 if mode.read_only || mode.demo {
1828 if mode.read_only || mode.demo {
1729 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1829 self.restore_unsent(
1830 "Read-only mode: nothing was sent",
1831 &outgoing,
1832 reply_root.as_deref(),
1833 window,
1834 cx,
1835 );
1730 return;
1836 return;
1731 }
1837 }
1732 let Some(engine) = engine else {
1838 let Some(engine) = engine else {
1733 self.discard_outbox_row(&id, cx);
1839 self.discard_outbox_row(&id, cx);
1734 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1840 self.restore_unsent(
1841 "Not connected yet: nothing was sent",
1842 &outgoing,
1843 reply_root.as_deref(),
1844 window,
1845 cx,
1846 );
1735 return;
1847 return;
1736 };
1848 };
1737 let conversation_id = current.selection.conversation_id().to_owned();
1849 let conversation_id = current.selection.conversation_id().to_owned();
1738 let (target, thread_root_id) = self.outbox_route();
1850 let (target, thread_root_id) = self.outbox_route(reply_root);
1739 let created_at = Utc::now();
1851 let created_at = Utc::now();
1740 self.push_pending(id.clone(), created_at, &outgoing, cx);
1852 self.push_pending(
1853 id.clone(),
1854 created_at,
1855 &outgoing,
1856 thread_root_id.clone(),
1857 cx,
1858 );
1741 if let Some(record) = outbox_record(
1859 if let Some(record) = outbox_record(
1742 &id,
1860 &id,
1743 &conversation_id,
1861 &conversation_id,
@@ -1750,8 +1868,13 @@ impl ConversationView {
1750 }
1868 }
1751 self.notice = None;
1869 self.notice = None;
1752 self.rebuild(false, cx);
1870 self.rebuild(false, cx);
1753 self.scroller
1871 if self.in_feed() {
1754 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1872 self.scroller
1873 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
1874 } else {
1875 self.scroller
1876 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
1877 }
1755
1878
1756 let receiver = runtime::spawn(async move {
1879 let receiver = runtime::spawn(async move {
1757 deliver(
1880 deliver(
@@ -1775,12 +1898,22 @@ impl ConversationView {
1775 &mut self,
1898 &mut self,
1776 message: &str,
1899 message: &str,
1777 outgoing: &Outgoing,
1900 outgoing: &Outgoing,
1901 reply_root: Option<&str>,
1778 window: &mut Window,
1902 window: &mut Window,
1779 cx: &mut Context<Self>,
1903 cx: &mut Context<Self>,
1780 ) {
1904 ) {
1781 self.notice = Some(message.to_owned());
1905 self.notice = Some(message.to_owned());
1782 self.composer
1906 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
1783 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1907 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
1908 if let Some(composer) = self.reply_composer.clone() {
1909 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1910 }
1911 } else {
1912 self.show_main_composer(cx);
1913 self.restore_subject(outgoing.subject.as_deref(), window, cx);
1914 self.composer
1915 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
1916 }
1784 cx.notify();
1917 cx.notify();
1785 }
1918 }
1786
1919
@@ -1794,6 +1927,7 @@ impl ConversationView {
1794 key: String,
1927 key: String,
1795 created_at: DateTime<Utc>,
1928 created_at: DateTime<Utc>,
1796 outgoing: &Outgoing,
1929 outgoing: &Outgoing,
1930 reply_root: Option<String>,
1797 cx: &App,
1931 cx: &App,
1798 ) {
1932 ) {
1799 let my_user_id = self.row_context(cx).my_user_id;
1933 let my_user_id = self.row_context(cx).my_user_id;
@@ -1802,14 +1936,16 @@ impl ConversationView {
1802 .as_ref()
1936 .as_ref()
1803 .map(|current| current.selection.conversation_id().to_owned())
1937 .map(|current| current.selection.conversation_id().to_owned())
1804 .unwrap_or_default();
1938 .unwrap_or_default();
1805 self.pending.push(pending_row(
1939 let mut row = pending_row(
1806 key.clone(),
1940 key.clone(),
1807 conversation_id,
1941 conversation_id,
1808 my_user_id,
1942 my_user_id,
1809 created_at,
1943 created_at,
1810 outgoing,
1944 outgoing,
1811 Delivery::Sending,
1945 Delivery::Sending,
1812 ));
1946 );
1947 row.reply_root = reply_root;
1948 self.pending.push(row);
1813 self.pending_outgoing.insert(key, outgoing.clone());
1949 self.pending_outgoing.insert(key, outgoing.clone());
1814 }
1950 }
1815
1951
@@ -1820,7 +1956,7 @@ impl ConversationView {
1820 (draft.chips().to_vec(), topic)
1956 (draft.chips().to_vec(), topic)
1821 };
1957 };
1822 if recipients.is_empty() {
1958 if recipients.is_empty() {
1823 self.restore_unsent("Add at least one person first", &outgoing, window, cx);
1959 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
1824 self.draft
1960 self.draft
1825 .update(cx, |draft, cx| draft.focus_query(window, cx));
1961 .update(cx, |draft, cx| draft.focus_query(window, cx));
1826 return;
1962 return;
@@ -1830,17 +1966,29 @@ impl ConversationView {
1830 .iter()
1966 .iter()
1831 .any(|row| matches!(row.delivery, Delivery::Sending))
1967 .any(|row| matches!(row.delivery, Delivery::Sending))
1832 {
1968 {
1833 self.restore_unsent("Still creating the chat", &outgoing, window, cx);
1969 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
1834 return;
1970 return;
1835 }
1971 }
1836 let state = self.app.read(cx);
1972 let state = self.app.read(cx);
1837 let (mode, engine) = (state.mode, state.engine.clone());
1973 let (mode, engine) = (state.mode, state.engine.clone());
1838 if mode.read_only {
1974 if mode.read_only {
1839 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1975 self.restore_unsent(
1976 "Read-only mode: nothing was sent",
1977 &outgoing,
1978 None,
1979 window,
1980 cx,
1981 );
1840 return;
1982 return;
1841 }
1983 }
1842 if mode.demo && outgoing.has_attachments() {
1984 if mode.demo && outgoing.has_attachments() {
1843 self.restore_unsent("Read-only mode: nothing was sent", &outgoing, window, cx);
1985 self.restore_unsent(
1986 "Read-only mode: nothing was sent",
1987 &outgoing,
1988 None,
1989 window,
1990 cx,
1991 );
1844 return;
1992 return;
1845 }
1993 }
1846 if mode.demo {
1994 if mode.demo {
@@ -1848,7 +1996,13 @@ impl ConversationView {
1848 return;
1996 return;
1849 }
1997 }
1850 let Some(engine) = engine else {
1998 let Some(engine) = engine else {
1851 self.restore_unsent("Not connected yet: nothing was sent", &outgoing, window, cx);
1999 self.restore_unsent(
2000 "Not connected yet: nothing was sent",
2001 &outgoing,
2002 None,
2003 window,
2004 cx,
2005 );
1852 return;
2006 return;
1853 };
2007 };
1854 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2008 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
@@ -1863,7 +2017,7 @@ impl ConversationView {
1863 self.draft_error = None;
2017 self.draft_error = None;
1864 self.notice = None;
2018 self.notice = None;
1865 let key = self.next_pending_key();
2019 let key = self.next_pending_key();
1866 self.push_pending(key.clone(), Utc::now(), &outgoing, cx);
2020 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
1867 self.rebuild(true, cx);
2021 self.rebuild(true, cx);
1868 let recipients_for_finish = user_ids.clone();
2022 let recipients_for_finish = user_ids.clone();
1869 let receiver = runtime::spawn(async move {
2023 let receiver = runtime::spawn(async move {
@@ -2202,6 +2356,7 @@ impl ConversationView {
2202 };
2356 };
2203 let draft = Outgoing {
2357 let draft = Outgoing {
2204 draft: message_draft(&record),
2358 draft: message_draft(&record),
2359 subject: None,
2205 mentions,
2360 mentions,
2206 reply: None,
2361 reply: None,
2207 edit: Some(edit),
2362 edit: Some(edit),
@@ -2209,6 +2364,7 @@ impl ConversationView {
2209 files: Vec::new(),
2364 files: Vec::new(),
2210 link_preview: None,
2365 link_preview: None,
2211 };
2366 };
2367 self.show_main_composer(cx);
2212 self.composer
2368 self.composer
2213 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2369 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2214 }
2370 }
@@ -2217,16 +2373,16 @@ impl ConversationView {
2217 if self.draft_active {
2373 if self.draft_active {
2218 return;
2374 return;
2219 }
2375 }
2220 let key = self.rows.borrow().iter().rev().find_map(|row| match row {
2376 let key = self
2221 Row::Message(message)
2377 .rows
2222 if message.own
2378 .borrow()
2223 && !message.deleted
2379 .iter()
2224 && !message.key.starts_with(PENDING_KEY_PREFIX) =>
2380 .flat_map(Row::messages)
2225 {
2381 .filter(|message| {
2226 Some(message.key.clone())
2382 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2227 }
2383 })
2228 _ => None,
2384 .max_by_key(|message| message.created_at)
2229 });
2385 .map(|message| message.key.clone());
2230 if let Some(key) = key {
2386 if let Some(key) = key {
2231 self.begin_edit(&key, window, cx);
2387 self.begin_edit(&key, window, cx);
2232 }
2388 }
@@ -2252,6 +2408,7 @@ impl ConversationView {
2252 }
2408 }
2253 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2409 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2254 self.notice = Some("Read-only mode: edit not saved".to_owned());
2410 self.notice = Some("Read-only mode: edit not saved".to_owned());
2411 self.show_main_composer(cx);
2255 self.composer
2412 self.composer
2256 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2413 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2257 cx.notify();
2414 cx.notify();
@@ -2272,6 +2429,7 @@ impl ConversationView {
2272 let failed = !matches!(receiver.await, Ok(Ok(())));
2429 let failed = !matches!(receiver.await, Ok(Ok(())));
2273 this.update_in(cx, |this, window, cx| {
2430 this.update_in(cx, |this, window, cx| {
2274 if failed {
2431 if failed {
2432 this.show_main_composer(cx);
2275 if this.composer.read(cx).is_empty(cx) {
2433 if this.composer.read(cx).is_empty(cx) {
2276 this.notice =
2434 this.notice =
2277 Some("Edit failed: your text is back in the composer".to_owned());
2435 Some("Edit failed: your text is back in the composer".to_owned());
@@ -2414,11 +2572,16 @@ impl ConversationView {
2414 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2572 let Some(outgoing) = self.pending_outgoing.remove(key) else {
2415 return;
2573 return;
2416 };
2574 };
2575 let reply_root = self
2576 .pending
2577 .iter()
2578 .find(|row| row.key == key)
2579 .and_then(|row| row.reply_root.clone());
2417 self.pending.retain(|row| row.key != key);
2580 self.pending.retain(|row| row.key != key);
2418 if self.draft_active {
2581 if self.draft_active {
2419 self.send_new_chat(outgoing, window, cx);
2582 self.send_new_chat(outgoing, window, cx);
2420 } else {
2583 } else {
2421 self.send_as(key.to_owned(), outgoing, window, cx);
2584 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
2422 }
2585 }
2423 }
2586 }
2424
2587
@@ -2624,17 +2787,29 @@ impl ConversationView {
2624 .border_color(theme::border());
2787 .border_color(theme::border());
2625 if matches!(current.mode, ViewMode::Thread(_)) {
2788 if matches!(current.mode, ViewMode::Thread(_)) {
2626 header = header.child(
2789 header = header.child(
2627 Button::new("back-to-threads")
2790 h_flex()
2628 .ghost()
2791 .id("back-to-channel")
2629 .compact()
2792 .flex_none()
2630 .label("Threads")
2793 .gap(px(2.))
2631 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))),
2794 .pl(px(4.))
2795 .pr(px(8.))
2796 .py(px(4.))
2797 .items_center()
2798 .rounded(px(6.))
2799 .cursor_pointer()
2800 .text_size(px(13.))
2801 .font_weight(FontWeight::SEMIBOLD)
2802 .text_color(theme::accent_text())
2803 .hover(|button| button.bg(theme::row_hover()))
2804 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
2805 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
2806 .child("Back to channel"),
2632 );
2807 );
2633 }
2808 }
2634 let channel_note = match current.mode {
2809 let channel_note = match current.mode {
2635 ViewMode::Flat => None,
2810 ViewMode::Flat => None,
2636 ViewMode::ThreadList => Some("Threads"),
2811 ViewMode::ThreadList => Some("Posts"),
2637 ViewMode::Thread(_) => Some("Thread"),
2812 ViewMode::Thread(_) => Some("Conversation"),
2638 };
2813 };
2639 if let Some(note) = channel_note {
2814 if let Some(note) = channel_note {
2640 subline = note.to_owned();
2815 subline = note.to_owned();
@@ -2686,7 +2861,7 @@ impl ConversationView {
2686}
2861}
2687
2862
2688impl Render for ConversationView {
2863impl Render for ConversationView {
2689 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2864 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2690 let background = theme::background();
2865 let background = theme::background();
2691 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2866 let mut root = v_flex().flex_1().min_w_0().h_full().bg(background);
2692 let drafting = self.draft_active;
2867 let drafting = self.draft_active;
@@ -2698,209 +2873,40 @@ impl Render for ConversationView {
2698 .child("Select a chat or channel")
2873 .child("Select a chat or channel")
2699 .into_any_element();
2874 .into_any_element();
2700 }
2875 }
2876 let in_feed = self.in_feed();
2877 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
2878 if in_feed && rows_seen != usize::MAX {
2879 self.feed_at_top = rows_seen == 0;
2880 }
2701 let rows = self.rows.clone();
2881 let rows = self.rows.clone();
2702 let view = cx.weak_entity();
2882 let rows_seen = self.feed_rows_seen.clone();
2703 let app = self.app.clone();
2883 let env = RenderEnv {
2704 let highlighted = self.highlighted_message.clone();
2884 view: cx.weak_entity(),
2885 app: self.app.clone(),
2886 highlighted: self.highlighted_message.clone(),
2887 drafting,
2888 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
2889 };
2705 let scroller = MessageScroller::new(
2890 let scroller = MessageScroller::new(
2706 "messages",
2891 "messages",
2707 self.scroller.clone(),
2892 self.scroller.clone(),
2708 move |index, window, cx| {
2893 move |index, window, cx| {
2894 rows_seen.set(rows_seen.get().min(index));
2709 let rows = rows.borrow();
2895 let rows = rows.borrow();
2710 match rows.get(index) {
2896 match rows.get(index) {
2711 Some(Row::Message(message)) => {
2897 Some(Row::Message(message)) => {
2712 let open_thread = message.open_thread.clone().map(|root_id| {
2898 let actions = env.message_actions(message, window, cx);
2713 let view = view.clone();
2899 let state = env.app.read(cx);
2714 Box::new(move |cx: &mut App| {
2900 render_message_row(message, index, actions, &state.directory, cx)
2715 let root_id = root_id.clone();
2901 }
2716 view.update(cx, |this, cx| this.open_thread(root_id, cx))
2902 Some(Row::Post(post)) => {
2717 .ok();
2903 let actions = env.post_actions(post, window, cx);
2718 }) as Box<dyn Fn(&mut App)>
2904 let state = env.app.read(cx);
2719 });
2905 render_post(post, index, actions, &state.directory, cx)
2720 let retry = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2721 let (view, key, handle) =
2722 (view.clone(), message.key.clone(), window.window_handle());
2723 Box::new(move |cx: &mut App| {
2724 let (view, key) = (view.clone(), key.clone());
2725 handle
2726 .update(cx, move |_, window, cx| {
2727 view.update(cx, |this, cx| this.retry(&key, window, cx))
2728 .ok();
2729 })
2730 .ok();
2731 }) as Box<dyn Fn(&mut App)>
2732 });
2733 let scheduled = view.upgrade().and_then(|entity| {
2734 entity
2735 .read(cx)
2736 .scheduled_row_actions(message, &view, window, cx)
2737 });
2738 let delete = matches!(message.delivery, Delivery::Failed(_)).then(|| {
2739 let (view, key) = (view.clone(), message.key.clone());
2740 Box::new(move |cx: &mut App| {
2741 view.update(cx, |this, cx| this.delete_pending(&key, cx))
2742 .ok();
2743 }) as Box<dyn Fn(&mut App)>
2744 });
2745 let senders: Vec<String> = (!message.own && !message.series.has_prev)
2746 .then(|| message.sender_id.clone())
2747 .flatten()
2748 .into_iter()
2749 .chain(
2750 message
2751 .reactions
2752 .iter()
2753 .flat_map(|chip| chip.reactors.iter())
2754 .filter_map(|reactor| reactor.user_id.clone()),
2755 )
2756 .filter(|sender| app.read(cx).directory.avatar(sender).is_none())
2757 .collect();
2758 if !senders.is_empty() {
2759 let app = app.clone();
2760 cx.defer(move |cx| {
2761 app.update(cx, |state, cx| state.request_avatars(senders, cx));
2762 });
2763 }
2764 let missing_images: Vec<ImageRef> = message
2765 .images
2766 .iter()
2767 .cloned()
2768 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
2769 .filter(|image| app.read(cx).directory.image(&image.url).is_none())
2770 .collect();
2771 if !missing_images.is_empty() {
2772 let app = app.clone();
2773 cx.defer(move |cx| {
2774 app.update(cx, |state, cx| {
2775 state.request_images(missing_images, cx)
2776 });
2777 });
2778 }
2779 let is_real = !drafting
2780 && !message.key.starts_with(PENDING_KEY_PREFIX)
2781 && scheduled.is_none();
2782 let hovered = is_real.then(|| {
2783 let (view, key) = (view.clone(), message.key.clone());
2784 Rc::new(move |hovered: bool, cx: &mut App| {
2785 view.update(cx, |this, cx| {
2786 this.set_hover(HoverSlot::Row, &key, hovered, cx)
2787 })
2788 .ok();
2789 }) as Rc<dyn Fn(bool, &mut App)>
2790 });
2791 let (delivery, scheduled_menu, hovered) = match scheduled {
2792 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
2793 None => (
2794 DeliveryActions {
2795 retry,
2796 delete,
2797 send_now: None,
2798 },
2799 None,
2800 hovered,
2801 ),
2802 };
2803 let actionable = is_real && !message.deleted && !message.card;
2804 let (menu, react, reaction_controls) = view
2805 .upgrade()
2806 .filter(|_| actionable)
2807 .map(|entity| {
2808 let this = entity.read(cx);
2809 let mine = message
2810 .reactions
2811 .iter()
2812 .filter(|chip| chip.mine)
2813 .map(|chip| chip.glyph())
2814 .collect();
2815 let menu = this.message_menu(
2816 &message.key,
2817 message.own,
2818 mine,
2819 view.clone(),
2820 cx,
2821 );
2822 let react = menu.react.clone();
2823 let visible = this.toolbar_visible(&message.key);
2824 let controls = (!message.reactions.is_empty())
2825 .then(|| this.reaction_controls(&message.key, view.clone()));
2826 (visible.then_some(menu), Some(react), controls)
2827 })
2828 .unwrap_or((None, None, None));
2829 let reply = (is_real && !message.deleted).then(|| {
2830 let (view, key, handle) =
2831 (view.clone(), message.key.clone(), window.window_handle());
2832 Box::new(move |cx: &mut App| {
2833 let (view, key) = (view.clone(), key.clone());
2834 handle
2835 .update(cx, move |_, window, cx| {
2836 view.update(cx, |this, cx| {
2837 this.begin_reply(&key, window, cx)
2838 })
2839 .ok();
2840 })
2841 .ok();
2842 }) as Box<dyn Fn(&mut App)>
2843 });
2844 let files = (is_real && !message.deleted && !message.files.is_empty())
2845 .then(|| view.upgrade())
2846 .flatten()
2847 .map(|entity| {
2848 entity.read(cx).file_actions(
2849 &message.key,
2850 &message.files,
2851 view.clone(),
2852 )
2853 });
2854 let bot = message
2855 .application_id
2856 .as_deref()
2857 .and_then(|application_id| {
2858 let known = app
2859 .read(cx)
2860 .bot_identity(&message.conversation_id, application_id);
2861 if known.is_none() {
2862 let (app, conversation_id) =
2863 (app.clone(), message.conversation_id.clone());
2864 cx.defer(move |cx| {
2865 app.update(cx, |state, cx| {
2866 state.request_chat_apps(&conversation_id, cx)
2867 });
2868 });
2869 }
2870 known
2871 });
2872 ensure_cards_inputs(
2873 &app,
2874 &message.adaptive_cards,
2875 &message.conversation_id,
2876 &message.key,
2877 window,
2878 cx,
2879 );
2880 let state = app.read(cx);
2881 render_message_row(
2882 message,
2883 index,
2884 RowActions {
2885 bot,
2886 open_thread,
2887 delivery,
2888 reply,
2889 hovered,
2890 menu,
2891 scheduled_menu,
2892 react,
2893 reaction_controls,
2894 files,
2895 highlighted: highlighted.as_deref() == Some(message.key.as_str()),
2896 },
2897 &state.directory,
2898 cx,
2899 )
2900 }
2906 }
2901 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
2907 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
2902 Some(Row::LoadOlder) => {
2908 Some(Row::LoadOlder) => {
2903 let view = view.clone();
2909 let view = env.view.clone();
2904 cx.defer(move |cx| {
2910 cx.defer(move |cx| {
2905 view.update(cx, |this, cx| this.request_older(cx)).ok();
2911 view.update(cx, |this, cx| this.request_older(cx)).ok();
2906 });
2912 });
@@ -2916,7 +2922,7 @@ impl Render for ConversationView {
2916 .into_any_element()
2922 .into_any_element()
2917 }
2923 }
2918 Some(Row::Start(start)) => {
2924 Some(Row::Start(start)) => {
2919 let state = app.read(cx);
2925 let state = env.app.read(cx);
2920 v_flex()
2926 v_flex()
2921 .w_full()
2927 .w_full()
2922 .items_center()
2928 .items_center()
@@ -2949,6 +2955,7 @@ impl Render for ConversationView {
2949 },
2955 },
2950 )
2956 )
2951 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2957 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
2958 .jump_button(!in_feed)
2952 .with_bottom_fade(background);
2959 .with_bottom_fade(background);
2953
2960
2954 root = match self.current.as_ref().filter(|_| !drafting) {
2961 root = match self.current.as_ref().filter(|_| !drafting) {
@@ -2981,11 +2988,8 @@ impl Render for ConversationView {
2981 }),
2988 }),
2982 );
2989 );
2983 }
2990 }
2984 let empty_channel = self
2991 let empty_channel = in_feed && self.rows.borrow().is_empty();
2985 .current
2992 let new_post = self.render_new_post(window, cx);
2986 .as_ref()
2987 .is_some_and(|current| current.mode == ViewMode::ThreadList)
2988 && self.rows.borrow().is_empty();
2989 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2993 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
2990 let draft = self.draft.read(cx);
2994 let draft = self.draft.read(cx);
2991 let group_name = draft.group_name(cx);
2995 let group_name = draft.group_name(cx);
@@ -3008,6 +3012,7 @@ impl Render for ConversationView {
3008 .relative()
3012 .relative()
3009 .flex_1()
3013 .flex_1()
3010 .min_h_0()
3014 .min_h_0()
3015 .children(new_post)
3011 .child(
3016 .child(
3012 div()
3017 div()
3013 .flex_1()
3018 .flex_1()
@@ -3018,8 +3023,11 @@ impl Render for ConversationView {
3018 .child(body),
3023 .child(body),
3019 )
3024 )
3020 .children(self.render_draft_error(cx))
3025 .children(self.render_draft_error(cx))
3021 .child(self.render_typing_line(cx))
3026 .when(!in_feed, |column| {
3022 .child(self.composer.clone())
3027 column
3028 .child(self.render_typing_line(cx))
3029 .child(self.composer.clone())
3030 })
3023 .child(self.render_drop_overlay(cx)),
3031 .child(self.render_drop_overlay(cx)),
3024 )
3032 )
3025 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3033 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
@@ -3028,13 +3036,15 @@ impl Render for ConversationView {
3028 cx.stop_propagation();
3036 cx.stop_propagation();
3029 }
3037 }
3030 }))
3038 }))
3031 .when(drafting, |root| {
3039 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3032 root.on_action(cx.listener(|this, _: &Escape, window, cx| {
3040 if this.draft_active {
3033 if this.draft.read(cx).has_focus(window, cx) {
3041 if this.draft.read(cx).has_focus(window, cx) {
3034 this.draft.update(cx, |draft, cx| draft.escape(cx));
3042 this.draft.update(cx, |draft, cx| draft.escape(cx));
3035 }
3043 }
3036 }))
3044 } else if !this.on_escape(window, cx) {
3037 })
3045 cx.propagate();
3046 }
3047 }))
3038 .into_any_element()
3048 .into_any_element()
3039 }
3049 }
3040}
3050}
crates/app/src/views/conversation/feed.rs added +443 −0
@@ -0,0 +1,443 @@
1 use std::cell::RefCell;
2 use std::rc::Rc;
3
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputEvent, InputState},
9 message_scroller::MessageScrollerState,
10 v_flex,
11 };
12 use gpui_kit::*;
13
14 use super::{ConversationView, ViewMode};
15 use crate::notice::short_error;
16 use crate::rows::Row;
17 use crate::runtime;
18 use crate::theme;
19 use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20 use crate::views::widgets::icon;
21
22 const REPLY_PLACEHOLDER: &str = "Reply";
23 const SUBJECT_PLACEHOLDER: &str = "Add a subject";
24
25 pub(super) struct FeedStash {
26 scroller: Entity<MessageScrollerState>,
27 rows: Rc<RefCell<Vec<Row>>>,
28 near_top: bool,
29 }
30
31 pub(super) fn subject_input(
32 window: &mut Window,
33 cx: &mut Context<ConversationView>,
34 ) -> Entity<InputState> {
35 cx.new(|cx| InputState::new(window, cx).placeholder(SUBJECT_PLACEHOLDER))
36 }
37
38 impl ConversationView {
39 pub(super) fn in_feed(&self) -> bool {
40 !self.draft_active
41 && self
42 .current
43 .as_ref()
44 .is_some_and(|current| current.mode == ViewMode::ThreadList)
45 }
46
47 pub(super) fn open_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
48 self.new_post_open = true;
49 self.composer
50 .update(cx, |composer, cx| composer.focus(window, cx));
51 cx.notify();
52 }
53
54 pub(super) fn close_new_post(&mut self, cx: &mut Context<Self>) {
55 if self.new_post_open {
56 self.new_post_open = false;
57 cx.notify();
58 }
59 }
60
61 pub(super) fn take_subject(
62 &mut self,
63 window: &mut Window,
64 cx: &mut Context<Self>,
65 ) -> Option<String> {
66 let subject = self.subject.read(cx).value().trim().to_owned();
67 self.subject
68 .update(cx, |input, cx| input.set_value("", window, cx));
69 (!subject.is_empty()).then_some(subject)
70 }
71
72 pub(super) fn restore_subject(
73 &mut self,
74 subject: Option<&str>,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 let subject = subject.unwrap_or_default().to_owned();
79 self.subject
80 .update(cx, |input, cx| input.set_value(subject, window, cx));
81 }
82
83 pub(super) fn has_subject(&self, cx: &App) -> bool {
84 !self.subject.read(cx).value().trim().is_empty()
85 }
86
87 pub(super) fn on_subject_event(
88 &mut self,
89 _: &Entity<InputState>,
90 event: &InputEvent,
91 window: &mut Window,
92 cx: &mut Context<Self>,
93 ) {
94 if matches!(event, InputEvent::PressEnter { .. }) {
95 self.composer
96 .update(cx, |composer, cx| composer.focus(window, cx));
97 }
98 }
99
100 fn reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Composer> {
101 if let Some(composer) = &self.reply_composer {
102 return composer.clone();
103 }
104 let composer = cx.new(|cx| Composer::new(self.app.clone(), window, cx).inline());
105 let subscription = cx.subscribe_in(&composer, window, Self::on_reply_event);
106 self._subscriptions.push(subscription);
107 self.reply_composer = Some(composer.clone());
108 self.sync_reply_composer(window, cx);
109 composer
110 }
111
112 pub(super) fn sync_reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
113 self.reply_root = None;
114 let (Some(composer), Some(conversation_id)) =
115 (self.reply_composer.clone(), self.conversation_id())
116 else {
117 return;
118 };
119 composer.update(cx, |composer, cx| {
120 composer.set_conversation(&conversation_id, "", window, cx);
121 composer.set_placeholder(REPLY_PLACEHOLDER, window, cx);
122 composer.set_text("", window, cx);
123 composer.set_reply(None, cx);
124 });
125 }
126
127 pub(super) fn open_reply_editor(
128 &mut self,
129 root_id: String,
130 quote: Option<ReplyPreview>,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let composer = self.reply_composer(window, cx);
135 let previous = self.reply_root.replace(root_id.clone());
136 let changed = previous.as_deref() != Some(root_id.as_str());
137 composer.update(cx, |composer, cx| {
138 if changed {
139 composer.set_text("", window, cx);
140 }
141 composer.set_reply(quote, cx);
142 composer.focus(window, cx);
143 });
144 self.remeasure_posts(&[Some(root_id), previous], cx);
145 }
146
147 pub(super) fn close_reply_editor(&mut self, cx: &mut Context<Self>) {
148 if let Some(root_id) = self.reply_root.take() {
149 self.remeasure_posts(&[Some(root_id)], cx);
150 }
151 }
152
153 fn remeasure_posts(&mut self, root_ids: &[Option<String>], cx: &mut Context<Self>) {
154 let indices: Vec<usize> = self
155 .rows
156 .borrow()
157 .iter()
158 .enumerate()
159 .filter(|(_, row)| {
160 matches!(row, Row::Post(post) if root_ids.iter().flatten().any(|id| *id == post.root.key))
161 })
162 .map(|(index, _)| index)
163 .collect();
164 self.scroller.update(cx, |scroller, cx| {
165 for index in indices {
166 scroller.remeasure_items(index..index + 1, cx);
167 }
168 });
169 cx.notify();
170 }
171
172 fn on_reply_event(
173 &mut self,
174 _: &Entity<Composer>,
175 event: &ComposerEvent,
176 window: &mut Window,
177 cx: &mut Context<Self>,
178 ) {
179 match event {
180 ComposerEvent::Submit(outgoing) => {
181 let Some(root_id) = self.reply_root.clone() else {
182 return;
183 };
184 self.close_reply_editor(cx);
185 self.send_in_thread(root_id, (**outgoing).clone(), window, cx);
186 }
187 ComposerEvent::Typing(active) => {
188 let root_id = self.reply_root.clone();
189 self.send_typing_in(root_id, *active, cx);
190 }
191 ComposerEvent::Schedule { .. } | ComposerEvent::EditLast => {}
192 }
193 }
194
195 pub(super) fn stop_reply_typing(&mut self, cx: &mut Context<Self>) {
196 let Some(composer) = self.reply_composer.clone() else {
197 return;
198 };
199 if composer.update(cx, |composer, _| composer.stop_typing()) {
200 let root_id = self.reply_root.clone();
201 self.send_typing_in(root_id, false, cx);
202 }
203 }
204
205 pub(super) fn show_main_composer(&mut self, cx: &mut Context<Self>) {
206 if self.in_feed() {
207 self.new_post_open = true;
208 cx.notify();
209 }
210 }
211
212 pub(super) fn render_new_post(
213 &self,
214 window: &Window,
215 cx: &mut Context<Self>,
216 ) -> Option<AnyElement> {
217 if !self.in_feed() {
218 return None;
219 }
220 if !self.new_post_open {
221 return Some(
222 h_flex()
223 .w_full()
224 .flex_none()
225 .px(px(24.))
226 .py(px(10.))
227 .child(
228 h_flex()
229 .id("new-post")
230 .h(px(32.))
231 .px(px(12.))
232 .gap(px(6.))
233 .items_center()
234 .rounded(px(8.))
235 .bg(theme::accent())
236 .text_color(theme::on_accent())
237 .text_size(px(13.))
238 .font_weight(FontWeight::SEMIBOLD)
239 .cursor_pointer()
240 .hover(|button| button.bg(theme::accent_text()))
241 .on_click(
242 cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),
243 )
244 .child(icon(IconName::Plus, 14., theme::on_accent()))
245 .child("New post"),
246 )
247 .into_any_element(),
248 );
249 }
250 let editing = self.composer.read(cx).is_editing();
251 let focused = self
252 .subject
253 .read(cx)
254 .focus_handle(cx)
255 .contains_focused(window, cx);
256 let subject = (!editing).then(|| {
257 div().w_full().px(px(24.)).pt(px(10.)).child(
258 div()
259 .w_full()
260 .h(px(36.))
261 .px(px(12.))
262 .flex()
263 .items_center()
264 .rounded(px(10.))
265 .bg(theme::surface())
266 .border_1()
267 .border_color(if focused {
268 theme::accent()
269 } else {
270 theme::border_strong()
271 })
272 .child(
273 div()
274 .w_full()
275 .child(Input::new(&self.subject).appearance(false).bordered(false)),
276 ),
277 )
278 });
279 Some(
280 v_flex()
281 .w_full()
282 .flex_none()
283 .border_b_1()
284 .border_color(theme::border())
285 .children(subject)
286 .child(self.composer.clone())
287 .child(
288 h_flex()
289 .w_full()
290 .px(px(24.))
291 .pb(px(10.))
292 .justify_end()
293 .child(
294 Button::new("cancel-new-post")
295 .ghost()
296 .compact()
297 .label("Cancel")
298 .on_click(cx.listener(|this, _, window, cx| {
299 this.cancel_new_post(window, cx)
300 })),
301 ),
302 )
303 .into_any_element(),
304 )
305 }
306
307 pub(super) fn cancel_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
308 let editing = self.composer.read(cx).is_editing();
309 if editing {
310 self.composer
311 .update(cx, |composer, cx| composer.cancel_edit(window, cx));
312 }
313 self.close_new_post(cx);
314 }
315
316 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
317 if self.reply_root.is_some() {
318 self.close_reply_editor(cx);
319 return true;
320 }
321 if self.new_post_open && self.in_feed() {
322 self.cancel_new_post(window, cx);
323 return true;
324 }
325 if matches!(
326 self.current.as_ref().map(|current| &current.mode),
327 Some(ViewMode::Thread(_))
328 ) && !self.draft_active
329 {
330 self.back_to_threads(cx);
331 return true;
332 }
333 false
334 }
335
336 pub(super) fn enter_thread_mode(&mut self, root_id: String, cx: &mut Context<Self>) {
337 let Some(current) = self.current.as_mut() else {
338 return;
339 };
340 if current.mode == ViewMode::ThreadList {
341 let stash = FeedStash {
342 scroller: self.scroller.clone(),
343 rows: self.rows.clone(),
344 near_top: self.feed_at_top,
345 };
346 self.feed_stash = Some(stash);
347 self.scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
348 self.rows = Rc::new(RefCell::new(Vec::new()));
349 }
350 current.mode = ViewMode::Thread(root_id);
351 self.reply_root = None;
352 }
353
354 pub(super) fn enter_feed_mode(&mut self) -> bool {
355 let Some(current) = self.current.as_mut() else {
356 return false;
357 };
358 current.mode = ViewMode::ThreadList;
359 match self.feed_stash.take() {
360 Some(stash) => {
361 self.scroller = stash.scroller;
362 self.rows = stash.rows;
363 self.feed_at_top = stash.near_top;
364 true
365 }
366 None => false,
367 }
368 }
369
370 pub(super) fn open_thread(
371 &mut self,
372 root_id: String,
373 window: &mut Window,
374 cx: &mut Context<Self>,
375 ) {
376 self.stop_typing(cx);
377 self.stop_reply_typing(cx);
378 self.enter_thread_mode(root_id.clone(), cx);
379 self.reload_pending(cx);
380 self.rebuild(true, cx);
381 self.refresh_thread(root_id, cx);
382 self.composer
383 .update(cx, |composer, cx| composer.focus(window, cx));
384 }
385
386 pub(super) fn back_to_threads(&mut self, cx: &mut Context<Self>) {
387 self.stop_typing(cx);
388 let restored = self.enter_feed_mode();
389 self.reload_pending(cx);
390 self.rebuild(!restored, cx);
391 }
392
393 pub(super) fn refresh_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
394 let state = self.app.read(cx);
395 if state.mode.demo || state.mode.read_only {
396 return;
397 }
398 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
399 else {
400 return;
401 };
402 let receiver = {
403 let (conversation_id, root_id) = (conversation_id.clone(), root_id.clone());
404 runtime::spawn(async move { engine.refresh_thread(&conversation_id, &root_id).await })
405 };
406 cx.spawn(async move |this, cx| {
407 let result = receiver.await;
408 this.update(cx, |this, cx| {
409 this.finish_thread_refresh(&conversation_id, &root_id, result, cx)
410 })
411 .ok();
412 })
413 .detach();
414 }
415
416 fn finish_thread_refresh(
417 &mut self,
418 conversation_id: &str,
419 root_id: &str,
420 result: Result<
421 teams_core::Result<teams_core::Delta>,
422 tokio::sync::oneshot::error::RecvError,
423 >,
424 cx: &mut Context<Self>,
425 ) {
426 let still_open = self.current.as_ref().is_some_and(|current| {
427 current.selection.conversation_id() == conversation_id
428 && current.mode == ViewMode::Thread(root_id.to_owned())
429 });
430 if !still_open {
431 return;
432 }
433 let failure = match result {
434 Ok(Ok(_)) => None,
435 Ok(Err(error)) => Some(short_error(&error)),
436 Err(error) => Some(short_error(&error)),
437 };
438 if let Some(failure) = failure {
439 self.notice = Some(format!("Could not load all replies: {failure}"));
440 }
441 self.rebuild(false, cx);
442 }
443 }
@@ -0,0 +1,443 @@
1use std::cell::RefCell;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputEvent, InputState},
9 message_scroller::MessageScrollerState,
10 v_flex,
11};
12use gpui_kit::*;
13
14use super::{ConversationView, ViewMode};
15use crate::notice::short_error;
16use crate::rows::Row;
17use crate::runtime;
18use crate::theme;
19use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
20use crate::views::widgets::icon;
21
22const REPLY_PLACEHOLDER: &str = "Reply";
23const SUBJECT_PLACEHOLDER: &str = "Add a subject";
24
25pub(super) struct FeedStash {
26 scroller: Entity<MessageScrollerState>,
27 rows: Rc<RefCell<Vec<Row>>>,
28 near_top: bool,
29}
30
31pub(super) fn subject_input(
32 window: &mut Window,
33 cx: &mut Context<ConversationView>,
34) -> Entity<InputState> {
35 cx.new(|cx| InputState::new(window, cx).placeholder(SUBJECT_PLACEHOLDER))
36}
37
38impl ConversationView {
39 pub(super) fn in_feed(&self) -> bool {
40 !self.draft_active
41 && self
42 .current
43 .as_ref()
44 .is_some_and(|current| current.mode == ViewMode::ThreadList)
45 }
46
47 pub(super) fn open_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
48 self.new_post_open = true;
49 self.composer
50 .update(cx, |composer, cx| composer.focus(window, cx));
51 cx.notify();
52 }
53
54 pub(super) fn close_new_post(&mut self, cx: &mut Context<Self>) {
55 if self.new_post_open {
56 self.new_post_open = false;
57 cx.notify();
58 }
59 }
60
61 pub(super) fn take_subject(
62 &mut self,
63 window: &mut Window,
64 cx: &mut Context<Self>,
65 ) -> Option<String> {
66 let subject = self.subject.read(cx).value().trim().to_owned();
67 self.subject
68 .update(cx, |input, cx| input.set_value("", window, cx));
69 (!subject.is_empty()).then_some(subject)
70 }
71
72 pub(super) fn restore_subject(
73 &mut self,
74 subject: Option<&str>,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 let subject = subject.unwrap_or_default().to_owned();
79 self.subject
80 .update(cx, |input, cx| input.set_value(subject, window, cx));
81 }
82
83 pub(super) fn has_subject(&self, cx: &App) -> bool {
84 !self.subject.read(cx).value().trim().is_empty()
85 }
86
87 pub(super) fn on_subject_event(
88 &mut self,
89 _: &Entity<InputState>,
90 event: &InputEvent,
91 window: &mut Window,
92 cx: &mut Context<Self>,
93 ) {
94 if matches!(event, InputEvent::PressEnter { .. }) {
95 self.composer
96 .update(cx, |composer, cx| composer.focus(window, cx));
97 }
98 }
99
100 fn reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<Composer> {
101 if let Some(composer) = &self.reply_composer {
102 return composer.clone();
103 }
104 let composer = cx.new(|cx| Composer::new(self.app.clone(), window, cx).inline());
105 let subscription = cx.subscribe_in(&composer, window, Self::on_reply_event);
106 self._subscriptions.push(subscription);
107 self.reply_composer = Some(composer.clone());
108 self.sync_reply_composer(window, cx);
109 composer
110 }
111
112 pub(super) fn sync_reply_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
113 self.reply_root = None;
114 let (Some(composer), Some(conversation_id)) =
115 (self.reply_composer.clone(), self.conversation_id())
116 else {
117 return;
118 };
119 composer.update(cx, |composer, cx| {
120 composer.set_conversation(&conversation_id, "", window, cx);
121 composer.set_placeholder(REPLY_PLACEHOLDER, window, cx);
122 composer.set_text("", window, cx);
123 composer.set_reply(None, cx);
124 });
125 }
126
127 pub(super) fn open_reply_editor(
128 &mut self,
129 root_id: String,
130 quote: Option<ReplyPreview>,
131 window: &mut Window,
132 cx: &mut Context<Self>,
133 ) {
134 let composer = self.reply_composer(window, cx);
135 let previous = self.reply_root.replace(root_id.clone());
136 let changed = previous.as_deref() != Some(root_id.as_str());
137 composer.update(cx, |composer, cx| {
138 if changed {
139 composer.set_text("", window, cx);
140 }
141 composer.set_reply(quote, cx);
142 composer.focus(window, cx);
143 });
144 self.remeasure_posts(&[Some(root_id), previous], cx);
145 }
146
147 pub(super) fn close_reply_editor(&mut self, cx: &mut Context<Self>) {
148 if let Some(root_id) = self.reply_root.take() {
149 self.remeasure_posts(&[Some(root_id)], cx);
150 }
151 }
152
153 fn remeasure_posts(&mut self, root_ids: &[Option<String>], cx: &mut Context<Self>) {
154 let indices: Vec<usize> = self
155 .rows
156 .borrow()
157 .iter()
158 .enumerate()
159 .filter(|(_, row)| {
160 matches!(row, Row::Post(post) if root_ids.iter().flatten().any(|id| *id == post.root.key))
161 })
162 .map(|(index, _)| index)
163 .collect();
164 self.scroller.update(cx, |scroller, cx| {
165 for index in indices {
166 scroller.remeasure_items(index..index + 1, cx);
167 }
168 });
169 cx.notify();
170 }
171
172 fn on_reply_event(
173 &mut self,
174 _: &Entity<Composer>,
175 event: &ComposerEvent,
176 window: &mut Window,
177 cx: &mut Context<Self>,
178 ) {
179 match event {
180 ComposerEvent::Submit(outgoing) => {
181 let Some(root_id) = self.reply_root.clone() else {
182 return;
183 };
184 self.close_reply_editor(cx);
185 self.send_in_thread(root_id, (**outgoing).clone(), window, cx);
186 }
187 ComposerEvent::Typing(active) => {
188 let root_id = self.reply_root.clone();
189 self.send_typing_in(root_id, *active, cx);
190 }
191 ComposerEvent::Schedule { .. } | ComposerEvent::EditLast => {}
192 }
193 }
194
195 pub(super) fn stop_reply_typing(&mut self, cx: &mut Context<Self>) {
196 let Some(composer) = self.reply_composer.clone() else {
197 return;
198 };
199 if composer.update(cx, |composer, _| composer.stop_typing()) {
200 let root_id = self.reply_root.clone();
201 self.send_typing_in(root_id, false, cx);
202 }
203 }
204
205 pub(super) fn show_main_composer(&mut self, cx: &mut Context<Self>) {
206 if self.in_feed() {
207 self.new_post_open = true;
208 cx.notify();
209 }
210 }
211
212 pub(super) fn render_new_post(
213 &self,
214 window: &Window,
215 cx: &mut Context<Self>,
216 ) -> Option<AnyElement> {
217 if !self.in_feed() {
218 return None;
219 }
220 if !self.new_post_open {
221 return Some(
222 h_flex()
223 .w_full()
224 .flex_none()
225 .px(px(24.))
226 .py(px(10.))
227 .child(
228 h_flex()
229 .id("new-post")
230 .h(px(32.))
231 .px(px(12.))
232 .gap(px(6.))
233 .items_center()
234 .rounded(px(8.))
235 .bg(theme::accent())
236 .text_color(theme::on_accent())
237 .text_size(px(13.))
238 .font_weight(FontWeight::SEMIBOLD)
239 .cursor_pointer()
240 .hover(|button| button.bg(theme::accent_text()))
241 .on_click(
242 cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),
243 )
244 .child(icon(IconName::Plus, 14., theme::on_accent()))
245 .child("New post"),
246 )
247 .into_any_element(),
248 );
249 }
250 let editing = self.composer.read(cx).is_editing();
251 let focused = self
252 .subject
253 .read(cx)
254 .focus_handle(cx)
255 .contains_focused(window, cx);
256 let subject = (!editing).then(|| {
257 div().w_full().px(px(24.)).pt(px(10.)).child(
258 div()
259 .w_full()
260 .h(px(36.))
261 .px(px(12.))
262 .flex()
263 .items_center()
264 .rounded(px(10.))
265 .bg(theme::surface())
266 .border_1()
267 .border_color(if focused {
268 theme::accent()
269 } else {
270 theme::border_strong()
271 })
272 .child(
273 div()
274 .w_full()
275 .child(Input::new(&self.subject).appearance(false).bordered(false)),
276 ),
277 )
278 });
279 Some(
280 v_flex()
281 .w_full()
282 .flex_none()
283 .border_b_1()
284 .border_color(theme::border())
285 .children(subject)
286 .child(self.composer.clone())
287 .child(
288 h_flex()
289 .w_full()
290 .px(px(24.))
291 .pb(px(10.))
292 .justify_end()
293 .child(
294 Button::new("cancel-new-post")
295 .ghost()
296 .compact()
297 .label("Cancel")
298 .on_click(cx.listener(|this, _, window, cx| {
299 this.cancel_new_post(window, cx)
300 })),
301 ),
302 )
303 .into_any_element(),
304 )
305 }
306
307 pub(super) fn cancel_new_post(&mut self, window: &mut Window, cx: &mut Context<Self>) {
308 let editing = self.composer.read(cx).is_editing();
309 if editing {
310 self.composer
311 .update(cx, |composer, cx| composer.cancel_edit(window, cx));
312 }
313 self.close_new_post(cx);
314 }
315
316 pub(super) fn on_escape(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
317 if self.reply_root.is_some() {
318 self.close_reply_editor(cx);
319 return true;
320 }
321 if self.new_post_open && self.in_feed() {
322 self.cancel_new_post(window, cx);
323 return true;
324 }
325 if matches!(
326 self.current.as_ref().map(|current| &current.mode),
327 Some(ViewMode::Thread(_))
328 ) && !self.draft_active
329 {
330 self.back_to_threads(cx);
331 return true;
332 }
333 false
334 }
335
336 pub(super) fn enter_thread_mode(&mut self, root_id: String, cx: &mut Context<Self>) {
337 let Some(current) = self.current.as_mut() else {
338 return;
339 };
340 if current.mode == ViewMode::ThreadList {
341 let stash = FeedStash {
342 scroller: self.scroller.clone(),
343 rows: self.rows.clone(),
344 near_top: self.feed_at_top,
345 };
346 self.feed_stash = Some(stash);
347 self.scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
348 self.rows = Rc::new(RefCell::new(Vec::new()));
349 }
350 current.mode = ViewMode::Thread(root_id);
351 self.reply_root = None;
352 }
353
354 pub(super) fn enter_feed_mode(&mut self) -> bool {
355 let Some(current) = self.current.as_mut() else {
356 return false;
357 };
358 current.mode = ViewMode::ThreadList;
359 match self.feed_stash.take() {
360 Some(stash) => {
361 self.scroller = stash.scroller;
362 self.rows = stash.rows;
363 self.feed_at_top = stash.near_top;
364 true
365 }
366 None => false,
367 }
368 }
369
370 pub(super) fn open_thread(
371 &mut self,
372 root_id: String,
373 window: &mut Window,
374 cx: &mut Context<Self>,
375 ) {
376 self.stop_typing(cx);
377 self.stop_reply_typing(cx);
378 self.enter_thread_mode(root_id.clone(), cx);
379 self.reload_pending(cx);
380 self.rebuild(true, cx);
381 self.refresh_thread(root_id, cx);
382 self.composer
383 .update(cx, |composer, cx| composer.focus(window, cx));
384 }
385
386 pub(super) fn back_to_threads(&mut self, cx: &mut Context<Self>) {
387 self.stop_typing(cx);
388 let restored = self.enter_feed_mode();
389 self.reload_pending(cx);
390 self.rebuild(!restored, cx);
391 }
392
393 pub(super) fn refresh_thread(&mut self, root_id: String, cx: &mut Context<Self>) {
394 let state = self.app.read(cx);
395 if state.mode.demo || state.mode.read_only {
396 return;
397 }
398 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
399 else {
400 return;
401 };
402 let receiver = {
403 let (conversation_id, root_id) = (conversation_id.clone(), root_id.clone());
404 runtime::spawn(async move { engine.refresh_thread(&conversation_id, &root_id).await })
405 };
406 cx.spawn(async move |this, cx| {
407 let result = receiver.await;
408 this.update(cx, |this, cx| {
409 this.finish_thread_refresh(&conversation_id, &root_id, result, cx)
410 })
411 .ok();
412 })
413 .detach();
414 }
415
416 fn finish_thread_refresh(
417 &mut self,
418 conversation_id: &str,
419 root_id: &str,
420 result: Result<
421 teams_core::Result<teams_core::Delta>,
422 tokio::sync::oneshot::error::RecvError,
423 >,
424 cx: &mut Context<Self>,
425 ) {
426 let still_open = self.current.as_ref().is_some_and(|current| {
427 current.selection.conversation_id() == conversation_id
428 && current.mode == ViewMode::Thread(root_id.to_owned())
429 });
430 if !still_open {
431 return;
432 }
433 let failure = match result {
434 Ok(Ok(_)) => None,
435 Ok(Err(error)) => Some(short_error(&error)),
436 Err(error) => Some(short_error(&error)),
437 };
438 if let Some(failure) = failure {
439 self.notice = Some(format!("Could not load all replies: {failure}"));
440 }
441 self.rebuild(false, cx);
442 }
443}
crates/app/src/views/conversation/render_env.rs added +270 −0
@@ -0,0 +1,270 @@
1 use std::rc::Rc;
2
3 use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex, v_flex,
6 };
7 use gpui_kit::*;
8 use teams_core::{ImageRef, LinkPreview};
9
10 use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
11 use crate::app_state::AppState;
12 use crate::rows::{Delivery, MessageRow, PostRow};
13 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14 use crate::views::adaptive_card::ensure_cards_inputs;
15 use crate::views::composer::Composer;
16 use crate::views::message_row::{DeliveryActions, RowActions};
17 use crate::views::post_card::{PostAction, PostActions};
18
19 pub(super) struct RenderEnv {
20 pub view: WeakEntity<ConversationView>,
21 pub app: Entity<AppState>,
22 pub highlighted: Option<String>,
23 pub drafting: bool,
24 pub reply_editor: Option<(String, Entity<Composer>)>,
25 }
26
27 fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
28 Box::new(action)
29 }
30
31 impl RenderEnv {
32 fn request_missing_media(&self, message: &MessageRow, cx: &mut App) {
33 let senders: Vec<String> = (!message.own && !message.series.has_prev)
34 .then(|| message.sender_id.clone())
35 .flatten()
36 .into_iter()
37 .chain(
38 message
39 .reactions
40 .iter()
41 .flat_map(|chip| chip.reactors.iter())
42 .filter_map(|reactor| reactor.user_id.clone()),
43 )
44 .filter(|sender| self.app.read(cx).directory.avatar(sender).is_none())
45 .collect();
46 if !senders.is_empty() {
47 let app = self.app.clone();
48 cx.defer(move |cx| {
49 app.update(cx, |state, cx| state.request_avatars(senders, cx));
50 });
51 }
52 let missing_images: Vec<ImageRef> = message
53 .images
54 .iter()
55 .cloned()
56 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
57 .filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
58 .collect();
59 if !missing_images.is_empty() {
60 let app = self.app.clone();
61 cx.defer(move |cx| {
62 app.update(cx, |state, cx| state.request_images(missing_images, cx));
63 });
64 }
65 }
66
67 fn bot_identity(
68 &self,
69 message: &MessageRow,
70 cx: &mut App,
71 ) -> Option<crate::card_state::BotIdentity> {
72 let application_id = message.application_id.as_deref()?;
73 let known = self
74 .app
75 .read(cx)
76 .bot_identity(&message.conversation_id, application_id);
77 if known.is_none() {
78 let (app, conversation_id) = (self.app.clone(), message.conversation_id.clone());
79 cx.defer(move |cx| {
80 app.update(cx, |state, cx| {
81 state.request_chat_apps(&conversation_id, cx)
82 });
83 });
84 }
85 known
86 }
87
88 pub fn message_actions(
89 &self,
90 message: &MessageRow,
91 window: &mut Window,
92 cx: &mut App,
93 ) -> RowActions {
94 let view = &self.view;
95 let failed = matches!(message.delivery, Delivery::Failed(_));
96 let retry = failed.then(|| {
97 let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());
98 boxed(move |cx| {
99 let (view, key) = (view.clone(), key.clone());
100 handle
101 .update(cx, move |_, window, cx| {
102 view.update(cx, |this, cx| this.retry(&key, window, cx))
103 .ok();
104 })
105 .ok();
106 })
107 });
108 let scheduled = view.upgrade().and_then(|entity| {
109 entity
110 .read(cx)
111 .scheduled_row_actions(message, view, window, cx)
112 });
113 let delete = failed.then(|| {
114 let (view, key) = (view.clone(), message.key.clone());
115 boxed(move |cx| {
116 view.update(cx, |this, cx| this.delete_pending(&key, cx))
117 .ok();
118 })
119 });
120 self.request_missing_media(message, cx);
121 let is_real =
122 !self.drafting && !message.key.starts_with(PENDING_KEY_PREFIX) && scheduled.is_none();
123 let hovered = is_real.then(|| {
124 let (view, key) = (view.clone(), message.key.clone());
125 Rc::new(move |hovered: bool, cx: &mut App| {
126 view.update(cx, |this, cx| {
127 this.set_hover(HoverSlot::Row, &key, hovered, cx)
128 })
129 .ok();
130 }) as Rc<dyn Fn(bool, &mut App)>
131 });
132 let (delivery, scheduled_menu, hovered) = match scheduled {
133 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
134 None => (
135 DeliveryActions {
136 retry,
137 delete,
138 send_now: None,
139 },
140 None,
141 hovered,
142 ),
143 };
144 let actionable = is_real && !message.deleted;
145 let (menu, react, reaction_controls) = view
146 .upgrade()
147 .filter(|_| actionable)
148 .map(|entity| {
149 let this = entity.read(cx);
150 let mine = message
151 .reactions
152 .iter()
153 .filter(|chip| chip.mine)
154 .map(|chip| chip.glyph())
155 .collect();
156 let menu = this.message_menu(&message.key, message.own, mine, view.clone(), cx);
157 let react = menu.react.clone();
158 let visible = this.toolbar_visible(&message.key);
159 let controls = (!message.reactions.is_empty())
160 .then(|| this.reaction_controls(&message.key, view.clone()));
161 (visible.then_some(menu), Some(react), controls)
162 })
163 .unwrap_or((None, None, None));
164 let reply = (is_real && !message.deleted).then(|| {
165 let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());
166 boxed(move |cx| {
167 let (view, key) = (view.clone(), key.clone());
168 handle
169 .update(cx, move |_, window, cx| {
170 view.update(cx, |this, cx| this.begin_reply(&key, window, cx))
171 .ok();
172 })
173 .ok();
174 })
175 });
176 let files = (is_real && !message.deleted && !message.files.is_empty())
177 .then(|| view.upgrade())
178 .flatten()
179 .map(|entity| {
180 entity
181 .read(cx)
182 .file_actions(&message.key, &message.files, view.clone())
183 });
184 let bot = self.bot_identity(message, cx);
185 ensure_cards_inputs(
186 &self.app,
187 &message.adaptive_cards,
188 &message.conversation_id,
189 &message.key,
190 window,
191 cx,
192 );
193 RowActions {
194 bot,
195 delivery,
196 reply,
197 hovered,
198 menu,
199 scheduled_menu,
200 react,
201 reaction_controls,
202 files,
203 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
204 }
205 }
206
207 fn open_by_root(
208 &self,
209 root_key: String,
210 run: fn(&mut ConversationView, String, &mut Window, &mut Context<ConversationView>),
211 ) -> PostAction {
212 let view = self.view.clone();
213 Box::new(move |window, cx| {
214 view.update(cx, |this, cx| run(this, root_key.clone(), window, cx))
215 .ok();
216 })
217 }
218
219 pub fn post_actions(&self, post: &PostRow, window: &mut Window, cx: &mut App) -> PostActions {
220 let root_key = post.root.key.clone();
221 let is_local =
222 root_key.starts_with(PENDING_KEY_PREFIX) || root_key.starts_with(SCHEDULED_KEY_PREFIX);
223 let open_thread = Some(
224 self.open_by_root(root_key.clone(), |this, root_key, window, cx| {
225 this.open_thread(root_key, window, cx)
226 }),
227 );
228 let open_reply = (!is_local).then(|| {
229 self.open_by_root(root_key.clone(), |this, root_key, window, cx| {
230 this.open_reply_editor(root_key, None, window, cx)
231 })
232 });
233 let reply_editor = self
234 .reply_editor
235 .as_ref()
236 .filter(|(open_root, _)| *open_root == root_key)
237 .map(|(_, composer)| self.inline_reply_editor(composer));
238 PostActions {
239 root: self.message_actions(&post.root, window, cx),
240 replies: post
241 .replies
242 .iter()
243 .map(|reply| self.message_actions(reply, window, cx))
244 .collect(),
245 open_thread,
246 open_reply,
247 reply_editor,
248 }
249 }
250
251 fn inline_reply_editor(&self, composer: &Entity<Composer>) -> AnyElement {
252 let view = self.view.clone();
253 v_flex()
254 .w_full()
255 .gap(px(6.))
256 .child(composer.clone())
257 .child(
258 h_flex().justify_end().child(
259 Button::new("cancel-inline-reply")
260 .ghost()
261 .compact()
262 .label("Cancel")
263 .on_click(move |_, _, cx| {
264 view.update(cx, |this, cx| this.close_reply_editor(cx)).ok();
265 }),
266 ),
267 )
268 .into_any_element()
269 }
270 }
@@ -0,0 +1,270 @@
1use std::rc::Rc;
2
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex, v_flex,
6};
7use gpui_kit::*;
8use teams_core::{ImageRef, LinkPreview};
9
10use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
11use crate::app_state::AppState;
12use crate::rows::{Delivery, MessageRow, PostRow};
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14use crate::views::adaptive_card::ensure_cards_inputs;
15use crate::views::composer::Composer;
16use crate::views::message_row::{DeliveryActions, RowActions};
17use crate::views::post_card::{PostAction, PostActions};
18
19pub(super) struct RenderEnv {
20 pub view: WeakEntity<ConversationView>,
21 pub app: Entity<AppState>,
22 pub highlighted: Option<String>,
23 pub drafting: bool,
24 pub reply_editor: Option<(String, Entity<Composer>)>,
25}
26
27fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
28 Box::new(action)
29}
30
31impl RenderEnv {
32 fn request_missing_media(&self, message: &MessageRow, cx: &mut App) {
33 let senders: Vec<String> = (!message.own && !message.series.has_prev)
34 .then(|| message.sender_id.clone())
35 .flatten()
36 .into_iter()
37 .chain(
38 message
39 .reactions
40 .iter()
41 .flat_map(|chip| chip.reactors.iter())
42 .filter_map(|reactor| reactor.user_id.clone()),
43 )
44 .filter(|sender| self.app.read(cx).directory.avatar(sender).is_none())
45 .collect();
46 if !senders.is_empty() {
47 let app = self.app.clone();
48 cx.defer(move |cx| {
49 app.update(cx, |state, cx| state.request_avatars(senders, cx));
50 });
51 }
52 let missing_images: Vec<ImageRef> = message
53 .images
54 .iter()
55 .cloned()
56 .chain(message.link_preview.as_ref().and_then(LinkPreview::image))
57 .filter(|image| self.app.read(cx).directory.image(&image.url).is_none())
58 .collect();
59 if !missing_images.is_empty() {
60 let app = self.app.clone();
61 cx.defer(move |cx| {
62 app.update(cx, |state, cx| state.request_images(missing_images, cx));
63 });
64 }
65 }
66
67 fn bot_identity(
68 &self,
69 message: &MessageRow,
70 cx: &mut App,
71 ) -> Option<crate::card_state::BotIdentity> {
72 let application_id = message.application_id.as_deref()?;
73 let known = self
74 .app
75 .read(cx)
76 .bot_identity(&message.conversation_id, application_id);
77 if known.is_none() {
78 let (app, conversation_id) = (self.app.clone(), message.conversation_id.clone());
79 cx.defer(move |cx| {
80 app.update(cx, |state, cx| {
81 state.request_chat_apps(&conversation_id, cx)
82 });
83 });
84 }
85 known
86 }
87
88 pub fn message_actions(
89 &self,
90 message: &MessageRow,
91 window: &mut Window,
92 cx: &mut App,
93 ) -> RowActions {
94 let view = &self.view;
95 let failed = matches!(message.delivery, Delivery::Failed(_));
96 let retry = failed.then(|| {
97 let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());
98 boxed(move |cx| {
99 let (view, key) = (view.clone(), key.clone());
100 handle
101 .update(cx, move |_, window, cx| {
102 view.update(cx, |this, cx| this.retry(&key, window, cx))
103 .ok();
104 })
105 .ok();
106 })
107 });
108 let scheduled = view.upgrade().and_then(|entity| {
109 entity
110 .read(cx)
111 .scheduled_row_actions(message, view, window, cx)
112 });
113 let delete = failed.then(|| {
114 let (view, key) = (view.clone(), message.key.clone());
115 boxed(move |cx| {
116 view.update(cx, |this, cx| this.delete_pending(&key, cx))
117 .ok();
118 })
119 });
120 self.request_missing_media(message, cx);
121 let is_real =
122 !self.drafting && !message.key.starts_with(PENDING_KEY_PREFIX) && scheduled.is_none();
123 let hovered = is_real.then(|| {
124 let (view, key) = (view.clone(), message.key.clone());
125 Rc::new(move |hovered: bool, cx: &mut App| {
126 view.update(cx, |this, cx| {
127 this.set_hover(HoverSlot::Row, &key, hovered, cx)
128 })
129 .ok();
130 }) as Rc<dyn Fn(bool, &mut App)>
131 });
132 let (delivery, scheduled_menu, hovered) = match scheduled {
133 Some(actions) => (actions.delivery, actions.menu, Some(actions.hovered)),
134 None => (
135 DeliveryActions {
136 retry,
137 delete,
138 send_now: None,
139 },
140 None,
141 hovered,
142 ),
143 };
144 let actionable = is_real && !message.deleted;
145 let (menu, react, reaction_controls) = view
146 .upgrade()
147 .filter(|_| actionable)
148 .map(|entity| {
149 let this = entity.read(cx);
150 let mine = message
151 .reactions
152 .iter()
153 .filter(|chip| chip.mine)
154 .map(|chip| chip.glyph())
155 .collect();
156 let menu = this.message_menu(&message.key, message.own, mine, view.clone(), cx);
157 let react = menu.react.clone();
158 let visible = this.toolbar_visible(&message.key);
159 let controls = (!message.reactions.is_empty())
160 .then(|| this.reaction_controls(&message.key, view.clone()));
161 (visible.then_some(menu), Some(react), controls)
162 })
163 .unwrap_or((None, None, None));
164 let reply = (is_real && !message.deleted).then(|| {
165 let (view, key, handle) = (view.clone(), message.key.clone(), window.window_handle());
166 boxed(move |cx| {
167 let (view, key) = (view.clone(), key.clone());
168 handle
169 .update(cx, move |_, window, cx| {
170 view.update(cx, |this, cx| this.begin_reply(&key, window, cx))
171 .ok();
172 })
173 .ok();
174 })
175 });
176 let files = (is_real && !message.deleted && !message.files.is_empty())
177 .then(|| view.upgrade())
178 .flatten()
179 .map(|entity| {
180 entity
181 .read(cx)
182 .file_actions(&message.key, &message.files, view.clone())
183 });
184 let bot = self.bot_identity(message, cx);
185 ensure_cards_inputs(
186 &self.app,
187 &message.adaptive_cards,
188 &message.conversation_id,
189 &message.key,
190 window,
191 cx,
192 );
193 RowActions {
194 bot,
195 delivery,
196 reply,
197 hovered,
198 menu,
199 scheduled_menu,
200 react,
201 reaction_controls,
202 files,
203 highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
204 }
205 }
206
207 fn open_by_root(
208 &self,
209 root_key: String,
210 run: fn(&mut ConversationView, String, &mut Window, &mut Context<ConversationView>),
211 ) -> PostAction {
212 let view = self.view.clone();
213 Box::new(move |window, cx| {
214 view.update(cx, |this, cx| run(this, root_key.clone(), window, cx))
215 .ok();
216 })
217 }
218
219 pub fn post_actions(&self, post: &PostRow, window: &mut Window, cx: &mut App) -> PostActions {
220 let root_key = post.root.key.clone();
221 let is_local =
222 root_key.starts_with(PENDING_KEY_PREFIX) || root_key.starts_with(SCHEDULED_KEY_PREFIX);
223 let open_thread = Some(
224 self.open_by_root(root_key.clone(), |this, root_key, window, cx| {
225 this.open_thread(root_key, window, cx)
226 }),
227 );
228 let open_reply = (!is_local).then(|| {
229 self.open_by_root(root_key.clone(), |this, root_key, window, cx| {
230 this.open_reply_editor(root_key, None, window, cx)
231 })
232 });
233 let reply_editor = self
234 .reply_editor
235 .as_ref()
236 .filter(|(open_root, _)| *open_root == root_key)
237 .map(|(_, composer)| self.inline_reply_editor(composer));
238 PostActions {
239 root: self.message_actions(&post.root, window, cx),
240 replies: post
241 .replies
242 .iter()
243 .map(|reply| self.message_actions(reply, window, cx))
244 .collect(),
245 open_thread,
246 open_reply,
247 reply_editor,
248 }
249 }
250
251 fn inline_reply_editor(&self, composer: &Entity<Composer>) -> AnyElement {
252 let view = self.view.clone();
253 v_flex()
254 .w_full()
255 .gap(px(6.))
256 .child(composer.clone())
257 .child(
258 h_flex().justify_end().child(
259 Button::new("cancel-inline-reply")
260 .ghost()
261 .compact()
262 .label("Cancel")
263 .on_click(move |_, _, cx| {
264 view.update(cx, |this, cx| this.close_reply_editor(cx)).ok();
265 }),
266 ),
267 )
268 .into_any_element()
269 }
270}
crates/app/src/views/conversation/scheduled.rs +31 −9
@@ -10,10 +10,12 @@ use super::{ConversationView, HoverSlot, ViewMode};
10 10 use crate::backend::Engine;
11 11 use crate::notice::{short_error, truncated};
12 12 use crate::outbox::{deliver, new_outbox_id, outbox_record};
13 use crate::rows::{MessageRow, Row};
13 use crate::rows::MessageRow;
14 14 use crate::runtime;
15 15 use crate::scheduled::{conversation_of, thread_root_of};
16 use crate::scheduled_rows::{draft_id_of, draft_key, scheduled_outgoing, scheduled_rows};
16 use crate::scheduled_rows::{
17 draft_id_of, draft_key, scheduled_feed_rows, scheduled_outgoing, scheduled_rows,
18 };
17 19 use crate::views::composer::{EditPreview, Outgoing};
18 20 use crate::views::message_actions::{Action, HoverChange};
19 21 use crate::views::message_row::{DeliveryActions, RowAction};
@@ -61,7 +63,7 @@ impl ConversationView {
61 63 })
62 64 }
63 65
64 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<Row> {
66 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<MessageRow> {
65 67 let (Some(inner_thread_id), Some(conversation_id)) =
66 68 (self.scheduled_thread_id(), self.conversation_id())
67 69 else {
@@ -71,17 +73,24 @@ impl ConversationView {
71 73 .scheduled_failure
72 74 .as_ref()
73 75 .map(|failure| failure.draft_id.as_str());
76 let drafts = &self.app.read(cx).scheduled;
77 if self.in_feed() {
78 return scheduled_feed_rows(
79 drafts,
80 &conversation_id,
81 my_user_id,
82 Utc::now(),
83 change_failed,
84 );
85 }
74 86 scheduled_rows(
75 &self.app.read(cx).scheduled,
87 drafts,
76 88 &inner_thread_id,
77 89 &conversation_id,
78 90 my_user_id,
79 91 Utc::now(),
80 92 change_failed,
81 93 )
82 .into_iter()
83 .map(|row| Row::Message(Box::new(row)))
84 .collect()
85 94 }
86 95
87 96 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
@@ -115,6 +124,13 @@ impl ConversationView {
115 124 else {
116 125 return;
117 126 };
127 if self.in_feed() && self.has_subject(cx) {
128 self.notice = Some("Can't schedule a post with a subject yet".to_owned());
129 self.composer
130 .update(cx, |composer, cx| composer.fail_schedule(cx));
131 cx.notify();
132 return;
133 }
118 134 let html = outgoing.html();
119 135 if self.app.read(cx).mode.demo {
120 136 let draft = demo_draft(&inner_thread_id, &html, send_at);
@@ -164,9 +180,14 @@ impl ConversationView {
164 180 self.composer.update(cx, |composer, cx| {
165 181 composer.finish_schedule(conversation_id, window, cx)
166 182 });
183 if self.in_feed() {
184 self.close_new_post(cx);
185 }
167 186 self.rebuild(false, cx);
168 self.scroller
169 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
187 if !self.in_feed() {
188 self.scroller
189 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
190 }
170 191 }
171 192
172 193 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
@@ -201,6 +222,7 @@ impl ConversationView {
201 222 excerpt,
202 223 scheduled: Some(draft.send_at),
203 224 });
225 self.show_main_composer(cx);
204 226 self.composer
205 227 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
206 228 }
@@ -10,10 +10,12 @@ use super::{ConversationView, HoverSlot, ViewMode};
10use crate::backend::Engine;
10use crate::backend::Engine;
11use crate::notice::{short_error, truncated};
11use crate::notice::{short_error, truncated};
12use crate::outbox::{deliver, new_outbox_id, outbox_record};
12use crate::outbox::{deliver, new_outbox_id, outbox_record};
13use crate::rows::{MessageRow, Row};
13use crate::rows::MessageRow;
14use crate::runtime;
14use crate::runtime;
15use crate::scheduled::{conversation_of, thread_root_of};
15use crate::scheduled::{conversation_of, thread_root_of};
16use crate::scheduled_rows::{draft_id_of, draft_key, scheduled_outgoing, scheduled_rows};
16use crate::scheduled_rows::{
17 draft_id_of, draft_key, scheduled_feed_rows, scheduled_outgoing, scheduled_rows,
18};
17use crate::views::composer::{EditPreview, Outgoing};
19use crate::views::composer::{EditPreview, Outgoing};
18use crate::views::message_actions::{Action, HoverChange};
20use crate::views::message_actions::{Action, HoverChange};
19use crate::views::message_row::{DeliveryActions, RowAction};
21use crate::views::message_row::{DeliveryActions, RowAction};
@@ -61,7 +63,7 @@ impl ConversationView {
61 })
63 })
62 }
64 }
63
65
64 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<Row> {
66 pub(super) fn scheduled_rows(&self, my_user_id: Option<&str>, cx: &App) -> Vec<MessageRow> {
65 let (Some(inner_thread_id), Some(conversation_id)) =
67 let (Some(inner_thread_id), Some(conversation_id)) =
66 (self.scheduled_thread_id(), self.conversation_id())
68 (self.scheduled_thread_id(), self.conversation_id())
67 else {
69 else {
@@ -71,17 +73,24 @@ impl ConversationView {
71 .scheduled_failure
73 .scheduled_failure
72 .as_ref()
74 .as_ref()
73 .map(|failure| failure.draft_id.as_str());
75 .map(|failure| failure.draft_id.as_str());
76 let drafts = &self.app.read(cx).scheduled;
77 if self.in_feed() {
78 return scheduled_feed_rows(
79 drafts,
80 &conversation_id,
81 my_user_id,
82 Utc::now(),
83 change_failed,
84 );
85 }
74 scheduled_rows(
86 scheduled_rows(
75 &self.app.read(cx).scheduled,
87 drafts,
76 &inner_thread_id,
88 &inner_thread_id,
77 &conversation_id,
89 &conversation_id,
78 my_user_id,
90 my_user_id,
79 Utc::now(),
91 Utc::now(),
80 change_failed,
92 change_failed,
81 )
93 )
82 .into_iter()
83 .map(|row| Row::Message(Box::new(row)))
84 .collect()
85 }
94 }
86
95
87 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
96 fn scheduled_draft(&self, draft_id: &str, cx: &App) -> Option<ScheduledDraft> {
@@ -115,6 +124,13 @@ impl ConversationView {
115 else {
124 else {
116 return;
125 return;
117 };
126 };
127 if self.in_feed() && self.has_subject(cx) {
128 self.notice = Some("Can't schedule a post with a subject yet".to_owned());
129 self.composer
130 .update(cx, |composer, cx| composer.fail_schedule(cx));
131 cx.notify();
132 return;
133 }
118 let html = outgoing.html();
134 let html = outgoing.html();
119 if self.app.read(cx).mode.demo {
135 if self.app.read(cx).mode.demo {
120 let draft = demo_draft(&inner_thread_id, &html, send_at);
136 let draft = demo_draft(&inner_thread_id, &html, send_at);
@@ -164,9 +180,14 @@ impl ConversationView {
164 self.composer.update(cx, |composer, cx| {
180 self.composer.update(cx, |composer, cx| {
165 composer.finish_schedule(conversation_id, window, cx)
181 composer.finish_schedule(conversation_id, window, cx)
166 });
182 });
183 if self.in_feed() {
184 self.close_new_post(cx);
185 }
167 self.rebuild(false, cx);
186 self.rebuild(false, cx);
168 self.scroller
187 if !self.in_feed() {
169 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
188 self.scroller
189 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
190 }
170 }
191 }
171
192
172 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
193 fn fail_scheduling(&mut self, error: &str, cx: &mut Context<Self>) {
@@ -201,6 +222,7 @@ impl ConversationView {
201 excerpt,
222 excerpt,
202 scheduled: Some(draft.send_at),
223 scheduled: Some(draft.send_at),
203 });
224 });
225 self.show_main_composer(cx);
204 self.composer
226 self.composer
205 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
227 .update(cx, |composer, cx| composer.begin_edit(outgoing, window, cx));
206 }
228 }
crates/app/src/views/message_row.rs +9 −196
@@ -1,4 +1,3 @@
1 use gpui_kit::base::TextSelection;
2 1 use gpui_kit::component::{h_flex, v_flex};
3 2 use gpui_kit::prelude::FluentBuilder as _;
4 3 use gpui_kit::*;
@@ -6,7 +5,7 @@ use std::time::Duration;
6 5
7 6 use super::adaptive_card::cards_view;
8 7 use super::attachments::{FileActions, attachments_view, message_body};
9 use super::avatar::{bot_avatar, member_stack, person_avatar};
8 use super::avatar::{bot_avatar, person_avatar};
10 9 use super::link_preview::link_preview_card;
11 10 use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12 11 use super::reaction_picker::PickHandler;
@@ -25,11 +24,9 @@ pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
25 24 const AVATAR_SIZE: f32 = 28.;
26 25 const AVATAR_GAP: f32 = 8.;
27 26 const SERIES_START_GAP: f32 = 8.;
28 const BODY_SIZE: f32 = 13.5;
27 pub(super) const BODY_SIZE: f32 = 13.5;
29 28 const MAX_WIDTH_RATIO: f32 = 0.7;
30 29 const REACTION_FOOTER_HEIGHT: f32 = 24.;
31 const CARD_AVATAR_SIZE: f32 = 32.;
32 const CARD_GAP: f32 = 12.;
33 30 const META_SIZE: f32 = 11.;
34 31 const META_CHECK_SIZE: f32 = 15.;
35 32 const FIGURE_SPACE_WIDTH: f32 = 7.4;
@@ -44,7 +41,6 @@ pub struct DeliveryActions {
44 41
45 42 pub struct RowActions {
46 43 pub bot: Option<BotIdentity>,
47 pub open_thread: RowAction,
48 44 pub delivery: DeliveryActions,
49 45 pub reply: RowAction,
50 46 pub hovered: Option<HoverChange>,
@@ -364,7 +360,7 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
364 360 Some(padded)
365 361 }
366 362
367 fn has_text(row: &MessageRow) -> bool {
363 pub(super) fn has_text(row: &MessageRow) -> bool {
368 364 !row.blocks.is_empty()
369 365 || (row.images.is_empty()
370 366 && row.local_images.is_empty()
@@ -384,7 +380,7 @@ fn delivery_link(index: usize, name: &str, label: &'static str, action: RowActio
384 380 })
385 381 }
386 382
387 fn delivery_note(
383 pub(super) fn delivery_note(
388 384 row: &MessageRow,
389 385 delivery: DeliveryActions,
390 386 index: usize,
@@ -425,173 +421,6 @@ fn delivery_note(
425 421 }
426 422 }
427 423
428 fn edited_marker() -> Div {
429 div()
430 .text_size(px(11.))
431 .italic()
432 .text_color(theme::text_muted())
433 .child("Edited")
434 }
435
436 fn post_card(
437 row: &MessageRow,
438 index: usize,
439 directory: &Directory,
440 files: Option<&FileActions>,
441 cx: &App,
442 ) -> Div {
443 let header = h_flex()
444 .gap(px(10.))
445 .items_center()
446 .child(person_avatar(
447 directory,
448 row.sender_id.as_deref(),
449 &row.author,
450 CARD_AVATAR_SIZE,
451 ))
452 .child(
453 v_flex()
454 .child(
455 div()
456 .text_size(px(13.))
457 .font_weight(FontWeight::SEMIBOLD)
458 .text_color(theme::text())
459 .child(row.author.clone()),
460 )
461 .child(
462 h_flex()
463 .gap(px(6.))
464 .text_size(px(11.))
465 .text_color(theme::text_muted())
466 .child(row.time.clone())
467 .when(row.edited, |line| line.child(edited_marker())),
468 ),
469 );
470 let count = row.reply_count.unwrap_or(0);
471 let footer = h_flex()
472 .gap(px(8.))
473 .items_center()
474 .pt(px(8.))
475 .border_t_1()
476 .border_color(theme::border())
477 .when(count > 0, |line| {
478 line.child(member_stack(
479 directory,
480 &row.reply_faces,
481 row.reply_faces.len(),
482 ))
483 })
484 .child(
485 div()
486 .text_size(px(12.5))
487 .font_weight(if count > 0 {
488 FontWeight::SEMIBOLD
489 } else {
490 FontWeight::NORMAL
491 })
492 .text_color(if count > 0 {
493 theme::accent_text()
494 } else {
495 theme::text_muted()
496 })
497 .child(match count {
498 0 => "No replies".to_owned(),
499 1 => "1 reply".to_owned(),
500 count => format!("{count} replies"),
501 }),
502 )
503 .children(row.last_reply_time.as_ref().map(|time| {
504 div()
505 .text_size(px(11.5))
506 .text_color(theme::text_muted())
507 .child(format!("Last reply {time}"))
508 }))
509 .child(div().flex_1())
510 .child(
511 div()
512 .text_size(px(12.5))
513 .text_color(theme::text_soft())
514 .child("Reply"),
515 );
516 let mut body = v_flex().gap(px(8.)).child(header);
517 if row.deleted {
518 body = body.child(
519 div()
520 .text_size(px(13.))
521 .italic()
522 .text_color(theme::text_muted())
523 .child(DELETED_PREVIEW),
524 );
525 } else {
526 if has_text(row) {
527 body = body.child(
528 v_flex()
529 .gap(px(6.))
530 .text_size(px(BODY_SIZE))
531 .line_height(relative(1.45))
532 .text_color(theme::text_strong())
533 .children(message_body(
534 &row.blocks,
535 &row.images,
536 &row.local_images,
537 &format!("message-{index}"),
538 false,
539 directory,
540 cx,
541 )),
542 );
543 }
544 body = body.children(attachments_view(
545 &row.blocks,
546 &row.images,
547 &row.local_images,
548 &row.files,
549 &format!("message-{index}"),
550 directory,
551 files,
552 ));
553 body = body.children(row.link_preview.as_ref().map(|preview| {
554 link_preview_card(
555 preview,
556 format!("message-{index}-link"),
557 directory,
558 false,
559 None,
560 )
561 }));
562 body = body.children(cards_view(
563 &row.adaptive_cards,
564 &row.conversation_id,
565 &row.key,
566 cx,
567 ));
568 if !row.reactions.is_empty() {
569 body = body.child(reaction_pills(
570 &row.reactions,
571 index,
572 false,
573 directory,
574 None,
575 None,
576 ));
577 }
578 }
579 v_flex()
580 .w_full()
581 .gap(px(8.))
582 .p(px(12.))
583 .rounded(px(10.))
584 .bg(theme::surface())
585 .border_1()
586 .border_color(theme::border())
587 .hover(|card| {
588 card.border_color(theme::border_strong())
589 .bg(theme::row_hover())
590 })
591 .child(body)
592 .child(footer)
593 }
594
595 424 fn others_row(
596 425 row: &MessageRow,
597 426 index: usize,
@@ -622,9 +451,9 @@ fn others_row(
622 451 if let Some(note) = delivery_note(row, delivery, index) {
623 452 column = column.child(note);
624 453 }
625 let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
454 let lead = if let Some(bot) = bot.filter(|_| first) {
626 455 bot_avatar(bot, AVATAR_SIZE)
627 } else if first || row.card {
456 } else if first {
628 457 person_avatar(
629 458 directory,
630 459 row.sender_id.as_deref(),
@@ -671,7 +500,6 @@ pub fn render_message_row(
671 500 ) -> AnyElement {
672 501 let RowActions {
673 502 bot,
674 open_thread,
675 503 delivery,
676 504 reply,
677 505 hovered,
@@ -682,7 +510,6 @@ pub fn render_message_row(
682 510 files,
683 511 highlighted,
684 512 } = actions;
685 let card_hover = hovered.clone().filter(|_| row.card);
686 513 let extras = BubbleExtras {
687 514 hover: hovered,
688 515 menu,
@@ -691,10 +518,8 @@ pub fn render_message_row(
691 518 controls: reaction_controls,
692 519 files,
693 520 };
694 let own = row.own && !row.card;
695 let spacing = if row.card {
696 px(CARD_GAP)
697 } else if row.series.has_prev {
521 let own = row.own;
522 let spacing = if row.series.has_prev {
698 523 px(2.)
699 524 } else {
700 525 px(SERIES_START_GAP)
@@ -706,9 +531,7 @@ pub fn render_message_row(
706 531 if row.new_marker {
707 532 container = container.child(new_marker());
708 533 }
709 let body = if row.card {
710 post_card(row, index, directory, extras.files.as_ref(), cx)
711 } else if own {
534 let body = if own {
712 535 own_row(row, index, directory, delivery, extras, cx)
713 536 } else {
714 537 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
@@ -719,16 +542,6 @@ pub fn render_message_row(
719 542 .id(ElementId::Name(format!("row-{index}").into()))
720 543 .w_full()
721 544 .pt(spacing)
722 .when_some(open_thread, |element, open| {
723 element.cursor_pointer().on_click(move |_, window, cx| {
724 if TextSelection::selected_text(window, cx).is_empty() {
725 open(cx);
726 }
727 })
728 })
729 .when_some(card_hover, |element, hovered| {
730 element.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
731 })
732 545 .when_some(reply, |element, reply| {
733 546 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
734 547 })
@@ -1,4 +1,3 @@
1use gpui_kit::base::TextSelection;
2use gpui_kit::component::{h_flex, v_flex};
1use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
2use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
3use gpui_kit::*;
@@ -6,7 +5,7 @@ use std::time::Duration;
6
5
7use super::adaptive_card::cards_view;
6use super::adaptive_card::cards_view;
8use super::attachments::{FileActions, attachments_view, message_body};
7use super::attachments::{FileActions, attachments_view, message_body};
9use super::avatar::{bot_avatar, member_stack, person_avatar};
8use super::avatar::{bot_avatar, person_avatar};
10use super::link_preview::link_preview_card;
9use super::link_preview::link_preview_card;
11use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
10use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
12use super::reaction_picker::PickHandler;
11use super::reaction_picker::PickHandler;
@@ -25,11 +24,9 @@ pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
25const AVATAR_SIZE: f32 = 28.;
24const AVATAR_SIZE: f32 = 28.;
26const AVATAR_GAP: f32 = 8.;
25const AVATAR_GAP: f32 = 8.;
27const SERIES_START_GAP: f32 = 8.;
26const SERIES_START_GAP: f32 = 8.;
28const BODY_SIZE: f32 = 13.5;
27pub(super) const BODY_SIZE: f32 = 13.5;
29const MAX_WIDTH_RATIO: f32 = 0.7;
28const MAX_WIDTH_RATIO: f32 = 0.7;
30const REACTION_FOOTER_HEIGHT: f32 = 24.;
29const REACTION_FOOTER_HEIGHT: f32 = 24.;
31const CARD_AVATAR_SIZE: f32 = 32.;
32const CARD_GAP: f32 = 12.;
33const META_SIZE: f32 = 11.;
30const META_SIZE: f32 = 11.;
34const META_CHECK_SIZE: f32 = 15.;
31const META_CHECK_SIZE: f32 = 15.;
35const FIGURE_SPACE_WIDTH: f32 = 7.4;
32const FIGURE_SPACE_WIDTH: f32 = 7.4;
@@ -44,7 +41,6 @@ pub struct DeliveryActions {
44
41
45pub struct RowActions {
42pub struct RowActions {
46 pub bot: Option<BotIdentity>,
43 pub bot: Option<BotIdentity>,
47 pub open_thread: RowAction,
48 pub delivery: DeliveryActions,
44 pub delivery: DeliveryActions,
49 pub reply: RowAction,
45 pub reply: RowAction,
50 pub hovered: Option<HoverChange>,
46 pub hovered: Option<HoverChange>,
@@ -364,7 +360,7 @@ fn with_meta_room(blocks: &[Block], room: usize) -> Option<Vec<Block>> {
364 Some(padded)
360 Some(padded)
365}
361}
366
362
367fn has_text(row: &MessageRow) -> bool {
363pub(super) fn has_text(row: &MessageRow) -> bool {
368 !row.blocks.is_empty()
364 !row.blocks.is_empty()
369 || (row.images.is_empty()
365 || (row.images.is_empty()
370 && row.local_images.is_empty()
366 && row.local_images.is_empty()
@@ -384,7 +380,7 @@ fn delivery_link(index: usize, name: &str, label: &'static str, action: RowActio
384 })
380 })
385}
381}
386
382
387fn delivery_note(
383pub(super) fn delivery_note(
388 row: &MessageRow,
384 row: &MessageRow,
389 delivery: DeliveryActions,
385 delivery: DeliveryActions,
390 index: usize,
386 index: usize,
@@ -425,173 +421,6 @@ fn delivery_note(
425 }
421 }
426}
422}
427
423
428fn edited_marker() -> Div {
429 div()
430 .text_size(px(11.))
431 .italic()
432 .text_color(theme::text_muted())
433 .child("Edited")
434}
435
436fn post_card(
437 row: &MessageRow,
438 index: usize,
439 directory: &Directory,
440 files: Option<&FileActions>,
441 cx: &App,
442) -> Div {
443 let header = h_flex()
444 .gap(px(10.))
445 .items_center()
446 .child(person_avatar(
447 directory,
448 row.sender_id.as_deref(),
449 &row.author,
450 CARD_AVATAR_SIZE,
451 ))
452 .child(
453 v_flex()
454 .child(
455 div()
456 .text_size(px(13.))
457 .font_weight(FontWeight::SEMIBOLD)
458 .text_color(theme::text())
459 .child(row.author.clone()),
460 )
461 .child(
462 h_flex()
463 .gap(px(6.))
464 .text_size(px(11.))
465 .text_color(theme::text_muted())
466 .child(row.time.clone())
467 .when(row.edited, |line| line.child(edited_marker())),
468 ),
469 );
470 let count = row.reply_count.unwrap_or(0);
471 let footer = h_flex()
472 .gap(px(8.))
473 .items_center()
474 .pt(px(8.))
475 .border_t_1()
476 .border_color(theme::border())
477 .when(count > 0, |line| {
478 line.child(member_stack(
479 directory,
480 &row.reply_faces,
481 row.reply_faces.len(),
482 ))
483 })
484 .child(
485 div()
486 .text_size(px(12.5))
487 .font_weight(if count > 0 {
488 FontWeight::SEMIBOLD
489 } else {
490 FontWeight::NORMAL
491 })
492 .text_color(if count > 0 {
493 theme::accent_text()
494 } else {
495 theme::text_muted()
496 })
497 .child(match count {
498 0 => "No replies".to_owned(),
499 1 => "1 reply".to_owned(),
500 count => format!("{count} replies"),
501 }),
502 )
503 .children(row.last_reply_time.as_ref().map(|time| {
504 div()
505 .text_size(px(11.5))
506 .text_color(theme::text_muted())
507 .child(format!("Last reply {time}"))
508 }))
509 .child(div().flex_1())
510 .child(
511 div()
512 .text_size(px(12.5))
513 .text_color(theme::text_soft())
514 .child("Reply"),
515 );
516 let mut body = v_flex().gap(px(8.)).child(header);
517 if row.deleted {
518 body = body.child(
519 div()
520 .text_size(px(13.))
521 .italic()
522 .text_color(theme::text_muted())
523 .child(DELETED_PREVIEW),
524 );
525 } else {
526 if has_text(row) {
527 body = body.child(
528 v_flex()
529 .gap(px(6.))
530 .text_size(px(BODY_SIZE))
531 .line_height(relative(1.45))
532 .text_color(theme::text_strong())
533 .children(message_body(
534 &row.blocks,
535 &row.images,
536 &row.local_images,
537 &format!("message-{index}"),
538 false,
539 directory,
540 cx,
541 )),
542 );
543 }
544 body = body.children(attachments_view(
545 &row.blocks,
546 &row.images,
547 &row.local_images,
548 &row.files,
549 &format!("message-{index}"),
550 directory,
551 files,
552 ));
553 body = body.children(row.link_preview.as_ref().map(|preview| {
554 link_preview_card(
555 preview,
556 format!("message-{index}-link"),
557 directory,
558 false,
559 None,
560 )
561 }));
562 body = body.children(cards_view(
563 &row.adaptive_cards,
564 &row.conversation_id,
565 &row.key,
566 cx,
567 ));
568 if !row.reactions.is_empty() {
569 body = body.child(reaction_pills(
570 &row.reactions,
571 index,
572 false,
573 directory,
574 None,
575 None,
576 ));
577 }
578 }
579 v_flex()
580 .w_full()
581 .gap(px(8.))
582 .p(px(12.))
583 .rounded(px(10.))
584 .bg(theme::surface())
585 .border_1()
586 .border_color(theme::border())
587 .hover(|card| {
588 card.border_color(theme::border_strong())
589 .bg(theme::row_hover())
590 })
591 .child(body)
592 .child(footer)
593}
594
595fn others_row(
424fn others_row(
596 row: &MessageRow,
425 row: &MessageRow,
597 index: usize,
426 index: usize,
@@ -622,9 +451,9 @@ fn others_row(
622 if let Some(note) = delivery_note(row, delivery, index) {
451 if let Some(note) = delivery_note(row, delivery, index) {
623 column = column.child(note);
452 column = column.child(note);
624 }
453 }
625 let lead = if let Some(bot) = bot.filter(|_| first || row.card) {
454 let lead = if let Some(bot) = bot.filter(|_| first) {
626 bot_avatar(bot, AVATAR_SIZE)
455 bot_avatar(bot, AVATAR_SIZE)
627 } else if first || row.card {
456 } else if first {
628 person_avatar(
457 person_avatar(
629 directory,
458 directory,
630 row.sender_id.as_deref(),
459 row.sender_id.as_deref(),
@@ -671,7 +500,6 @@ pub fn render_message_row(
671) -> AnyElement {
500) -> AnyElement {
672 let RowActions {
501 let RowActions {
673 bot,
502 bot,
674 open_thread,
675 delivery,
503 delivery,
676 reply,
504 reply,
677 hovered,
505 hovered,
@@ -682,7 +510,6 @@ pub fn render_message_row(
682 files,
510 files,
683 highlighted,
511 highlighted,
684 } = actions;
512 } = actions;
685 let card_hover = hovered.clone().filter(|_| row.card);
686 let extras = BubbleExtras {
513 let extras = BubbleExtras {
687 hover: hovered,
514 hover: hovered,
688 menu,
515 menu,
@@ -691,10 +518,8 @@ pub fn render_message_row(
691 controls: reaction_controls,
518 controls: reaction_controls,
692 files,
519 files,
693 };
520 };
694 let own = row.own && !row.card;
521 let own = row.own;
695 let spacing = if row.card {
522 let spacing = if row.series.has_prev {
696 px(CARD_GAP)
697 } else if row.series.has_prev {
698 px(2.)
523 px(2.)
699 } else {
524 } else {
700 px(SERIES_START_GAP)
525 px(SERIES_START_GAP)
@@ -706,9 +531,7 @@ pub fn render_message_row(
706 if row.new_marker {
531 if row.new_marker {
707 container = container.child(new_marker());
532 container = container.child(new_marker());
708 }
533 }
709 let body = if row.card {
534 let body = if own {
710 post_card(row, index, directory, extras.files.as_ref(), cx)
711 } else if own {
712 own_row(row, index, directory, delivery, extras, cx)
535 own_row(row, index, directory, delivery, extras, cx)
713 } else {
536 } else {
714 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
537 others_row(row, index, directory, bot.as_ref(), delivery, extras, cx)
@@ -719,16 +542,6 @@ pub fn render_message_row(
719 .id(ElementId::Name(format!("row-{index}").into()))
542 .id(ElementId::Name(format!("row-{index}").into()))
720 .w_full()
543 .w_full()
721 .pt(spacing)
544 .pt(spacing)
722 .when_some(open_thread, |element, open| {
723 element.cursor_pointer().on_click(move |_, window, cx| {
724 if TextSelection::selected_text(window, cx).is_empty() {
725 open(cx);
726 }
727 })
728 })
729 .when_some(card_hover, |element, hovered| {
730 element.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
731 })
732 .when_some(reply, |element, reply| {
545 .when_some(reply, |element, reply| {
733 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
546 element.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
734 })
547 })
crates/app/src/views/mod.rs +1 −0
@@ -15,6 +15,7 @@ pub mod fun_picker;
15 15 pub mod message_actions;
16 16 pub mod message_row;
17 17 pub mod new_chat;
18 pub mod post_card;
18 19 pub mod reaction_picker;
19 20 pub mod reaction_pills;
20 21 pub mod scheduled_toolbar;
@@ -15,6 +15,7 @@ pub mod fun_picker;
15pub mod message_actions;
15pub mod message_actions;
16pub mod message_row;
16pub mod message_row;
17pub mod new_chat;
17pub mod new_chat;
18pub mod post_card;
18pub mod reaction_picker;
19pub mod reaction_picker;
19pub mod reaction_pills;
20pub mod reaction_pills;
20pub mod scheduled_toolbar;
21pub mod scheduled_toolbar;
crates/app/src/views/post_card.rs added +355 −0
@@ -0,0 +1,355 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{h_flex, v_flex};
3 use gpui_kit::prelude::FluentBuilder as _;
4 use gpui_kit::*;
5
6 use super::adaptive_card::cards_view;
7 use super::attachments::{attachments_view, message_body};
8 use super::avatar::{bot_avatar, person_avatar};
9 use super::link_preview::link_preview_card;
10 use super::message_actions::message_toolbar;
11 use super::message_row::{BODY_SIZE, RowActions, delivery_note, has_text};
12 use super::reaction_pills::reaction_pills;
13 use super::scheduled_toolbar::scheduled_toolbar;
14 use super::widgets::{icon, symbol};
15 use crate::data::Directory;
16 use crate::rows::{Delivery, MessageRow, PostRow};
17 use crate::sidebar_model::DELETED_PREVIEW;
18 use crate::theme;
19
20 const ROOT_AVATAR: f32 = 32.;
21 const REPLY_AVATAR: f32 = 24.;
22 const AVATAR_GAP: f32 = 10.;
23 const CARD_PADDING: f32 = 12.;
24 const CARD_RADIUS: f32 = 8.;
25 const CARD_GAP: f32 = 12.;
26 const SLOTS_PER_POST: usize = 64;
27 const TOOLBAR_LIFT: f32 = 22.;
28 const SUBJECT_SIZE: f32 = 14.;
29
30 pub type PostAction = Box<dyn Fn(&mut Window, &mut App)>;
31
32 pub struct PostActions {
33 pub root: RowActions,
34 pub replies: Vec<RowActions>,
35 pub open_thread: Option<PostAction>,
36 pub open_reply: Option<PostAction>,
37 pub reply_editor: Option<AnyElement>,
38 }
39
40 #[derive(Clone, Copy, PartialEq, Eq)]
41 enum Role {
42 Root,
43 Reply,
44 }
45
46 fn message_index(post_index: usize, slot: usize) -> usize {
47 post_index * SLOTS_PER_POST + slot.min(SLOTS_PER_POST - 1)
48 }
49
50 fn edited_marker() -> Div {
51 div()
52 .text_size(px(11.))
53 .italic()
54 .text_color(theme::text_muted())
55 .child("Edited")
56 }
57
58 fn message_content(
59 row: &MessageRow,
60 index: usize,
61 directory: &Directory,
62 actions: &RowActions,
63 cx: &App,
64 ) -> Div {
65 let mut content = v_flex().gap(px(6.));
66 if row.deleted {
67 return content.child(
68 div()
69 .text_size(px(13.))
70 .italic()
71 .text_color(theme::text_muted())
72 .child(DELETED_PREVIEW),
73 );
74 }
75 if has_text(row) {
76 content = content.child(
77 v_flex()
78 .gap(px(6.))
79 .text_size(px(BODY_SIZE))
80 .line_height(relative(1.45))
81 .text_color(theme::text_strong())
82 .children(message_body(
83 &row.blocks,
84 &row.images,
85 &row.local_images,
86 &format!("message-{index}"),
87 false,
88 directory,
89 cx,
90 )),
91 );
92 }
93 content = content.children(attachments_view(
94 &row.blocks,
95 &row.images,
96 &row.local_images,
97 &row.files,
98 &format!("message-{index}"),
99 directory,
100 actions.files.as_ref(),
101 ));
102 content = content.children(row.link_preview.as_ref().map(|preview| {
103 link_preview_card(
104 preview,
105 format!("message-{index}-link"),
106 directory,
107 false,
108 None,
109 )
110 }));
111 content = content.children(cards_view(
112 &row.adaptive_cards,
113 &row.conversation_id,
114 &row.key,
115 cx,
116 ));
117 if !row.reactions.is_empty() {
118 content = content.child(reaction_pills(
119 &row.reactions,
120 index,
121 false,
122 directory,
123 actions.react.clone(),
124 actions.reaction_controls.as_ref(),
125 ));
126 }
127 content
128 }
129
130 fn message_header(row: &MessageRow, author: String) -> Div {
131 h_flex()
132 .gap(px(6.))
133 .items_center()
134 .child(
135 div()
136 .text_size(px(13.))
137 .font_weight(FontWeight::SEMIBOLD)
138 .text_color(theme::text())
139 .child(author),
140 )
141 .child(
142 div()
143 .text_size(px(11.))
144 .text_color(theme::text_muted())
145 .child(row.time.clone()),
146 )
147 .when(row.edited, |line| line.child(edited_marker()))
148 .when(row.delivery == Delivery::Sending, |line| {
149 line.child(symbol("schedule", 13., theme::text_muted()))
150 })
151 }
152
153 fn message_block(
154 row: &MessageRow,
155 index: usize,
156 role: Role,
157 actions: RowActions,
158 directory: &Directory,
159 cx: &App,
160 ) -> Stateful<Div> {
161 let size = if role == Role::Root {
162 ROOT_AVATAR
163 } else {
164 REPLY_AVATAR
165 };
166 let author = actions
167 .bot
168 .as_ref()
169 .map_or_else(|| row.author.clone(), |bot| bot.name.clone());
170 let avatar = match &actions.bot {
171 Some(bot) => bot_avatar(bot, size),
172 None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
173 };
174 let content = message_content(row, index, directory, &actions, cx);
175 let RowActions {
176 delivery,
177 reply,
178 hovered,
179 menu,
180 scheduled_menu,
181 highlighted,
182 ..
183 } = actions;
184 let note = delivery_note(row, delivery, index);
185 let body = v_flex()
186 .flex_1()
187 .min_w_0()
188 .gap(px(6.))
189 .child(message_header(row, author))
190 .when_some(
191 row.subject.clone().filter(|_| role == Role::Root),
192 |column, subject| {
193 column.child(
194 div()
195 .text_size(px(SUBJECT_SIZE))
196 .font_weight(FontWeight::BOLD)
197 .text_color(theme::text())
198 .child(subject),
199 )
200 },
201 )
202 .child(content)
203 .children(note);
204 div()
205 .id(ElementId::Name(format!("post-message-{index}").into()))
206 .relative()
207 .w_full()
208 .p(px(CARD_PADDING))
209 .when(role == Role::Reply, |block| {
210 block
211 .pl(px(CARD_PADDING + ROOT_AVATAR + AVATAR_GAP))
212 .border_t_1()
213 .border_color(theme::border())
214 })
215 .when(highlighted, |block| block.bg(theme::accent().opacity(0.2)))
216 .when_some(hovered, |block, hovered| {
217 block.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
218 })
219 .when_some(reply, |block, reply| {
220 block.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
221 })
222 .child(
223 h_flex()
224 .items_start()
225 .gap(px(if role == Role::Root { AVATAR_GAP } else { 8. }))
226 .child(div().w(px(size)).flex_none().child(avatar))
227 .child(body),
228 )
229 .when_some(menu, |block, menu| {
230 block.child(
231 div()
232 .absolute()
233 .top(px(-TOOLBAR_LIFT))
234 .right(px(8.))
235 .child(deferred(message_toolbar(menu)).with_priority(1)),
236 )
237 })
238 .when_some(scheduled_menu, |block, menu| {
239 block.child(
240 div()
241 .absolute()
242 .top(px(-TOOLBAR_LIFT))
243 .right(px(8.))
244 .child(deferred(scheduled_toolbar(menu)).with_priority(1)),
245 )
246 })
247 }
248
249 fn replies_link(label: String, post_index: usize, open: Option<PostAction>) -> Stateful<Div> {
250 div()
251 .id(ElementId::Name(format!("post-replies-{post_index}").into()))
252 .pl(px(CARD_PADDING + ROOT_AVATAR + AVATAR_GAP))
253 .pr(px(CARD_PADDING))
254 .pb(px(8.))
255 .text_size(px(13.))
256 .font_weight(FontWeight::SEMIBOLD)
257 .text_color(theme::accent_text())
258 .when_some(open, |link, open| {
259 link.cursor_pointer()
260 .hover(|link| link.text_color(theme::accent_soft()))
261 .on_click(move |_, window, cx| open(window, cx))
262 })
263 .child(label)
264 }
265
266 fn reply_footer(
267 post_index: usize,
268 open: Option<PostAction>,
269 editor: Option<AnyElement>,
270 ) -> Option<Div> {
271 let footer = v_flex()
272 .w_full()
273 .px(px(CARD_PADDING))
274 .py(px(8.))
275 .border_t_1()
276 .border_color(theme::border());
277 if let Some(editor) = editor {
278 return Some(footer.child(editor));
279 }
280 let open = open?;
281 Some(
282 footer.child(
283 h_flex().child(
284 h_flex()
285 .id(ElementId::Name(format!("post-reply-{post_index}").into()))
286 .gap(px(6.))
287 .px(px(6.))
288 .py(px(4.))
289 .items_center()
290 .rounded(px(6.))
291 .cursor_pointer()
292 .text_size(px(12.5))
293 .text_color(theme::text_muted())
294 .hover(|button| {
295 button
296 .bg(theme::row_hover())
297 .text_color(theme::text_strong())
298 })
299 .on_click(move |_, window, cx| open(window, cx))
300 .child(icon(IconName::Reply, 14., theme::text_muted()))
301 .child("Reply"),
302 ),
303 ),
304 )
305 }
306
307 pub fn render_post(
308 post: &PostRow,
309 index: usize,
310 actions: PostActions,
311 directory: &Directory,
312 cx: &App,
313 ) -> AnyElement {
314 let PostActions {
315 root,
316 replies,
317 open_thread,
318 open_reply,
319 reply_editor,
320 } = actions;
321 let mut card = v_flex()
322 .w_full()
323 .rounded(px(CARD_RADIUS))
324 .bg(theme::surface())
325 .border_1()
326 .border_color(theme::border())
327 .child(message_block(
328 &post.root,
329 message_index(index, 0),
330 Role::Root,
331 root,
332 directory,
333 cx,
334 ));
335 if let Some(label) = post.hidden_replies_label() {
336 card = card.child(replies_link(label, index, open_thread));
337 }
338 for (position, (reply, actions)) in post.replies.iter().zip(replies).enumerate() {
339 card = card.child(message_block(
340 reply,
341 message_index(index, position + 1),
342 Role::Reply,
343 actions,
344 directory,
345 cx,
346 ));
347 }
348 card = card.children(reply_footer(index, open_reply, reply_editor));
349 div()
350 .w_full()
351 .px(px(24.))
352 .pt(px(CARD_GAP))
353 .child(card)
354 .into_any_element()
355 }
@@ -0,0 +1,355 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5
6use super::adaptive_card::cards_view;
7use super::attachments::{attachments_view, message_body};
8use super::avatar::{bot_avatar, person_avatar};
9use super::link_preview::link_preview_card;
10use super::message_actions::message_toolbar;
11use super::message_row::{BODY_SIZE, RowActions, delivery_note, has_text};
12use super::reaction_pills::reaction_pills;
13use super::scheduled_toolbar::scheduled_toolbar;
14use super::widgets::{icon, symbol};
15use crate::data::Directory;
16use crate::rows::{Delivery, MessageRow, PostRow};
17use crate::sidebar_model::DELETED_PREVIEW;
18use crate::theme;
19
20const ROOT_AVATAR: f32 = 32.;
21const REPLY_AVATAR: f32 = 24.;
22const AVATAR_GAP: f32 = 10.;
23const CARD_PADDING: f32 = 12.;
24const CARD_RADIUS: f32 = 8.;
25const CARD_GAP: f32 = 12.;
26const SLOTS_PER_POST: usize = 64;
27const TOOLBAR_LIFT: f32 = 22.;
28const SUBJECT_SIZE: f32 = 14.;
29
30pub type PostAction = Box<dyn Fn(&mut Window, &mut App)>;
31
32pub struct PostActions {
33 pub root: RowActions,
34 pub replies: Vec<RowActions>,
35 pub open_thread: Option<PostAction>,
36 pub open_reply: Option<PostAction>,
37 pub reply_editor: Option<AnyElement>,
38}
39
40#[derive(Clone, Copy, PartialEq, Eq)]
41enum Role {
42 Root,
43 Reply,
44}
45
46fn message_index(post_index: usize, slot: usize) -> usize {
47 post_index * SLOTS_PER_POST + slot.min(SLOTS_PER_POST - 1)
48}
49
50fn edited_marker() -> Div {
51 div()
52 .text_size(px(11.))
53 .italic()
54 .text_color(theme::text_muted())
55 .child("Edited")
56}
57
58fn message_content(
59 row: &MessageRow,
60 index: usize,
61 directory: &Directory,
62 actions: &RowActions,
63 cx: &App,
64) -> Div {
65 let mut content = v_flex().gap(px(6.));
66 if row.deleted {
67 return content.child(
68 div()
69 .text_size(px(13.))
70 .italic()
71 .text_color(theme::text_muted())
72 .child(DELETED_PREVIEW),
73 );
74 }
75 if has_text(row) {
76 content = content.child(
77 v_flex()
78 .gap(px(6.))
79 .text_size(px(BODY_SIZE))
80 .line_height(relative(1.45))
81 .text_color(theme::text_strong())
82 .children(message_body(
83 &row.blocks,
84 &row.images,
85 &row.local_images,
86 &format!("message-{index}"),
87 false,
88 directory,
89 cx,
90 )),
91 );
92 }
93 content = content.children(attachments_view(
94 &row.blocks,
95 &row.images,
96 &row.local_images,
97 &row.files,
98 &format!("message-{index}"),
99 directory,
100 actions.files.as_ref(),
101 ));
102 content = content.children(row.link_preview.as_ref().map(|preview| {
103 link_preview_card(
104 preview,
105 format!("message-{index}-link"),
106 directory,
107 false,
108 None,
109 )
110 }));
111 content = content.children(cards_view(
112 &row.adaptive_cards,
113 &row.conversation_id,
114 &row.key,
115 cx,
116 ));
117 if !row.reactions.is_empty() {
118 content = content.child(reaction_pills(
119 &row.reactions,
120 index,
121 false,
122 directory,
123 actions.react.clone(),
124 actions.reaction_controls.as_ref(),
125 ));
126 }
127 content
128}
129
130fn message_header(row: &MessageRow, author: String) -> Div {
131 h_flex()
132 .gap(px(6.))
133 .items_center()
134 .child(
135 div()
136 .text_size(px(13.))
137 .font_weight(FontWeight::SEMIBOLD)
138 .text_color(theme::text())
139 .child(author),
140 )
141 .child(
142 div()
143 .text_size(px(11.))
144 .text_color(theme::text_muted())
145 .child(row.time.clone()),
146 )
147 .when(row.edited, |line| line.child(edited_marker()))
148 .when(row.delivery == Delivery::Sending, |line| {
149 line.child(symbol("schedule", 13., theme::text_muted()))
150 })
151}
152
153fn message_block(
154 row: &MessageRow,
155 index: usize,
156 role: Role,
157 actions: RowActions,
158 directory: &Directory,
159 cx: &App,
160) -> Stateful<Div> {
161 let size = if role == Role::Root {
162 ROOT_AVATAR
163 } else {
164 REPLY_AVATAR
165 };
166 let author = actions
167 .bot
168 .as_ref()
169 .map_or_else(|| row.author.clone(), |bot| bot.name.clone());
170 let avatar = match &actions.bot {
171 Some(bot) => bot_avatar(bot, size),
172 None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
173 };
174 let content = message_content(row, index, directory, &actions, cx);
175 let RowActions {
176 delivery,
177 reply,
178 hovered,
179 menu,
180 scheduled_menu,
181 highlighted,
182 ..
183 } = actions;
184 let note = delivery_note(row, delivery, index);
185 let body = v_flex()
186 .flex_1()
187 .min_w_0()
188 .gap(px(6.))
189 .child(message_header(row, author))
190 .when_some(
191 row.subject.clone().filter(|_| role == Role::Root),
192 |column, subject| {
193 column.child(
194 div()
195 .text_size(px(SUBJECT_SIZE))
196 .font_weight(FontWeight::BOLD)
197 .text_color(theme::text())
198 .child(subject),
199 )
200 },
201 )
202 .child(content)
203 .children(note);
204 div()
205 .id(ElementId::Name(format!("post-message-{index}").into()))
206 .relative()
207 .w_full()
208 .p(px(CARD_PADDING))
209 .when(role == Role::Reply, |block| {
210 block
211 .pl(px(CARD_PADDING + ROOT_AVATAR + AVATAR_GAP))
212 .border_t_1()
213 .border_color(theme::border())
214 })
215 .when(highlighted, |block| block.bg(theme::accent().opacity(0.2)))
216 .when_some(hovered, |block, hovered| {
217 block.on_hover(move |is_hovered, _, cx| hovered(*is_hovered, cx))
218 })
219 .when_some(reply, |block, reply| {
220 block.on_mouse_down(MouseButton::Right, move |_, _, cx| reply(cx))
221 })
222 .child(
223 h_flex()
224 .items_start()
225 .gap(px(if role == Role::Root { AVATAR_GAP } else { 8. }))
226 .child(div().w(px(size)).flex_none().child(avatar))
227 .child(body),
228 )
229 .when_some(menu, |block, menu| {
230 block.child(
231 div()
232 .absolute()
233 .top(px(-TOOLBAR_LIFT))
234 .right(px(8.))
235 .child(deferred(message_toolbar(menu)).with_priority(1)),
236 )
237 })
238 .when_some(scheduled_menu, |block, menu| {
239 block.child(
240 div()
241 .absolute()
242 .top(px(-TOOLBAR_LIFT))
243 .right(px(8.))
244 .child(deferred(scheduled_toolbar(menu)).with_priority(1)),
245 )
246 })
247}
248
249fn replies_link(label: String, post_index: usize, open: Option<PostAction>) -> Stateful<Div> {
250 div()
251 .id(ElementId::Name(format!("post-replies-{post_index}").into()))
252 .pl(px(CARD_PADDING + ROOT_AVATAR + AVATAR_GAP))
253 .pr(px(CARD_PADDING))
254 .pb(px(8.))
255 .text_size(px(13.))
256 .font_weight(FontWeight::SEMIBOLD)
257 .text_color(theme::accent_text())
258 .when_some(open, |link, open| {
259 link.cursor_pointer()
260 .hover(|link| link.text_color(theme::accent_soft()))
261 .on_click(move |_, window, cx| open(window, cx))
262 })
263 .child(label)
264}
265
266fn reply_footer(
267 post_index: usize,
268 open: Option<PostAction>,
269 editor: Option<AnyElement>,
270) -> Option<Div> {
271 let footer = v_flex()
272 .w_full()
273 .px(px(CARD_PADDING))
274 .py(px(8.))
275 .border_t_1()
276 .border_color(theme::border());
277 if let Some(editor) = editor {
278 return Some(footer.child(editor));
279 }
280 let open = open?;
281 Some(
282 footer.child(
283 h_flex().child(
284 h_flex()
285 .id(ElementId::Name(format!("post-reply-{post_index}").into()))
286 .gap(px(6.))
287 .px(px(6.))
288 .py(px(4.))
289 .items_center()
290 .rounded(px(6.))
291 .cursor_pointer()
292 .text_size(px(12.5))
293 .text_color(theme::text_muted())
294 .hover(|button| {
295 button
296 .bg(theme::row_hover())
297 .text_color(theme::text_strong())
298 })
299 .on_click(move |_, window, cx| open(window, cx))
300 .child(icon(IconName::Reply, 14., theme::text_muted()))
301 .child("Reply"),
302 ),
303 ),
304 )
305}
306
307pub fn render_post(
308 post: &PostRow,
309 index: usize,
310 actions: PostActions,
311 directory: &Directory,
312 cx: &App,
313) -> AnyElement {
314 let PostActions {
315 root,
316 replies,
317 open_thread,
318 open_reply,
319 reply_editor,
320 } = actions;
321 let mut card = v_flex()
322 .w_full()
323 .rounded(px(CARD_RADIUS))
324 .bg(theme::surface())
325 .border_1()
326 .border_color(theme::border())
327 .child(message_block(
328 &post.root,
329 message_index(index, 0),
330 Role::Root,
331 root,
332 directory,
333 cx,
334 ));
335 if let Some(label) = post.hidden_replies_label() {
336 card = card.child(replies_link(label, index, open_thread));
337 }
338 for (position, (reply, actions)) in post.replies.iter().zip(replies).enumerate() {
339 card = card.child(message_block(
340 reply,
341 message_index(index, position + 1),
342 Role::Reply,
343 actions,
344 directory,
345 cx,
346 ));
347 }
348 card = card.children(reply_footer(index, open_reply, reply_editor));
349 div()
350 .w_full()
351 .px(px(24.))
352 .pt(px(CARD_GAP))
353 .child(card)
354 .into_any_element()
355}
crates/app/src/views/sidebar.rs +93 −9
@@ -8,7 +8,7 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8 8 use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
9 9 use gpui_kit::prelude::FluentBuilder as _;
10 10 use gpui_kit::*;
11 use store::{ChannelRecord, SidebarTeam, TeamRecord};
11 use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};
12 12
13 13 use super::avatar::{spec_avatar, square_avatar, with_presence};
14 14 use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
@@ -24,6 +24,7 @@ use crate::sidebar_model::{
24 24 };
25 25 use crate::theme;
26 26
27 const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
27 28 pub const SIDEBAR_WIDTH: f32 = 312.;
28 29 const ROW_HEIGHT: f32 = 54.;
29 30 const PINNED_CHANNEL_HEIGHT: f32 = 48.;
@@ -257,7 +258,7 @@ fn confirm_leave(
257 258 pub struct SidebarView {
258 259 state: Entity<AppState>,
259 260 tab: SidebarTab,
260 expanded_teams: HashSet<String>,
261 collapsed_teams: HashSet<String>,
261 262 revealed_channel_teams: HashSet<String>,
262 263 hidden_teams_open: bool,
263 264 chats_scroll: ScrollHandle,
@@ -316,8 +317,11 @@ fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
316 317 impl SidebarView {
317 318 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
318 319 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
319 if matches!(event, AppEvent::Selection) && state.read(cx).new_chat {
320 this.tab = SidebarTab::Chats;
320 if matches!(event, AppEvent::Selection) {
321 if state.read(cx).new_chat {
322 this.tab = SidebarTab::Chats;
323 }
324 this.expand_team_of_selection(cx);
321 325 }
322 326 if matches!(
323 327 event,
@@ -335,10 +339,11 @@ impl SidebarView {
335 339 } else {
336 340 SidebarTab::Chats
337 341 };
342 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
338 343 SidebarView {
339 344 state,
340 345 tab,
341 expanded_teams: HashSet::new(),
346 collapsed_teams,
342 347 revealed_channel_teams: HashSet::new(),
343 348 hidden_teams_open: false,
344 349 chats_scroll: ScrollHandle::new(),
@@ -347,6 +352,29 @@ impl SidebarView {
347 352 }
348 353 }
349 354
355 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
356 let state = self.state.read(cx);
357 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
358 return;
359 };
360 let team_id = state
361 .sidebar
362 .teams
363 .iter()
364 .find(|entry| {
365 entry
366 .channels
367 .iter()
368 .any(|channel| channel.id == channel_id)
369 })
370 .map(|entry| entry.team.id.clone());
371 if let Some(team_id) = team_id
372 && self.collapsed_teams.remove(&team_id)
373 {
374 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
375 }
376 }
377
350 378 fn tab_button(
351 379 &self,
352 380 tab: SidebarTab,
@@ -935,7 +963,7 @@ impl SidebarView {
935 963 ) -> Div {
936 964 let followed = self.state.read(cx).followed_channels.clone();
937 965 let team_id = entry.team.id.clone();
938 let expanded = team_holds(entry, selected) || self.expanded_teams.contains(&team_id);
966 let expanded = team_expanded(&team_id, &self.collapsed_teams);
939 967 let unread = entry.channels.iter().any(|channel| channel.unread);
940 968 let toggle_id = team_id.clone();
941 969 list = list.child(
@@ -975,9 +1003,10 @@ impl SidebarView {
975 1003 )
976 1004 .when(unread && !expanded, |row| row.child(dot(7.)))
977 1005 .on_click(cx.listener(move |this, _, _, cx| {
978 if !this.expanded_teams.remove(&toggle_id) {
979 this.expanded_teams.insert(toggle_id.clone());
1006 if !this.collapsed_teams.remove(&toggle_id) {
1007 this.collapsed_teams.insert(toggle_id.clone());
980 1008 }
1009 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
981 1010 cx.notify();
982 1011 })),
983 1012 );
@@ -1219,6 +1248,36 @@ fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> P
1219 1248 })
1220 1249 }
1221 1250
1251 fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1252 !collapsed_teams.contains(team_id)
1253 }
1254
1255 fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1256 store
1257 .meta(COLLAPSED_TEAMS_META_KEY)
1258 .ok()
1259 .flatten()
1260 .map(|value| parse_collapsed_teams(&value))
1261 .unwrap_or_default()
1262 }
1263
1264 fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1265 let _ = store.set_meta(
1266 COLLAPSED_TEAMS_META_KEY,
1267 &serialize_collapsed_teams(collapsed_teams),
1268 );
1269 }
1270
1271 fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1272 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1273 team_ids.sort_unstable();
1274 serde_json::to_string(&team_ids).unwrap_or_default()
1275 }
1276
1277 fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1278 serde_json::from_str(value).unwrap_or_default()
1279 }
1280
1222 1281 fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1223 1282 entry
1224 1283 .channels
@@ -1282,7 +1341,32 @@ impl Render for SidebarView {
1282 1341
1283 1342 #[cfg(test)]
1284 1343 mod tests {
1285 use super::leave_description;
1344 use std::collections::HashSet;
1345
1346 use super::{
1347 leave_description, parse_collapsed_teams, serialize_collapsed_teams, team_expanded,
1348 };
1349
1350 #[test]
1351 fn teams_start_expanded() {
1352 assert!(team_expanded("t1", &HashSet::new()));
1353 }
1354
1355 #[test]
1356 fn collapsed_team_stays_closed() {
1357 let collapsed = HashSet::from(["t1".to_owned()]);
1358 assert!(!team_expanded("t1", &collapsed));
1359 assert!(team_expanded("t2", &collapsed));
1360 }
1361
1362 #[test]
1363 fn collapsed_teams_round_trip_as_json() {
1364 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1365 let json = serialize_collapsed_teams(&collapsed);
1366 assert_eq!(json, r#"["a","b"]"#);
1367 assert_eq!(parse_collapsed_teams(&json), collapsed);
1368 assert!(parse_collapsed_teams("garbage").is_empty());
1369 }
1286 1370
1287 1371 #[test]
1288 1372 fn leave_text_counts_the_other_members() {
@@ -8,7 +8,7 @@ use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
8use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
10use gpui_kit::*;
11use store::{ChannelRecord, SidebarTeam, TeamRecord};
11use store::{ChannelRecord, SidebarTeam, Store, TeamRecord};
12
12
13use super::avatar::{spec_avatar, square_avatar, with_presence};
13use super::avatar::{spec_avatar, square_avatar, with_presence};
14use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
14use super::widgets::{count_badge, dot, icon, symbol, unread_marker};
@@ -24,6 +24,7 @@ use crate::sidebar_model::{
24};
24};
25use crate::theme;
25use crate::theme;
26
26
27const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
27pub const SIDEBAR_WIDTH: f32 = 312.;
28pub const SIDEBAR_WIDTH: f32 = 312.;
28const ROW_HEIGHT: f32 = 54.;
29const ROW_HEIGHT: f32 = 54.;
29const PINNED_CHANNEL_HEIGHT: f32 = 48.;
30const PINNED_CHANNEL_HEIGHT: f32 = 48.;
@@ -257,7 +258,7 @@ fn confirm_leave(
257pub struct SidebarView {
258pub struct SidebarView {
258 state: Entity<AppState>,
259 state: Entity<AppState>,
259 tab: SidebarTab,
260 tab: SidebarTab,
260 expanded_teams: HashSet<String>,
261 collapsed_teams: HashSet<String>,
261 revealed_channel_teams: HashSet<String>,
262 revealed_channel_teams: HashSet<String>,
262 hidden_teams_open: bool,
263 hidden_teams_open: bool,
263 chats_scroll: ScrollHandle,
264 chats_scroll: ScrollHandle,
@@ -316,8 +317,11 @@ fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
316impl SidebarView {
317impl SidebarView {
317 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
318 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
318 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
319 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
319 if matches!(event, AppEvent::Selection) && state.read(cx).new_chat {
320 if matches!(event, AppEvent::Selection) {
320 this.tab = SidebarTab::Chats;
321 if state.read(cx).new_chat {
322 this.tab = SidebarTab::Chats;
323 }
324 this.expand_team_of_selection(cx);
321 }
325 }
322 if matches!(
326 if matches!(
323 event,
327 event,
@@ -335,10 +339,11 @@ impl SidebarView {
335 } else {
339 } else {
336 SidebarTab::Chats
340 SidebarTab::Chats
337 };
341 };
342 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
338 SidebarView {
343 SidebarView {
339 state,
344 state,
340 tab,
345 tab,
341 expanded_teams: HashSet::new(),
346 collapsed_teams,
342 revealed_channel_teams: HashSet::new(),
347 revealed_channel_teams: HashSet::new(),
343 hidden_teams_open: false,
348 hidden_teams_open: false,
344 chats_scroll: ScrollHandle::new(),
349 chats_scroll: ScrollHandle::new(),
@@ -347,6 +352,29 @@ impl SidebarView {
347 }
352 }
348 }
353 }
349
354
355 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
356 let state = self.state.read(cx);
357 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
358 return;
359 };
360 let team_id = state
361 .sidebar
362 .teams
363 .iter()
364 .find(|entry| {
365 entry
366 .channels
367 .iter()
368 .any(|channel| channel.id == channel_id)
369 })
370 .map(|entry| entry.team.id.clone());
371 if let Some(team_id) = team_id
372 && self.collapsed_teams.remove(&team_id)
373 {
374 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
375 }
376 }
377
350 fn tab_button(
378 fn tab_button(
351 &self,
379 &self,
352 tab: SidebarTab,
380 tab: SidebarTab,
@@ -935,7 +963,7 @@ impl SidebarView {
935 ) -> Div {
963 ) -> Div {
936 let followed = self.state.read(cx).followed_channels.clone();
964 let followed = self.state.read(cx).followed_channels.clone();
937 let team_id = entry.team.id.clone();
965 let team_id = entry.team.id.clone();
938 let expanded = team_holds(entry, selected) || self.expanded_teams.contains(&team_id);
966 let expanded = team_expanded(&team_id, &self.collapsed_teams);
939 let unread = entry.channels.iter().any(|channel| channel.unread);
967 let unread = entry.channels.iter().any(|channel| channel.unread);
940 let toggle_id = team_id.clone();
968 let toggle_id = team_id.clone();
941 list = list.child(
969 list = list.child(
@@ -975,9 +1003,10 @@ impl SidebarView {
975 )
1003 )
976 .when(unread && !expanded, |row| row.child(dot(7.)))
1004 .when(unread && !expanded, |row| row.child(dot(7.)))
977 .on_click(cx.listener(move |this, _, _, cx| {
1005 .on_click(cx.listener(move |this, _, _, cx| {
978 if !this.expanded_teams.remove(&toggle_id) {
1006 if !this.collapsed_teams.remove(&toggle_id) {
979 this.expanded_teams.insert(toggle_id.clone());
1007 this.collapsed_teams.insert(toggle_id.clone());
980 }
1008 }
1009 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
981 cx.notify();
1010 cx.notify();
982 })),
1011 })),
983 );
1012 );
@@ -1219,6 +1248,36 @@ fn follow_item(state: Entity<AppState>, channel_id: String, followed: bool) -> P
1219 })
1248 })
1220}
1249}
1221
1250
1251fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1252 !collapsed_teams.contains(team_id)
1253}
1254
1255fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1256 store
1257 .meta(COLLAPSED_TEAMS_META_KEY)
1258 .ok()
1259 .flatten()
1260 .map(|value| parse_collapsed_teams(&value))
1261 .unwrap_or_default()
1262}
1263
1264fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1265 let _ = store.set_meta(
1266 COLLAPSED_TEAMS_META_KEY,
1267 &serialize_collapsed_teams(collapsed_teams),
1268 );
1269}
1270
1271fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1272 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1273 team_ids.sort_unstable();
1274 serde_json::to_string(&team_ids).unwrap_or_default()
1275}
1276
1277fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1278 serde_json::from_str(value).unwrap_or_default()
1279}
1280
1222fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1281fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1223 entry
1282 entry
1224 .channels
1283 .channels
@@ -1282,7 +1341,32 @@ impl Render for SidebarView {
1282
1341
1283#[cfg(test)]
1342#[cfg(test)]
1284mod tests {
1343mod tests {
1285 use super::leave_description;
1344 use std::collections::HashSet;
1345
1346 use super::{
1347 leave_description, parse_collapsed_teams, serialize_collapsed_teams, team_expanded,
1348 };
1349
1350 #[test]
1351 fn teams_start_expanded() {
1352 assert!(team_expanded("t1", &HashSet::new()));
1353 }
1354
1355 #[test]
1356 fn collapsed_team_stays_closed() {
1357 let collapsed = HashSet::from(["t1".to_owned()]);
1358 assert!(!team_expanded("t1", &collapsed));
1359 assert!(team_expanded("t2", &collapsed));
1360 }
1361
1362 #[test]
1363 fn collapsed_teams_round_trip_as_json() {
1364 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1365 let json = serialize_collapsed_teams(&collapsed);
1366 assert_eq!(json, r#"["a","b"]"#);
1367 assert_eq!(parse_collapsed_teams(&json), collapsed);
1368 assert!(parse_collapsed_teams("garbage").is_empty());
1369 }
1286
1370
1287 #[test]
1371 #[test]
1288 fn leave_text_counts_the_other_members() {
1372 fn leave_text_counts_the_other_members() {
crates/core/src/channel_sync.rs +21 −0
@@ -180,6 +180,27 @@ impl<R: Remote> SyncEngine<R> {
180 180 Ok(records)
181 181 }
182 182
183 pub(crate) async fn refresh_channel_thread(
184 &self,
185 team_id: &str,
186 channel_id: &str,
187 root_id: &str,
188 ) -> Result<Delta> {
189 let listings = self
190 .remote
191 .channel_replies(team_id, channel_id, &[root_id.to_owned()])
192 .await?;
193 let mut records = Vec::new();
194 for listing in listings {
195 records.extend(
196 listing?
197 .iter()
198 .filter_map(|reply| message_record(channel_id, reply)),
199 );
200 }
201 self.ingest(channel_id, records)
202 }
203
183 204 pub(crate) async fn load_older_channel(
184 205 &self,
185 206 channel_id: &str,
@@ -180,6 +180,27 @@ impl<R: Remote> SyncEngine<R> {
180 Ok(records)
180 Ok(records)
181 }
181 }
182
182
183 pub(crate) async fn refresh_channel_thread(
184 &self,
185 team_id: &str,
186 channel_id: &str,
187 root_id: &str,
188 ) -> Result<Delta> {
189 let listings = self
190 .remote
191 .channel_replies(team_id, channel_id, &[root_id.to_owned()])
192 .await?;
193 let mut records = Vec::new();
194 for listing in listings {
195 records.extend(
196 listing?
197 .iter()
198 .filter_map(|reply| message_record(channel_id, reply)),
199 );
200 }
201 self.ingest(channel_id, records)
202 }
203
183 pub(crate) async fn load_older_channel(
204 pub(crate) async fn load_older_channel(
184 &self,
205 &self,
185 channel_id: &str,
206 channel_id: &str,
crates/core/src/engine.rs +11 −0
@@ -195,6 +195,17 @@ impl<R: Remote> SyncEngine<R> {
195 195 Ok(delta)
196 196 }
197 197
198 pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
199 let Conversation::Channel { team_id } = self.resolve(conversation_id)? else {
200 return Err(Error::Unsupported("refreshing a thread of a chat"));
201 };
202 let delta = self
203 .refresh_channel_thread(&team_id, conversation_id, root_id)
204 .await?;
205 self.announce(conversation_id, !delta.is_empty());
206 Ok(delta)
207 }
208
198 209 pub async fn load_older(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> {
199 210 let conversation = self.resolve(conversation_id)?;
200 211 if self.store.sync_state(conversation_id)?.is_none() {
@@ -195,6 +195,17 @@ impl<R: Remote> SyncEngine<R> {
195 Ok(delta)
195 Ok(delta)
196 }
196 }
197
197
198 pub async fn refresh_thread(&self, conversation_id: &str, root_id: &str) -> Result<Delta> {
199 let Conversation::Channel { team_id } = self.resolve(conversation_id)? else {
200 return Err(Error::Unsupported("refreshing a thread of a chat"));
201 };
202 let delta = self
203 .refresh_channel_thread(&team_id, conversation_id, root_id)
204 .await?;
205 self.announce(conversation_id, !delta.is_empty());
206 Ok(delta)
207 }
208
198 pub async fn load_older(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> {
209 pub async fn load_older(&self, conversation_id: &str) -> Result<Vec<MessageRecord>> {
199 let conversation = self.resolve(conversation_id)?;
210 let conversation = self.resolve(conversation_id)?;
200 if self.store.sync_state(conversation_id)?.is_none() {
211 if self.store.sync_state(conversation_id)?.is_none() {
crates/core/src/mapping.rs +26 −0
@@ -167,6 +167,12 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
167 167 .collect::<Vec<_>>(),
168 168 ),
169 169 links_json: EMPTY_LINKS.to_owned(),
170 subject: message
171 .subject
172 .as_deref()
173 .map(str::trim)
174 .filter(|subject| !subject.is_empty())
175 .map(str::to_owned),
170 176 })
171 177 }
172 178
@@ -326,6 +332,26 @@ mod tests {
326 332 assert!(!record.last_event_system);
327 333 }
328 334
335 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
336 let message: Message = serde_json::from_value(json!({
337 "id": "1",
338 "createdDateTime": "2026-10-06T09:00:00Z",
339 "subject": subject,
340 }))
341 .unwrap();
342 message_record("c", &message).unwrap().subject
343 }
344
345 #[test]
346 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
347 assert_eq!(
348 record_with_subject(json!(" Release plan ")).as_deref(),
349 Some("Release plan")
350 );
351 assert_eq!(record_with_subject(json!(" ")), None);
352 assert_eq!(record_with_subject(json!(null)), None);
353 }
354
329 355 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
330 356 let message: Message = serde_json::from_value(json!({
331 357 "id": "1",
@@ -167,6 +167,12 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
167 .collect::<Vec<_>>(),
167 .collect::<Vec<_>>(),
168 ),
168 ),
169 links_json: EMPTY_LINKS.to_owned(),
169 links_json: EMPTY_LINKS.to_owned(),
170 subject: message
171 .subject
172 .as_deref()
173 .map(str::trim)
174 .filter(|subject| !subject.is_empty())
175 .map(str::to_owned),
170 })
176 })
171}
177}
172
178
@@ -326,6 +332,26 @@ mod tests {
326 assert!(!record.last_event_system);
332 assert!(!record.last_event_system);
327 }
333 }
328
334
335 fn record_with_subject(subject: serde_json::Value) -> Option<String> {
336 let message: Message = serde_json::from_value(json!({
337 "id": "1",
338 "createdDateTime": "2026-10-06T09:00:00Z",
339 "subject": subject,
340 }))
341 .unwrap();
342 message_record("c", &message).unwrap().subject
343 }
344
345 #[test]
346 fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
347 assert_eq!(
348 record_with_subject(json!(" Release plan ")).as_deref(),
349 Some("Release plan")
350 );
351 assert_eq!(record_with_subject(json!(" ")), None);
352 assert_eq!(record_with_subject(json!(null)), None);
353 }
354
329 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
355 fn mentions_of(mentioned: serde_json::Value) -> Vec<MentionInfo> {
330 let message: Message = serde_json::from_value(json!({
356 let message: Message = serde_json::from_value(json!({
331 "id": "1",
357 "id": "1",
crates/core/src/stored.rs +1 −0
@@ -591,6 +591,7 @@ mod tests {
591 591
592 592 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
593 593 MessageRecord {
594 subject: None,
594 595 conversation_id: "c".to_owned(),
595 596 message_id: "m".to_owned(),
596 597 reply_to_id: None,
@@ -591,6 +591,7 @@ mod tests {
591
591
592 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
592 fn record(body_html: &str, attachments_json: &str) -> MessageRecord {
593 MessageRecord {
593 MessageRecord {
594 subject: None,
594 conversation_id: "c".to_owned(),
595 conversation_id: "c".to_owned(),
595 message_id: "m".to_owned(),
596 message_id: "m".to_owned(),
596 reply_to_id: None,
597 reply_to_id: None,
crates/core/tests/engine.rs +36 −1
@@ -78,6 +78,7 @@ struct Fake {
78 78 team_calls: Mutex<usize>,
79 79 calls: Mutex<Vec<String>>,
80 80 delta_items: Mutex<Vec<Message>>,
81 thread_replies: Mutex<Vec<Message>>,
81 82 delta_fails: Mutex<bool>,
82 83 photos: Mutex<HashMap<String, Vec<u8>>>,
83 84 photo_requests: Mutex<Vec<Vec<String>>>,
@@ -342,7 +343,17 @@ impl Remote for Handle {
342 343 _channel_id: &str,
343 344 root_ids: &[String],
344 345 ) -> Result<Vec<Result<Vec<Message>>>> {
345 Ok(root_ids.iter().map(|_| Ok(Vec::new())).collect())
346 let replies = self.thread_replies.lock().unwrap().clone();
347 Ok(root_ids
348 .iter()
349 .map(|root_id| {
350 Ok(replies
351 .iter()
352 .filter(|reply| reply.reply_to_id.as_deref() == Some(root_id.as_str()))
353 .cloned()
354 .collect())
355 })
356 .collect())
346 357 }
347 358
348 359 async fn send_chat_message(
@@ -1238,6 +1249,30 @@ async fn channel_engine(fake: &Arc<Fake>) -> SyncEngine<Handle> {
1238 1249 engine
1239 1250 }
1240 1251
1252 #[tokio::test]
1253 async fn refreshing_a_thread_stores_every_reply_of_that_root() {
1254 let fake = Arc::new(Fake::default());
1255 let engine = channel_engine(&fake).await;
1256 engine.fetch_newer(CHANNEL).await.unwrap();
1257 let root_id = engine.open_conversation(CHANNEL).unwrap()[0]
1258 .message_id
1259 .clone();
1260 let reply = |id: u32, minute: i64, root: &str| -> Message {
1261 let mut reply = message(id, minute, &format!("<p>reply {id}</p>"));
1262 reply.reply_to_id = Some(root.to_owned());
1263 reply
1264 };
1265 *fake.thread_replies.lock().unwrap() = vec![
1266 reply(7001, 90, &root_id),
1267 reply(7002, 91, &root_id),
1268 reply(7003, 92, "other-root"),
1269 ];
1270 let delta = engine.refresh_thread(CHANNEL, &root_id).await.unwrap();
1271 assert_eq!(delta.added.len(), 2);
1272 let thread = engine.store().thread_messages(CHANNEL, &root_id).unwrap();
1273 assert_eq!(thread.len(), 4);
1274 }
1275
1241 1276 #[tokio::test]
1242 1277 async fn channel_delta_picks_up_new_and_edited_posts_and_stores_the_link() {
1243 1278 let fake = Arc::new(Fake::default());
@@ -78,6 +78,7 @@ struct Fake {
78 team_calls: Mutex<usize>,
78 team_calls: Mutex<usize>,
79 calls: Mutex<Vec<String>>,
79 calls: Mutex<Vec<String>>,
80 delta_items: Mutex<Vec<Message>>,
80 delta_items: Mutex<Vec<Message>>,
81 thread_replies: Mutex<Vec<Message>>,
81 delta_fails: Mutex<bool>,
82 delta_fails: Mutex<bool>,
82 photos: Mutex<HashMap<String, Vec<u8>>>,
83 photos: Mutex<HashMap<String, Vec<u8>>>,
83 photo_requests: Mutex<Vec<Vec<String>>>,
84 photo_requests: Mutex<Vec<Vec<String>>>,
@@ -342,7 +343,17 @@ impl Remote for Handle {
342 _channel_id: &str,
343 _channel_id: &str,
343 root_ids: &[String],
344 root_ids: &[String],
344 ) -> Result<Vec<Result<Vec<Message>>>> {
345 ) -> Result<Vec<Result<Vec<Message>>>> {
345 Ok(root_ids.iter().map(|_| Ok(Vec::new())).collect())
346 let replies = self.thread_replies.lock().unwrap().clone();
347 Ok(root_ids
348 .iter()
349 .map(|root_id| {
350 Ok(replies
351 .iter()
352 .filter(|reply| reply.reply_to_id.as_deref() == Some(root_id.as_str()))
353 .cloned()
354 .collect())
355 })
356 .collect())
346 }
357 }
347
358
348 async fn send_chat_message(
359 async fn send_chat_message(
@@ -1238,6 +1249,30 @@ async fn channel_engine(fake: &Arc<Fake>) -> SyncEngine<Handle> {
1238 engine
1249 engine
1239}
1250}
1240
1251
1252#[tokio::test]
1253async fn refreshing_a_thread_stores_every_reply_of_that_root() {
1254 let fake = Arc::new(Fake::default());
1255 let engine = channel_engine(&fake).await;
1256 engine.fetch_newer(CHANNEL).await.unwrap();
1257 let root_id = engine.open_conversation(CHANNEL).unwrap()[0]
1258 .message_id
1259 .clone();
1260 let reply = |id: u32, minute: i64, root: &str| -> Message {
1261 let mut reply = message(id, minute, &format!("<p>reply {id}</p>"));
1262 reply.reply_to_id = Some(root.to_owned());
1263 reply
1264 };
1265 *fake.thread_replies.lock().unwrap() = vec![
1266 reply(7001, 90, &root_id),
1267 reply(7002, 91, &root_id),
1268 reply(7003, 92, "other-root"),
1269 ];
1270 let delta = engine.refresh_thread(CHANNEL, &root_id).await.unwrap();
1271 assert_eq!(delta.added.len(), 2);
1272 let thread = engine.store().thread_messages(CHANNEL, &root_id).unwrap();
1273 assert_eq!(thread.len(), 4);
1274}
1275
1241#[tokio::test]
1276#[tokio::test]
1242async fn channel_delta_picks_up_new_and_edited_posts_and_stores_the_link() {
1277async fn channel_delta_picks_up_new_and_edited_posts_and_stores_the_link() {
1243 let fake = Arc::new(Fake::default());
1278 let fake = Arc::new(Fake::default());
crates/core/tests/spans.rs +1 −0
@@ -358,6 +358,7 @@ fn card_text_lists_texts_and_facts_in_document_order() {
358 358
359 359 fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
360 360 MessageRecord {
361 subject: None,
361 362 conversation_id: "c".to_owned(),
362 363 message_id: "m".to_owned(),
363 364 reply_to_id: None,
@@ -358,6 +358,7 @@ fn card_text_lists_texts_and_facts_in_document_order() {
358
358
359fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
359fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
360 MessageRecord {
360 MessageRecord {
361 subject: None,
361 conversation_id: "c".to_owned(),
362 conversation_id: "c".to_owned(),
362 message_id: "m".to_owned(),
363 message_id: "m".to_owned(),
363 reply_to_id: None,
364 reply_to_id: None,
crates/store/src/messages.rs +23 −2
@@ -10,7 +10,7 @@ use crate::store::Store;
10 10 use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11 11
12 12 const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject";
14 14
15 15 impl Store {
16 16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,7 +19,7 @@ impl Store {
19 19 {
20 20 let mut upsert = transaction.prepare_cached(&format!(
21 21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
23 23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 25 sender_name = excluded.sender_name, created_at = excluded.created_at,
@@ -27,6 +27,7 @@ impl Store {
27 27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28 28 mentions_json = excluded.mentions_json,
29 29 sender_application_id = excluded.sender_application_id,
30 subject = COALESCE(excluded.subject, messages.subject),
30 31 links_json = CASE WHEN excluded.links_json IN ('', '[]')
31 32 THEN messages.links_json ELSE excluded.links_json END"
32 33 ))?;
@@ -46,6 +47,7 @@ impl Store {
46 47 message.mentions_json,
47 48 message.sender_application_id,
48 49 message.links_json,
50 message.subject,
49 51 ])?;
50 52 index_message(&transaction, message)?;
51 53 }
@@ -135,6 +137,24 @@ impl Store {
135 137 Ok(messages)
136 138 }
137 139
140 /// Oldest-first root and replies of one channel thread.
141 pub fn thread_messages(
142 &self,
143 conversation_id: &str,
144 root_id: &str,
145 ) -> Result<Vec<MessageRecord>> {
146 let connection = self.lock()?;
147 let mut statement = connection.prepare_cached(&format!(
148 "SELECT {MESSAGE_COLUMNS} FROM messages
149 WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(params![conversation_id, root_id], message_from_row)?
154 .collect::<rusqlite::Result<Vec<_>>>()?;
155 Ok(messages)
156 }
157
138 158 pub fn messages_by_id(
139 159 &self,
140 160 conversation_id: &str,
@@ -229,5 +249,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
229 249 mentions_json: row.get(11)?,
230 250 sender_application_id: row.get(12)?,
231 251 links_json: row.get(13)?,
252 subject: row.get(14)?,
232 253 })
233 254 }
@@ -10,7 +10,7 @@ use crate::store::Store;
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
10use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
12const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";
13 edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject";
14
14
15impl Store {
15impl Store {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
16 pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,7 +19,7 @@ impl Store {
19 {
19 {
20 let mut upsert = transaction.prepare_cached(&format!(
20 let mut upsert = transaction.prepare_cached(&format!(
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
21 "INSERT INTO messages ({MESSAGE_COLUMNS})
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
22 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
23 ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
24 reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
25 sender_name = excluded.sender_name, created_at = excluded.created_at,
@@ -27,6 +27,7 @@ impl Store {
27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
27 attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28 mentions_json = excluded.mentions_json,
28 mentions_json = excluded.mentions_json,
29 sender_application_id = excluded.sender_application_id,
29 sender_application_id = excluded.sender_application_id,
30 subject = COALESCE(excluded.subject, messages.subject),
30 links_json = CASE WHEN excluded.links_json IN ('', '[]')
31 links_json = CASE WHEN excluded.links_json IN ('', '[]')
31 THEN messages.links_json ELSE excluded.links_json END"
32 THEN messages.links_json ELSE excluded.links_json END"
32 ))?;
33 ))?;
@@ -46,6 +47,7 @@ impl Store {
46 message.mentions_json,
47 message.mentions_json,
47 message.sender_application_id,
48 message.sender_application_id,
48 message.links_json,
49 message.links_json,
50 message.subject,
49 ])?;
51 ])?;
50 index_message(&transaction, message)?;
52 index_message(&transaction, message)?;
51 }
53 }
@@ -135,6 +137,24 @@ impl Store {
135 Ok(messages)
137 Ok(messages)
136 }
138 }
137
139
140 /// Oldest-first root and replies of one channel thread.
141 pub fn thread_messages(
142 &self,
143 conversation_id: &str,
144 root_id: &str,
145 ) -> Result<Vec<MessageRecord>> {
146 let connection = self.lock()?;
147 let mut statement = connection.prepare_cached(&format!(
148 "SELECT {MESSAGE_COLUMNS} FROM messages
149 WHERE conversation_id = ?1 AND (message_id = ?2 OR reply_to_id = ?2)
150 ORDER BY created_at ASC, message_id ASC"
151 ))?;
152 let messages = statement
153 .query_map(params![conversation_id, root_id], message_from_row)?
154 .collect::<rusqlite::Result<Vec<_>>>()?;
155 Ok(messages)
156 }
157
138 pub fn messages_by_id(
158 pub fn messages_by_id(
139 &self,
159 &self,
140 conversation_id: &str,
160 conversation_id: &str,
@@ -229,5 +249,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
229 mentions_json: row.get(11)?,
249 mentions_json: row.get(11)?,
230 sender_application_id: row.get(12)?,
250 sender_application_id: row.get(12)?,
231 links_json: row.get(13)?,
251 links_json: row.get(13)?,
252 subject: row.get(14)?,
232 })
253 })
233}
254}
crates/store/src/migrations.rs +4 −0
@@ -57,6 +57,10 @@ const MIGRATIONS: &[Migration] = &[
57 57 script: include_str!("migrations/0012_outbox_drafts.sql"),
58 58 after: None,
59 59 },
60 Migration {
61 script: include_str!("migrations/0013_message_subject.sql"),
62 after: None,
63 },
60 64 ];
61 65
62 66 pub fn latest_version() -> i64 {
@@ -57,6 +57,10 @@ const MIGRATIONS: &[Migration] = &[
57 script: include_str!("migrations/0012_outbox_drafts.sql"),
57 script: include_str!("migrations/0012_outbox_drafts.sql"),
58 after: None,
58 after: None,
59 },
59 },
60 Migration {
61 script: include_str!("migrations/0013_message_subject.sql"),
62 after: None,
63 },
60];
64];
61
65
62pub fn latest_version() -> i64 {
66pub fn latest_version() -> i64 {
crates/store/src/migrations/0013_message_subject.sql added +3 −0
@@ -0,0 +1,3 @@
1 ALTER TABLE messages ADD COLUMN subject TEXT;
2
3 UPDATE sync_state SET delta_link = NULL WHERE conversation_id IN (SELECT id FROM channels);
@@ -0,0 +1,3 @@
1ALTER TABLE messages ADD COLUMN subject TEXT;
2
3UPDATE sync_state SET delta_link = NULL WHERE conversation_id IN (SELECT id FROM channels);
crates/store/src/models.rs +1 −0
@@ -72,6 +72,7 @@ pub struct MessageRecord {
72 72 pub mentions_json: String,
73 73 pub sender_application_id: Option<String>,
74 74 pub links_json: String,
75 pub subject: Option<String>,
75 76 }
76 77
77 78 #[derive(Debug, Clone, PartialEq)]
@@ -72,6 +72,7 @@ pub struct MessageRecord {
72 pub mentions_json: String,
72 pub mentions_json: String,
73 pub sender_application_id: Option<String>,
73 pub sender_application_id: Option<String>,
74 pub links_json: String,
74 pub links_json: String,
75 pub subject: Option<String>,
75}
76}
76
77
77#[derive(Debug, Clone, PartialEq)]
78#[derive(Debug, Clone, PartialEq)]
crates/store/tests/store.rs +68 −4
@@ -65,9 +65,46 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
65 65 mentions_json: "[]".to_owned(),
66 66 sender_application_id: None,
67 67 links_json: "[]".to_owned(),
68 subject: None,
68 69 }
69 70 }
70 71
72 #[test]
73 fn subject_round_trips_and_survives_an_upsert_without_one() {
74 let store = Store::open_in_memory().unwrap();
75 let post = MessageRecord {
76 subject: Some("Release plan".to_owned()),
77 ..message("c1", "m1", 1)
78 };
79 store.upsert_messages(std::slice::from_ref(&post)).unwrap();
80 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
81 assert_eq!(found["m1"], post);
82
83 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
84 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
85 assert_eq!(found["m1"].subject.as_deref(), Some("Release plan"));
86 }
87
88 #[test]
89 fn thread_messages_return_root_and_replies_oldest_first_beyond_any_page() {
90 let store = Store::open_in_memory().unwrap();
91 let reply = |id: &str, minute: u32, root: &str| MessageRecord {
92 reply_to_id: Some(root.to_owned()),
93 ..message("c1", id, minute)
94 };
95 store
96 .upsert_messages(&[
97 reply("r2", 30, "root"),
98 message("c1", "root", 1),
99 message("c1", "other", 2),
100 reply("r1", 10, "root"),
101 reply("o1", 11, "other"),
102 ])
103 .unwrap();
104 let thread = store.thread_messages("c1", "root").unwrap();
105 assert_eq!(ids(&thread), ["root", "r1", "r2"]);
106 }
107
71 108 #[test]
72 109 fn sender_application_round_trips() {
73 110 let store = Store::open_in_memory().unwrap();
@@ -430,11 +467,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
430 467 let path = directory.path().join("nested").join("cache.sqlite3");
431 468 {
432 469 let store = Store::open(&path).unwrap();
433 assert_eq!(store.schema_version().unwrap(), 12);
470 assert_eq!(store.schema_version().unwrap(), 13);
434 471 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
435 472 }
436 473 let reopened = Store::open(&path).unwrap();
437 assert_eq!(reopened.schema_version().unwrap(), 12);
474 assert_eq!(reopened.schema_version().unwrap(), 13);
438 475 assert_eq!(reopened.message_count("c").unwrap(), 1);
439 476 drop(reopened);
440 477 let mode: String = rusqlite_open(&path)
@@ -466,7 +503,7 @@ fn old_schema_is_upgraded_in_place() {
466 503 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
467 504 drop(connection);
468 505 let store = Store::open(&path).unwrap();
469 assert_eq!(store.schema_version().unwrap(), 12);
506 assert_eq!(store.schema_version().unwrap(), 13);
470 507 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
471 508 }
472 509
@@ -532,7 +569,33 @@ fn migration_to_v2_keeps_existing_sync_state() {
532 569 let store = Store::open(&path).unwrap();
533 570 let state = store.sync_state("c").unwrap().unwrap();
534 571 assert_eq!(state.delta_link, None);
535 assert_eq!(store.schema_version().unwrap(), 12);
572 assert_eq!(store.schema_version().unwrap(), 13);
573 }
574
575 #[test]
576 fn migration_to_v13_clears_channel_delta_links_only() {
577 let directory = tempfile::tempdir().unwrap();
578 let path = directory.path().join("old.sqlite3");
579 {
580 let store = Store::open(&path).unwrap();
581 drop(store);
582 let connection = Connection::open(&path).unwrap();
583 connection
584 .execute_batch(
585 "INSERT INTO teams (id, name) VALUES ('t', 'T');
586 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
587 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
588 ALTER TABLE messages DROP COLUMN subject;
589 PRAGMA user_version = 12",
590 )
591 .unwrap();
592 }
593 let store = Store::open(&path).unwrap();
594 assert_eq!(store.sync_state("ch").unwrap().unwrap().delta_link, None);
595 assert_eq!(
596 store.sync_state("chat").unwrap().unwrap().delta_link.as_deref(),
597 Some("link")
598 );
536 599 }
537 600
538 601 #[test]
@@ -766,6 +829,7 @@ fn migration_indexes_rows_that_predate_search() {
766 829 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
767 830 ALTER TABLE messages DROP COLUMN sender_application_id;
768 831 ALTER TABLE messages DROP COLUMN links_json;
832 ALTER TABLE messages DROP COLUMN subject;
769 833 ALTER TABLE chats DROP COLUMN muted;
770 834 PRAGMA user_version = 3;",
771 835 )
@@ -65,9 +65,46 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
65 mentions_json: "[]".to_owned(),
65 mentions_json: "[]".to_owned(),
66 sender_application_id: None,
66 sender_application_id: None,
67 links_json: "[]".to_owned(),
67 links_json: "[]".to_owned(),
68 subject: None,
68 }
69 }
69}
70}
70
71
72#[test]
73fn subject_round_trips_and_survives_an_upsert_without_one() {
74 let store = Store::open_in_memory().unwrap();
75 let post = MessageRecord {
76 subject: Some("Release plan".to_owned()),
77 ..message("c1", "m1", 1)
78 };
79 store.upsert_messages(std::slice::from_ref(&post)).unwrap();
80 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
81 assert_eq!(found["m1"], post);
82
83 store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
84 let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
85 assert_eq!(found["m1"].subject.as_deref(), Some("Release plan"));
86}
87
88#[test]
89fn thread_messages_return_root_and_replies_oldest_first_beyond_any_page() {
90 let store = Store::open_in_memory().unwrap();
91 let reply = |id: &str, minute: u32, root: &str| MessageRecord {
92 reply_to_id: Some(root.to_owned()),
93 ..message("c1", id, minute)
94 };
95 store
96 .upsert_messages(&[
97 reply("r2", 30, "root"),
98 message("c1", "root", 1),
99 message("c1", "other", 2),
100 reply("r1", 10, "root"),
101 reply("o1", 11, "other"),
102 ])
103 .unwrap();
104 let thread = store.thread_messages("c1", "root").unwrap();
105 assert_eq!(ids(&thread), ["root", "r1", "r2"]);
106}
107
71#[test]
108#[test]
72fn sender_application_round_trips() {
109fn sender_application_round_trips() {
73 let store = Store::open_in_memory().unwrap();
110 let store = Store::open_in_memory().unwrap();
@@ -430,11 +467,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
430 let path = directory.path().join("nested").join("cache.sqlite3");
467 let path = directory.path().join("nested").join("cache.sqlite3");
431 {
468 {
432 let store = Store::open(&path).unwrap();
469 let store = Store::open(&path).unwrap();
433 assert_eq!(store.schema_version().unwrap(), 12);
470 assert_eq!(store.schema_version().unwrap(), 13);
434 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
471 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
435 }
472 }
436 let reopened = Store::open(&path).unwrap();
473 let reopened = Store::open(&path).unwrap();
437 assert_eq!(reopened.schema_version().unwrap(), 12);
474 assert_eq!(reopened.schema_version().unwrap(), 13);
438 assert_eq!(reopened.message_count("c").unwrap(), 1);
475 assert_eq!(reopened.message_count("c").unwrap(), 1);
439 drop(reopened);
476 drop(reopened);
440 let mode: String = rusqlite_open(&path)
477 let mode: String = rusqlite_open(&path)
@@ -466,7 +503,7 @@ fn old_schema_is_upgraded_in_place() {
466 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
503 connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; PRAGMA user_version = 0").unwrap();
467 drop(connection);
504 drop(connection);
468 let store = Store::open(&path).unwrap();
505 let store = Store::open(&path).unwrap();
469 assert_eq!(store.schema_version().unwrap(), 12);
506 assert_eq!(store.schema_version().unwrap(), 13);
470 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
507 store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
471}
508}
472
509
@@ -532,7 +569,33 @@ fn migration_to_v2_keeps_existing_sync_state() {
532 let store = Store::open(&path).unwrap();
569 let store = Store::open(&path).unwrap();
533 let state = store.sync_state("c").unwrap().unwrap();
570 let state = store.sync_state("c").unwrap().unwrap();
534 assert_eq!(state.delta_link, None);
571 assert_eq!(state.delta_link, None);
535 assert_eq!(store.schema_version().unwrap(), 12);
572 assert_eq!(store.schema_version().unwrap(), 13);
573}
574
575#[test]
576fn migration_to_v13_clears_channel_delta_links_only() {
577 let directory = tempfile::tempdir().unwrap();
578 let path = directory.path().join("old.sqlite3");
579 {
580 let store = Store::open(&path).unwrap();
581 drop(store);
582 let connection = Connection::open(&path).unwrap();
583 connection
584 .execute_batch(
585 "INSERT INTO teams (id, name) VALUES ('t', 'T');
586 INSERT INTO channels (id, team_id, name) VALUES ('ch', 't', 'C');
587 INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
588 ALTER TABLE messages DROP COLUMN subject;
589 PRAGMA user_version = 12",
590 )
591 .unwrap();
592 }
593 let store = Store::open(&path).unwrap();
594 assert_eq!(store.sync_state("ch").unwrap().unwrap().delta_link, None);
595 assert_eq!(
596 store.sync_state("chat").unwrap().unwrap().delta_link.as_deref(),
597 Some("link")
598 );
536}
599}
537
600
538#[test]
601#[test]
@@ -766,6 +829,7 @@ fn migration_indexes_rows_that_predate_search() {
766 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
829 DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
767 ALTER TABLE messages DROP COLUMN sender_application_id;
830 ALTER TABLE messages DROP COLUMN sender_application_id;
768 ALTER TABLE messages DROP COLUMN links_json;
831 ALTER TABLE messages DROP COLUMN links_json;
832 ALTER TABLE messages DROP COLUMN subject;
769 ALTER TABLE chats DROP COLUMN muted;
833 ALTER TABLE chats DROP COLUMN muted;
770 PRAGMA user_version = 3;",
834 PRAGMA user_version = 3;",
771 )
835 )