feat(chat): message actions - forward, copy link, save, pin, mark unread from here
| Before | After | |---|---| | More menu: reply, copy text, edit, delete | Adds Forward, Copy link, Save/Unsave, Pin/Unpin, Mark as unread | | No forward | Dialog with chat and channel search, preview, optional comment; "Forwarded" header on received forwards | | No saved list | Bookmark mark on saved messages, Saved panel next to the bell, synced with Teams 48:saved | | No pinned messages | Pin banner under the chat header, cycles several pins, unpin from the banner, live via PinsChanged | - Forward: chatsvc messages/forward. Save: chatsvc rcmetadata. Pins: CSA pinbar (Graph pinnedMessages returns 403). - Copy link builds the Teams deep link locally. - Demo mode seeds a pin, two saved messages and a forwarded message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -7980,6 +7980,7 @@ dependencies = [
7980
7980
"chrono",
7981
7981
"futures-util",
7982
7982
"graph",
7983
"percent-encoding",
7983
7984
"regex",
7984
7985
"scraper",
7985
7986
"serde",
@@ -7980,6 +7980,7 @@ dependencies = [7980
"chrono",7980
"chrono",7981
"futures-util",7981
"futures-util",7982
"graph",7982
"graph",7983
"percent-encoding",7983
"regex",7984
"regex",7984
"scraper",7985
"scraper",7985
"serde",7986
"serde",@@ -41,6 +41,7 @@
41
41
42
42
**Messages**
43
43
- Send, edit, delete, react, quote-reply, @mentions
44
- Forward, copy link, save (Saved panel), pin to the chat banner, mark unread from here
44
45
- Inline images, file cards, link previews
45
46
- Adaptive Cards: layout, links, images, buttons, inputs, task dialogs
46
47
- GIFs and stickers in messages
@@ -41,6 +41,7 @@41
41
42
**Messages**42
**Messages**43
- Send, edit, delete, react, quote-reply, @mentions43
- Send, edit, delete, react, quote-reply, @mentions44
- Forward, copy link, save (Saved panel), pin to the chat banner, mark unread from here44
- Inline images, file cards, link previews45
- Inline images, file cards, link previews45
- Adaptive Cards: layout, links, images, buttons, inputs, task dialogs46
- Adaptive Cards: layout, links, images, buttons, inputs, task dialogs46
- GIFs and stickers in messages47
- GIFs and stickers in messages@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 74 %** (63 done, 2 partial, 21 missing of 86). Partial counts half.
5
**Parity: 79 %** (68 done, 2 partial, 17 missing of 87). Partial counts half.
6
6
7
7
## By area
8
8
@@ -12,7 +12,7 @@ Feature parity with the Microsoft Teams desktop client.
12
12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13
13
| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14
14
| [Writing](#writing) | 100 % | 14 | 0 | 0 |
15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
15
| [Message actions](#message-actions) | 100 % | 5 | 0 | 0 |
16
16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |
17
17
| [Notifications](#notifications) | 88 % | 7 | 0 | 1 |
18
18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |
@@ -100,10 +100,11 @@ Feature parity with the Microsoft Teams desktop client.
100
100
101
101
| Feature | State | Note |
102
102
|---|---|---|
103
| Forward a message | Missing | |
104
| Copy link to a message | Missing | |
105
| Save a message, saved list | Missing | |
106
| Pin a message in a chat | Missing | |
103
| Forward a message | Done | Dialog with chat and channel search, optional comment, "Forwarded" header on received forwards |
104
| Copy link to a message | Done | Teams deep link to the clipboard |
105
| Save a message, saved list | Done | Bookmark mark on saved messages, Saved panel next to the bell, synced with Teams |
106
| Pin a message in a chat | Done | Banner under the chat header, several pins cycle, unpin from the banner. Chats only |
107
| Mark as unread from a message | Done | Unread from the chosen message on |
107
108
108
109
## Channels
109
110
@@ -2,7 +2,7 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 74 %** (63 done, 2 partial, 21 missing of 86). Partial counts half.5
**Parity: 79 %** (68 done, 2 partial, 17 missing of 87). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -12,7 +12,7 @@ Feature parity with the Microsoft Teams desktop client.12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |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) | 100 % | 5 | 0 | 0 |16
| [Channels](#channels) | 57 % | 4 | 0 | 3 |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) | 80 % | 4 | 0 | 1 |18
| [Search and navigation](#search-and-navigation) | 80 % | 4 | 0 | 1 |@@ -100,10 +100,11 @@ Feature parity with the Microsoft Teams desktop client.100
100
101
| Feature | State | Note |101
| Feature | State | Note |102
|---|---|---|102
|---|---|---|103
| Forward a message | Missing | |103
| Forward a message | Done | Dialog with chat and channel search, optional comment, "Forwarded" header on received forwards |104
| Copy link to a message | Missing | |104
| Copy link to a message | Done | Teams deep link to the clipboard |105
| Save a message, saved list | Missing | |105
| Save a message, saved list | Done | Bookmark mark on saved messages, Saved panel next to the bell, synced with Teams |106
| Pin a message in a chat | Missing | |106
| Pin a message in a chat | Done | Banner under the chat header, several pins cycle, unpin from the banner. Chats only |107
| Mark as unread from a message | Done | Unread from the chosen message on |107
108
108
## Channels109
## Channels109
110
@@ -6,12 +6,13 @@ use chatsvc::TypingEvent;
6
6
use chrono::{DateTime, Utc};
7
7
use gpui_kit::*;
8
8
use store::{ChatRecord, Sidebar, Store};
9
use teams_core::{ChatApp, CoreEvent, ImageRef, ScheduledDraft};
9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, ScheduledDraft};
10
10
11
11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
12
12
use crate::card_state::{CardState, TaskDialogState};
13
13
use crate::data::{self, Directory};
14
14
use crate::local_previews::{LocalPreview, load_local_previews};
15
use crate::message_actions::{ForwardSource, SavedSet};
15
16
use crate::notice::Notice;
16
17
use crate::notify;
17
18
use crate::typing::TypingState;
@@ -47,6 +48,9 @@ pub enum AppEvent {
47
48
LocalPreviews,
48
49
Outbox(String),
49
50
Scheduled,
51
Pins(String),
52
Saved,
53
Forward,
50
54
}
51
55
52
56
#[derive(Debug, Clone, Copy, Default)]
@@ -84,6 +88,9 @@ pub struct AppState {
84
88
pub local_previews: HashMap<String, LocalPreview>,
85
89
pub scheduled: Vec<ScheduledDraft>,
86
90
pub scheduled_polling: bool,
91
pub saved: SavedSet,
92
pub pins: HashMap<String, Vec<PinnedMessage>>,
93
pub forward_request: Option<ForwardSource>,
87
94
}
88
95
89
96
pub struct AppHandle(pub Entity<AppState>);
@@ -158,6 +165,9 @@ impl AppState {
158
165
local_previews: HashMap::new(),
159
166
scheduled: Vec::new(),
160
167
scheduled_polling: false,
168
saved: SavedSet::default(),
169
pins: HashMap::new(),
170
forward_request: None,
161
171
};
162
172
state.local_previews = load_local_previews(&state.store);
163
173
state.collapsed = state.load_collapsed();
@@ -582,6 +592,9 @@ impl AppState {
582
592
self.clear_typists_who_sent(&conversation_id, cx);
583
593
cx.emit(AppEvent::Messages(conversation_id));
584
594
}
595
BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {
596
self.refresh_pins(&conversation_id, cx);
597
}
585
598
BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {
586
599
if let Some(engine) = &self.engine {
587
600
for key in &keys {
@@ -623,6 +636,9 @@ impl AppState {
623
636
cx.emit(AppEvent::Sidebar);
624
637
}
625
638
BackendEvent::Synced(time) => {
639
if self.last_sync.is_none() {
640
self.refresh_saved(cx);
641
}
626
642
self.last_sync = Some(time);
627
643
cx.emit(AppEvent::Status);
628
644
}
@@ -6,12 +6,13 @@ use chatsvc::TypingEvent;6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use gpui_kit::*;7
use gpui_kit::*;8
use store::{ChatRecord, Sidebar, Store};8
use store::{ChatRecord, Sidebar, Store};9
use teams_core::{ChatApp, CoreEvent, ImageRef, ScheduledDraft};9
use teams_core::{ChatApp, CoreEvent, ImageRef, PinnedMessage, ScheduledDraft};10
10
11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};11
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};12
use crate::card_state::{CardState, TaskDialogState};12
use crate::card_state::{CardState, TaskDialogState};13
use crate::data::{self, Directory};13
use crate::data::{self, Directory};14
use crate::local_previews::{LocalPreview, load_local_previews};14
use crate::local_previews::{LocalPreview, load_local_previews};15
use crate::message_actions::{ForwardSource, SavedSet};15
use crate::notice::Notice;16
use crate::notice::Notice;16
use crate::notify;17
use crate::notify;17
use crate::typing::TypingState;18
use crate::typing::TypingState;@@ -47,6 +48,9 @@ pub enum AppEvent {47
LocalPreviews,48
LocalPreviews,48
Outbox(String),49
Outbox(String),49
Scheduled,50
Scheduled,51
Pins(String),52
Saved,53
Forward,50
}54
}51
55
52
#[derive(Debug, Clone, Copy, Default)]56
#[derive(Debug, Clone, Copy, Default)]@@ -84,6 +88,9 @@ pub struct AppState {84
pub local_previews: HashMap<String, LocalPreview>,88
pub local_previews: HashMap<String, LocalPreview>,85
pub scheduled: Vec<ScheduledDraft>,89
pub scheduled: Vec<ScheduledDraft>,86
pub scheduled_polling: bool,90
pub scheduled_polling: bool,91
pub saved: SavedSet,92
pub pins: HashMap<String, Vec<PinnedMessage>>,93
pub forward_request: Option<ForwardSource>,87
}94
}88
95
89
pub struct AppHandle(pub Entity<AppState>);96
pub struct AppHandle(pub Entity<AppState>);@@ -158,6 +165,9 @@ impl AppState {158
local_previews: HashMap::new(),165
local_previews: HashMap::new(),159
scheduled: Vec::new(),166
scheduled: Vec::new(),160
scheduled_polling: false,167
scheduled_polling: false,168
saved: SavedSet::default(),169
pins: HashMap::new(),170
forward_request: None,161
};171
};162
state.local_previews = load_local_previews(&state.store);172
state.local_previews = load_local_previews(&state.store);163
state.collapsed = state.load_collapsed();173
state.collapsed = state.load_collapsed();@@ -582,6 +592,9 @@ impl AppState {582
self.clear_typists_who_sent(&conversation_id, cx);592
self.clear_typists_who_sent(&conversation_id, cx);583
cx.emit(AppEvent::Messages(conversation_id));593
cx.emit(AppEvent::Messages(conversation_id));584
}594
}595
BackendEvent::Core(CoreEvent::PinsChanged { conversation_id }) => {596
self.refresh_pins(&conversation_id, cx);597
}585
BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {598
BackendEvent::Core(CoreEvent::ImagesChanged { keys }) => {586
if let Some(engine) = &self.engine {599
if let Some(engine) = &self.engine {587
for key in &keys {600
for key in &keys {@@ -623,6 +636,9 @@ impl AppState {623
cx.emit(AppEvent::Sidebar);636
cx.emit(AppEvent::Sidebar);624
}637
}625
BackendEvent::Synced(time) => {638
BackendEvent::Synced(time) => {639
if self.last_sync.is_none() {640
self.refresh_saved(cx);641
}626
self.last_sync = Some(time);642
self.last_sync = Some(time);627
cx.emit(AppEvent::Status);643
cx.emit(AppEvent::Status);628
}644
}@@ -196,6 +196,7 @@ async fn realtime_loop(
196
196
let _ = events.send(BackendEvent::Live(LiveState::Live));
197
197
let receipt_engine = engine.clone();
198
198
let receipt_event = message.clone();
199
engine.handle_pin_event(&message);
199
200
tokio::spawn(async move {
200
201
receipt_engine.handle_receipt_event(&receipt_event).await
201
202
});
@@ -196,6 +196,7 @@ async fn realtime_loop(196
let _ = events.send(BackendEvent::Live(LiveState::Live));196
let _ = events.send(BackendEvent::Live(LiveState::Live));197
let receipt_engine = engine.clone();197
let receipt_engine = engine.clone();198
let receipt_event = message.clone();198
let receipt_event = message.clone();199
engine.handle_pin_event(&message);199
tokio::spawn(async move {200
tokio::spawn(async move {200
receipt_engine.handle_receipt_event(&receipt_event).await201
receipt_engine.handle_receipt_event(&receipt_event).await201
});202
});@@ -1,6 +1,6 @@
1
1
use std::future::Future;
2
2
3
use chrono::{Duration, Local, Offset, Utc};
3
use chrono::{DateTime, Duration, Local, Offset, Utc};
4
4
use gpui_kit::*;
5
5
use store::ChatRecord;
6
6
@@ -16,6 +16,15 @@ impl AppState {
16
16
}
17
17
18
18
pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {
19
self.mark_chat_unread_from(chat_id, None, cx);
20
}
21
22
pub fn mark_chat_unread_from(
23
&mut self,
24
chat_id: &str,
25
message_created_at: Option<DateTime<Utc>>,
26
cx: &mut Context<Self>,
27
) {
19
28
let Some(chat) = self.chat_record(chat_id) else {
20
29
return;
21
30
};
@@ -25,7 +34,8 @@ impl AppState {
25
34
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
26
35
return;
27
36
};
28
let last_read_at = last_message_at - Duration::milliseconds(1);
37
let last_read_at =
38
message_created_at.unwrap_or(last_message_at) - Duration::milliseconds(1);
29
39
let _ = self.store.mark_chat_unread(chat_id, last_read_at);
30
40
if self.selection == Some(Selection::Chat(chat_id.to_owned())) {
31
41
self.keep_unread = Some(chat_id.to_owned());
@@ -39,7 +49,12 @@ impl AppState {
39
49
let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);
40
50
self.run_chat_action(
41
51
"Mark as unread",
42
async move { engine.mark_unread(&owned_id).await },
52
async move {
53
match message_created_at {
54
Some(created_at) => engine.mark_unread_from(&owned_id, created_at).await,
55
None => engine.mark_unread(&owned_id).await,
56
}
57
},
43
58
move |state, cx| {
44
59
let _ = state.store.mark_chat_read(&revert_id, restored_read_at);
45
60
if state.keep_unread.as_deref() == Some(revert_id.as_str()) {
@@ -149,7 +164,7 @@ impl AppState {
149
164
}
150
165
151
166
/// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.
152
fn chat_action_engine(
167
pub(crate) fn chat_action_engine(
153
168
&mut self,
154
169
cx: &mut Context<Self>,
155
170
) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {
@@ -202,7 +217,7 @@ impl AppState {
202
217
next_chat_id(&build_sections(&input), chat_id)
203
218
}
204
219
205
fn run_chat_action(
220
pub(crate) fn run_chat_action(
206
221
&mut self,
207
222
label: &'static str,
208
223
call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
@@ -1,6 +1,6 @@1
use std::future::Future;1
use std::future::Future;2
2
3
use chrono::{Duration, Local, Offset, Utc};3
use chrono::{DateTime, Duration, Local, Offset, Utc};4
use gpui_kit::*;4
use gpui_kit::*;5
use store::ChatRecord;5
use store::ChatRecord;6
6
@@ -16,6 +16,15 @@ impl AppState {16
}16
}17
17
18
pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {18
pub fn mark_chat_unread(&mut self, chat_id: &str, cx: &mut Context<Self>) {19
self.mark_chat_unread_from(chat_id, None, cx);20
}21
22
pub fn mark_chat_unread_from(23
&mut self,24
chat_id: &str,25
message_created_at: Option<DateTime<Utc>>,26
cx: &mut Context<Self>,27
) {19
let Some(chat) = self.chat_record(chat_id) else {28
let Some(chat) = self.chat_record(chat_id) else {20
return;29
return;21
};30
};@@ -25,7 +34,8 @@ impl AppState {25
let Some(engine_or_demo) = self.chat_action_engine(cx) else {34
let Some(engine_or_demo) = self.chat_action_engine(cx) else {26
return;35
return;27
};36
};28
let last_read_at = last_message_at - Duration::milliseconds(1);37
let last_read_at =38
message_created_at.unwrap_or(last_message_at) - Duration::milliseconds(1);29
let _ = self.store.mark_chat_unread(chat_id, last_read_at);39
let _ = self.store.mark_chat_unread(chat_id, last_read_at);30
if self.selection == Some(Selection::Chat(chat_id.to_owned())) {40
if self.selection == Some(Selection::Chat(chat_id.to_owned())) {31
self.keep_unread = Some(chat_id.to_owned());41
self.keep_unread = Some(chat_id.to_owned());@@ -39,7 +49,12 @@ impl AppState {39
let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);49
let restored_read_at = chat.last_read_at.unwrap_or(last_message_at);40
self.run_chat_action(50
self.run_chat_action(41
"Mark as unread",51
"Mark as unread",42
async move { engine.mark_unread(&owned_id).await },52
async move {53
match message_created_at {54
Some(created_at) => engine.mark_unread_from(&owned_id, created_at).await,55
None => engine.mark_unread(&owned_id).await,56
}57
},43
move |state, cx| {58
move |state, cx| {44
let _ = state.store.mark_chat_read(&revert_id, restored_read_at);59
let _ = state.store.mark_chat_read(&revert_id, restored_read_at);45
if state.keep_unread.as_deref() == Some(revert_id.as_str()) {60
if state.keep_unread.as_deref() == Some(revert_id.as_str()) {@@ -149,7 +164,7 @@ impl AppState {149
}164
}150
165
151
/// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.166
/// `None` stops the action. `Some(None)` is demo mode, which only changes the local store.152
fn chat_action_engine(167
pub(crate) fn chat_action_engine(153
&mut self,168
&mut self,154
cx: &mut Context<Self>,169
cx: &mut Context<Self>,155
) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {170
) -> Option<Option<std::sync::Arc<crate::backend::Engine>>> {@@ -202,7 +217,7 @@ impl AppState {202
next_chat_id(&build_sections(&input), chat_id)217
next_chat_id(&build_sections(&input), chat_id)203
}218
}204
219
205
fn run_chat_action(220
pub(crate) fn run_chat_action(206
&mut self,221
&mut self,207
label: &'static str,222
label: &'static str,208
call: impl Future<Output = teams_core::Result<()>> + Send + 'static,223
call: impl Future<Output = teams_core::Result<()>> + Send + 'static,@@ -10,7 +10,7 @@ use store::{
10
10
};
11
11
use teams_core::{
12
12
CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13
TaskDialog, TaskDialogKind,
13
PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,
14
14
};
15
15
16
16
use crate::activity::{Actor, Entry, Kind};
@@ -18,6 +18,7 @@ use crate::app_state::{AppState, Selection};
18
18
use crate::card_actions::{CardAnswer, CardTask};
19
19
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
20
20
use crate::demo_gifs;
21
use crate::message_actions::ForwardSource;
21
22
22
23
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
23
24
@@ -128,6 +129,9 @@ const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
128
129
129
130
const UNREAD_CHAT: &str = "demo-chat-atlas";
130
131
const RELEASE_CHAT: &str = "demo-chat-release";
132
const PINNED_MESSAGE: &str = "m5b";
133
const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"];
134
const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward";
131
135
const FAVORITES_ID: &str = "demo-folder-favorites";
132
136
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
133
137
const ATLAS_FOLDER: &str = "demo-folder-atlas";
@@ -684,6 +688,61 @@ pub fn seed_directory(state: &mut AppState) {
684
688
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
685
689
state.last_sync = Some(Utc::now());
686
690
state.apply_bot_titles();
691
seed_message_actions(state);
692
}
693
694
fn seed_message_actions(state: &mut AppState) {
695
state.pins.insert(
696
RELEASE_CHAT.to_owned(),
697
vec![PinnedMessage {
698
message_id: PINNED_MESSAGE.to_owned(),
699
pinned_at: Some(at(0, 11, 30)),
700
parent_id: None,
701
}],
702
);
703
let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
704
let records = state
705
.store
706
.messages_by_id(RELEASE_CHAT, &ids)
707
.unwrap_or_default();
708
let saved = SAVED_MESSAGES
709
.iter()
710
.enumerate()
711
.filter_map(|(position, id)| {
712
let record = records.get(*id)?;
713
Some(SavedMessage {
714
conversation_id: record.conversation_id.clone(),
715
message_id: record.message_id.clone(),
716
root_id: record.message_id.clone(),
717
author_id: record.sender_id.clone(),
718
author_name: record.sender_name.clone(),
719
preview: crate::rows::reply_excerpt(record),
720
saved_at: at(position as i64, 15, 20),
721
topic: None,
722
})
723
})
724
.collect();
725
state.saved.replace(saved);
726
}
727
728
pub fn forwarded_message(
729
chat: &ChatRecord,
730
source: &ForwardSource,
731
comment: &str,
732
now: DateTime<Utc>,
733
) -> (ChatRecord, MessageRecord) {
734
let comment_html = if comment.is_empty() {
735
String::new()
736
} else {
737
format!("<p>{}</p>", teams_core::escape_html(comment))
738
};
739
let html = format!(
740
"{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
741
teams_core::escape_html(&source.message_id),
742
teams_core::escape_html(&source.author),
743
teams_core::escape_html(&source.text),
744
);
745
send_in_chat(chat, &source.text, &html, now)
687
746
}
688
747
689
748
#[allow(clippy::too_many_arguments)]
@@ -1115,6 +1174,18 @@ fn release_messages() -> Vec<MessageRecord> {
1115
1174
"[]",
1116
1175
false,
1117
1176
),
1177
message(
1178
chat,
1179
"m5d",
1180
None,
1181
(PRIYA_ID, priya_name),
1182
at(0, 12, 20),
1183
&format!(
1184
"<p>FYI, the customer asked for this.</p><blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"1790000000000\"><strong>Tobias Klein</strong><p>Can we move the freeze to Thursday? The customer demo is on Friday morning.</p></blockquote>"
1185
),
1186
"[]",
1187
false,
1188
),
1118
1189
message(
1119
1190
chat,
1120
1191
"m6",
@@ -10,7 +10,7 @@ use store::{10
};10
};11
use teams_core::{11
use teams_core::{12
CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,12
CardActionOutcome, ChatApp, Gif, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,13
TaskDialog, TaskDialogKind,13
PinnedMessage, SavedMessage, TaskDialog, TaskDialogKind,14
};14
};15
15
16
use crate::activity::{Actor, Entry, Kind};16
use crate::activity::{Actor, Entry, Kind};@@ -18,6 +18,7 @@ use crate::app_state::{AppState, Selection};18
use crate::card_actions::{CardAnswer, CardTask};18
use crate::card_actions::{CardAnswer, CardTask};19
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};19
use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};20
use crate::demo_gifs;20
use crate::demo_gifs;21
use crate::message_actions::ForwardSource;21
22
22
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();23
static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();23
24
@@ -128,6 +129,9 @@ const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";128
129
129
const UNREAD_CHAT: &str = "demo-chat-atlas";130
const UNREAD_CHAT: &str = "demo-chat-atlas";130
const RELEASE_CHAT: &str = "demo-chat-release";131
const RELEASE_CHAT: &str = "demo-chat-release";132
const PINNED_MESSAGE: &str = "m5b";133
const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"];134
const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward";131
const FAVORITES_ID: &str = "demo-folder-favorites";135
const FAVORITES_ID: &str = "demo-folder-favorites";132
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";136
const CUSTOMERS_FOLDER: &str = "demo-folder-customers";133
const ATLAS_FOLDER: &str = "demo-folder-atlas";137
const ATLAS_FOLDER: &str = "demo-folder-atlas";@@ -684,6 +688,61 @@ pub fn seed_directory(state: &mut AppState) {684
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());688
state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());685
state.last_sync = Some(Utc::now());689
state.last_sync = Some(Utc::now());686
state.apply_bot_titles();690
state.apply_bot_titles();691
seed_message_actions(state);692
}693
694
fn seed_message_actions(state: &mut AppState) {695
state.pins.insert(696
RELEASE_CHAT.to_owned(),697
vec![PinnedMessage {698
message_id: PINNED_MESSAGE.to_owned(),699
pinned_at: Some(at(0, 11, 30)),700
parent_id: None,701
}],702
);703
let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();704
let records = state705
.store706
.messages_by_id(RELEASE_CHAT, &ids)707
.unwrap_or_default();708
let saved = SAVED_MESSAGES709
.iter()710
.enumerate()711
.filter_map(|(position, id)| {712
let record = records.get(*id)?;713
Some(SavedMessage {714
conversation_id: record.conversation_id.clone(),715
message_id: record.message_id.clone(),716
root_id: record.message_id.clone(),717
author_id: record.sender_id.clone(),718
author_name: record.sender_name.clone(),719
preview: crate::rows::reply_excerpt(record),720
saved_at: at(position as i64, 15, 20),721
topic: None,722
})723
})724
.collect();725
state.saved.replace(saved);726
}727
728
pub fn forwarded_message(729
chat: &ChatRecord,730
source: &ForwardSource,731
comment: &str,732
now: DateTime<Utc>,733
) -> (ChatRecord, MessageRecord) {734
let comment_html = if comment.is_empty() {735
String::new()736
} else {737
format!("<p>{}</p>", teams_core::escape_html(comment))738
};739
let html = format!(740
"{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",741
teams_core::escape_html(&source.message_id),742
teams_core::escape_html(&source.author),743
teams_core::escape_html(&source.text),744
);745
send_in_chat(chat, &source.text, &html, now)687
}746
}688
747
689
#[allow(clippy::too_many_arguments)]748
#[allow(clippy::too_many_arguments)]@@ -1115,6 +1174,18 @@ fn release_messages() -> Vec<MessageRecord> {1115
"[]",1174
"[]",1116
false,1175
false,1117
),1176
),1177
message(1178
chat,1179
"m5d",1180
None,1181
(PRIYA_ID, priya_name),1182
at(0, 12, 20),1183
&format!(1184
"<p>FYI, the customer asked for this.</p><blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"1790000000000\"><strong>Tobias Klein</strong><p>Can we move the freeze to Thursday? The customer demo is on Friday morning.</p></blockquote>"1185
),1186
"[]",1187
false,1188
),1118
message(1189
message(1119
chat,1190
chat,1120
"m6",1191
"m6",@@ -23,6 +23,7 @@ mod frame_log;
23
23
mod fuzzy;
24
24
mod gifs;
25
25
mod local_previews;
26
mod message_actions;
26
27
mod notice;
27
28
mod notify;
28
29
mod outbox;
@@ -23,6 +23,7 @@ mod frame_log;23
mod fuzzy;23
mod fuzzy;24
mod gifs;24
mod gifs;25
mod local_previews;25
mod local_previews;26
mod message_actions;26
mod notice;27
mod notice;27
mod notify;28
mod notify;28
mod outbox;29
mod outbox;@@ -0,0 +1,438 @@
1
use std::collections::HashSet;
2
3
use chrono::{DateTime, Local, Offset, Utc};
4
use gpui_kit::*;
5
use store::MessageRecord;
6
use teams_core::{PinnedMessage, SavedMessage};
7
8
use crate::app_state::{AppEvent, AppState, Selection};
9
use crate::format;
10
use crate::notice::short_error;
11
use crate::notify::selection_for;
12
use crate::rows::{message_text, reply_excerpt};
13
use crate::runtime;
14
15
#[derive(Default)]
16
pub struct SavedSet {
17
items: Vec<SavedMessage>,
18
keys: HashSet<(String, String)>,
19
}
20
21
impl SavedSet {
22
pub fn items(&self) -> &[SavedMessage] {
23
&self.items
24
}
25
26
pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {
27
self.keys
28
.contains(&(conversation_id.to_owned(), message_id.to_owned()))
29
}
30
31
pub fn replace(&mut self, items: Vec<SavedMessage>) {
32
self.keys = items.iter().map(saved_key).collect();
33
self.items = items;
34
}
35
36
pub fn insert(&mut self, item: SavedMessage) {
37
if self.keys.insert(saved_key(&item)) {
38
self.items.insert(0, item);
39
}
40
}
41
42
pub fn remove(&mut self, conversation_id: &str, message_id: &str) -> Option<SavedMessage> {
43
let key = (conversation_id.to_owned(), message_id.to_owned());
44
if !self.keys.remove(&key) {
45
return None;
46
}
47
let position = self.items.iter().position(|item| saved_key(item) == key)?;
48
Some(self.items.remove(position))
49
}
50
}
51
52
fn saved_key(item: &SavedMessage) -> (String, String) {
53
(item.conversation_id.clone(), item.message_id.clone())
54
}
55
56
#[derive(Debug, Clone, PartialEq, Eq)]
57
pub struct ForwardSource {
58
pub conversation_id: String,
59
pub message_id: String,
60
pub author: String,
61
pub time: String,
62
pub text: String,
63
}
64
65
fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
66
SavedMessage {
67
conversation_id: record.conversation_id.clone(),
68
message_id: record.message_id.clone(),
69
root_id: record
70
.reply_to_id
71
.clone()
72
.filter(|_| is_channel)
73
.unwrap_or_else(|| record.message_id.clone()),
74
author_id: record.sender_id.clone(),
75
author_name: record.sender_name.clone(),
76
preview: reply_excerpt(record),
77
saved_at: Utc::now(),
78
topic: None,
79
}
80
}
81
82
impl AppState {
83
fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {
84
self.store
85
.messages_by_id(conversation_id, &[message_id.to_owned()])
86
.ok()?
87
.remove(message_id)
88
.filter(|record| !record.deleted)
89
}
90
91
pub fn is_saved(&self, conversation_id: &str, message_id: &str) -> bool {
92
self.saved.contains(conversation_id, message_id)
93
}
94
95
pub fn pinned_messages(&self, chat_id: &str) -> &[PinnedMessage] {
96
self.pins.get(chat_id).map_or(&[], Vec::as_slice)
97
}
98
99
pub fn is_pinned(&self, chat_id: &str, message_id: &str) -> bool {
100
self.pinned_messages(chat_id)
101
.iter()
102
.any(|pin| pin.message_id == message_id)
103
}
104
105
pub fn refresh_saved(&mut self, cx: &mut Context<Self>) {
106
let Some(engine) = self.engine.clone() else {
107
return;
108
};
109
let receiver = runtime::spawn(async move { engine.list_saved().await });
110
cx.spawn(async move |this, cx| {
111
if let Ok(Ok(items)) = receiver.await {
112
this.update(cx, |state, cx| {
113
state.saved.replace(items);
114
cx.emit(AppEvent::Saved);
115
cx.notify();
116
})
117
.ok();
118
}
119
})
120
.detach();
121
}
122
123
pub fn toggle_saved(
124
&mut self,
125
conversation_id: &str,
126
message_id: &str,
127
cx: &mut Context<Self>,
128
) {
129
let existing = self
130
.saved
131
.items()
132
.iter()
133
.find(|item| item.conversation_id == conversation_id && item.message_id == message_id)
134
.cloned();
135
match existing {
136
Some(entry) => self.set_saved(entry, false, cx),
137
None => {
138
let Some(record) = self.message_record(conversation_id, message_id) else {
139
return;
140
};
141
let is_channel = matches!(
142
selection_for(&self.sidebar, conversation_id),
143
Some(Selection::Channel(_))
144
);
145
self.set_saved(saved_entry(&record, is_channel), true, cx);
146
}
147
}
148
}
149
150
pub fn set_saved(&mut self, entry: SavedMessage, saved: bool, cx: &mut Context<Self>) {
151
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
152
return;
153
};
154
let restore = if saved {
155
self.saved.insert(entry.clone());
156
None
157
} else {
158
self.saved.remove(&entry.conversation_id, &entry.message_id)
159
};
160
cx.emit(AppEvent::Saved);
161
cx.notify();
162
let Some(engine) = engine_or_demo else {
163
return;
164
};
165
let (conversation_id, message_id) =
166
(entry.conversation_id.clone(), entry.message_id.clone());
167
let root_id = (entry.root_id != entry.message_id).then(|| entry.root_id.clone());
168
self.run_chat_action(
169
if saved { "Save" } else { "Unsave" },
170
async move {
171
engine
172
.set_saved(&conversation_id, &message_id, root_id.as_deref(), saved)
173
.await
174
},
175
move |state, cx| {
176
if saved {
177
state
178
.saved
179
.remove(&entry.conversation_id, &entry.message_id);
180
} else {
181
state.saved.insert(restore.unwrap_or(entry));
182
}
183
cx.emit(AppEvent::Saved);
184
cx.notify();
185
},
186
|_, _| {},
187
cx,
188
);
189
}
190
191
pub fn refresh_pins(&mut self, chat_id: &str, cx: &mut Context<Self>) {
192
let Some(engine) = self.engine.clone() else {
193
return;
194
};
195
let chat_id = chat_id.to_owned();
196
let requested_id = chat_id.clone();
197
let receiver = runtime::spawn(async move { engine.chat_pins(&requested_id).await });
198
cx.spawn(async move |this, cx| {
199
if let Ok(Ok(pins)) = receiver.await {
200
this.update(cx, |state, cx| state.store_pins(&chat_id, pins, cx))
201
.ok();
202
}
203
})
204
.detach();
205
}
206
207
fn store_pins(&mut self, chat_id: &str, pins: Vec<PinnedMessage>, cx: &mut Context<Self>) {
208
self.pins.insert(chat_id.to_owned(), pins);
209
cx.emit(AppEvent::Pins(chat_id.to_owned()));
210
cx.notify();
211
}
212
213
pub fn toggle_pinned(&mut self, chat_id: &str, message_id: &str, cx: &mut Context<Self>) {
214
let pinned = self.is_pinned(chat_id, message_id);
215
self.set_pinned(chat_id, message_id, !pinned, cx);
216
}
217
218
pub fn set_pinned(
219
&mut self,
220
chat_id: &str,
221
message_id: &str,
222
pinned: bool,
223
cx: &mut Context<Self>,
224
) {
225
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
226
return;
227
};
228
let previous = self.pinned_messages(chat_id).to_vec();
229
let parent_id = previous
230
.iter()
231
.find(|pin| pin.message_id == message_id)
232
.and_then(|pin| pin.parent_id.clone());
233
let mut updated: Vec<PinnedMessage> = previous
234
.iter()
235
.filter(|pin| pin.message_id != message_id)
236
.cloned()
237
.collect();
238
if pinned {
239
updated.insert(
240
0,
241
PinnedMessage {
242
message_id: message_id.to_owned(),
243
pinned_at: Some(Utc::now()),
244
parent_id: None,
245
},
246
);
247
}
248
self.store_pins(chat_id, updated, cx);
249
let Some(engine) = engine_or_demo else {
250
return;
251
};
252
let (owned_chat, owned_message, revert_chat) = (
253
chat_id.to_owned(),
254
message_id.to_owned(),
255
chat_id.to_owned(),
256
);
257
self.run_chat_action(
258
if pinned { "Pin" } else { "Unpin" },
259
async move {
260
if pinned {
261
engine.pin_message(&owned_chat, &owned_message).await
262
} else {
263
engine
264
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
265
.await
266
}
267
},
268
move |state, cx| state.store_pins(&revert_chat, previous, cx),
269
|_, _| {},
270
cx,
271
);
272
}
273
274
pub fn copy_message_link(
275
&mut self,
276
conversation_id: &str,
277
message_id: &str,
278
cx: &mut Context<Self>,
279
) {
280
let Some(engine) = self.engine.clone() else {
281
if !self.mode.demo {
282
return;
283
}
284
let link = teams_core::chat_message_link(conversation_id, message_id, None);
285
cx.write_to_clipboard(ClipboardItem::new_string(link));
286
self.raise_notice("Link copied".to_owned(), None, cx);
287
return;
288
};
289
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());
290
let receiver =
291
runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await });
292
cx.spawn(async move |this, cx| {
293
let outcome = match receiver.await {
294
Ok(Ok(link)) => Ok(link),
295
Ok(Err(error)) => Err(short_error(&error)),
296
Err(_) => Err("cancelled".to_owned()),
297
};
298
this.update(cx, |state, cx| match outcome {
299
Ok(link) => {
300
cx.write_to_clipboard(ClipboardItem::new_string(link));
301
state.raise_notice("Link copied".to_owned(), None, cx);
302
}
303
Err(reason) => state.raise_notice(format!("Copy link failed: {reason}"), None, cx),
304
})
305
.ok();
306
})
307
.detach();
308
}
309
310
pub fn request_forward(
311
&mut self,
312
conversation_id: &str,
313
message_id: &str,
314
cx: &mut Context<Self>,
315
) {
316
if self.mode.read_only {
317
self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);
318
return;
319
}
320
let Some(record) = self.message_record(conversation_id, message_id) else {
321
return;
322
};
323
let now = Local::now();
324
self.forward_request = Some(ForwardSource {
325
conversation_id: record.conversation_id.clone(),
326
message_id: record.message_id.clone(),
327
author: record
328
.sender_name
329
.clone()
330
.unwrap_or_else(|| "Unknown".to_owned()),
331
time: forward_time(record.created_at, now),
332
text: message_text(&record),
333
});
334
cx.emit(AppEvent::Forward);
335
cx.notify();
336
}
337
338
pub fn take_forward_request(&mut self) -> Option<ForwardSource> {
339
self.forward_request.take()
340
}
341
342
pub fn forward_locally(
343
&mut self,
344
source: &ForwardSource,
345
target: &Selection,
346
comment: &str,
347
cx: &mut Context<Self>,
348
) {
349
let Selection::Chat(chat_id) = target else {
350
return;
351
};
352
let Some(chat) = self.sidebar.chats.iter().find(|chat| &chat.id == chat_id) else {
353
return;
354
};
355
let (chat, record) =
356
crate::demo::forwarded_message(chat, source, comment, chrono::Utc::now());
357
let _ = self.store.upsert_chats(&[chat]);
358
let _ = self.store.upsert_messages(&[record]);
359
self.reload_sidebar(cx);
360
cx.emit(AppEvent::Messages(chat_id.clone()));
361
}
362
363
pub fn mark_unread_from_message(
364
&mut self,
365
chat_id: &str,
366
message_id: &str,
367
cx: &mut Context<Self>,
368
) {
369
let Some(record) = self.message_record(chat_id, message_id) else {
370
return;
371
};
372
self.mark_chat_unread_from(chat_id, Some(record.created_at), cx);
373
}
374
}
375
376
fn forward_time(time: DateTime<Utc>, now: DateTime<Local>) -> String {
377
format::list_time_label(time, now.date_naive(), now.offset().fix())
378
}
379
380
#[cfg(test)]
381
mod tests {
382
use chrono::{TimeZone, Utc};
383
use teams_core::SavedMessage;
384
385
use super::SavedSet;
386
387
fn saved(message_id: &str) -> SavedMessage {
388
SavedMessage {
389
conversation_id: "chat".into(),
390
message_id: message_id.into(),
391
root_id: message_id.into(),
392
author_id: None,
393
author_name: None,
394
preview: "text".into(),
395
saved_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),
396
topic: None,
397
}
398
}
399
400
#[test]
401
fn saving_then_unsaving_a_message_updates_the_lookup() {
402
let mut set = SavedSet::default();
403
set.insert(saved("m1"));
404
assert!(set.contains("chat", "m1"));
405
assert!(!set.contains("other", "m1"));
406
assert!(set.remove("chat", "m1").is_some());
407
assert!(!set.contains("chat", "m1"));
408
assert!(set.items().is_empty());
409
}
410
411
#[test]
412
fn newest_saved_message_comes_first() {
413
let mut set = SavedSet::default();
414
set.insert(saved("m1"));
415
set.insert(saved("m2"));
416
set.insert(saved("m2"));
417
let ids: Vec<&str> = set
418
.items()
419
.iter()
420
.map(|item| item.message_id.as_str())
421
.collect();
422
assert_eq!(ids, vec!["m2", "m1"]);
423
}
424
425
#[test]
426
fn replacing_the_set_rebuilds_the_lookup() {
427
let mut set = SavedSet::default();
428
set.insert(saved("m1"));
429
set.replace(vec![saved("m2")]);
430
assert!(!set.contains("chat", "m1"));
431
assert!(set.contains("chat", "m2"));
432
assert_eq!(
433
set.remove("chat", "m2").map(|item| item.message_id),
434
Some("m2".into())
435
);
436
assert_eq!(set.remove("chat", "m2"), None);
437
}
438
}
@@ -0,0 +1,438 @@1
use std::collections::HashSet;2
3
use chrono::{DateTime, Local, Offset, Utc};4
use gpui_kit::*;5
use store::MessageRecord;6
use teams_core::{PinnedMessage, SavedMessage};7
8
use crate::app_state::{AppEvent, AppState, Selection};9
use crate::format;10
use crate::notice::short_error;11
use crate::notify::selection_for;12
use crate::rows::{message_text, reply_excerpt};13
use crate::runtime;14
15
#[derive(Default)]16
pub struct SavedSet {17
items: Vec<SavedMessage>,18
keys: HashSet<(String, String)>,19
}20
21
impl SavedSet {22
pub fn items(&self) -> &[SavedMessage] {23
&self.items24
}25
26
pub fn contains(&self, conversation_id: &str, message_id: &str) -> bool {27
self.keys28
.contains(&(conversation_id.to_owned(), message_id.to_owned()))29
}30
31
pub fn replace(&mut self, items: Vec<SavedMessage>) {32
self.keys = items.iter().map(saved_key).collect();33
self.items = items;34
}35
36
pub fn insert(&mut self, item: SavedMessage) {37
if self.keys.insert(saved_key(&item)) {38
self.items.insert(0, item);39
}40
}41
42
pub fn remove(&mut self, conversation_id: &str, message_id: &str) -> Option<SavedMessage> {43
let key = (conversation_id.to_owned(), message_id.to_owned());44
if !self.keys.remove(&key) {45
return None;46
}47
let position = self.items.iter().position(|item| saved_key(item) == key)?;48
Some(self.items.remove(position))49
}50
}51
52
fn saved_key(item: &SavedMessage) -> (String, String) {53
(item.conversation_id.clone(), item.message_id.clone())54
}55
56
#[derive(Debug, Clone, PartialEq, Eq)]57
pub struct ForwardSource {58
pub conversation_id: String,59
pub message_id: String,60
pub author: String,61
pub time: String,62
pub text: String,63
}64
65
fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {66
SavedMessage {67
conversation_id: record.conversation_id.clone(),68
message_id: record.message_id.clone(),69
root_id: record70
.reply_to_id71
.clone()72
.filter(|_| is_channel)73
.unwrap_or_else(|| record.message_id.clone()),74
author_id: record.sender_id.clone(),75
author_name: record.sender_name.clone(),76
preview: reply_excerpt(record),77
saved_at: Utc::now(),78
topic: None,79
}80
}81
82
impl AppState {83
fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {84
self.store85
.messages_by_id(conversation_id, &[message_id.to_owned()])86
.ok()?87
.remove(message_id)88
.filter(|record| !record.deleted)89
}90
91
pub fn is_saved(&self, conversation_id: &str, message_id: &str) -> bool {92
self.saved.contains(conversation_id, message_id)93
}94
95
pub fn pinned_messages(&self, chat_id: &str) -> &[PinnedMessage] {96
self.pins.get(chat_id).map_or(&[], Vec::as_slice)97
}98
99
pub fn is_pinned(&self, chat_id: &str, message_id: &str) -> bool {100
self.pinned_messages(chat_id)101
.iter()102
.any(|pin| pin.message_id == message_id)103
}104
105
pub fn refresh_saved(&mut self, cx: &mut Context<Self>) {106
let Some(engine) = self.engine.clone() else {107
return;108
};109
let receiver = runtime::spawn(async move { engine.list_saved().await });110
cx.spawn(async move |this, cx| {111
if let Ok(Ok(items)) = receiver.await {112
this.update(cx, |state, cx| {113
state.saved.replace(items);114
cx.emit(AppEvent::Saved);115
cx.notify();116
})117
.ok();118
}119
})120
.detach();121
}122
123
pub fn toggle_saved(124
&mut self,125
conversation_id: &str,126
message_id: &str,127
cx: &mut Context<Self>,128
) {129
let existing = self130
.saved131
.items()132
.iter()133
.find(|item| item.conversation_id == conversation_id && item.message_id == message_id)134
.cloned();135
match existing {136
Some(entry) => self.set_saved(entry, false, cx),137
None => {138
let Some(record) = self.message_record(conversation_id, message_id) else {139
return;140
};141
let is_channel = matches!(142
selection_for(&self.sidebar, conversation_id),143
Some(Selection::Channel(_))144
);145
self.set_saved(saved_entry(&record, is_channel), true, cx);146
}147
}148
}149
150
pub fn set_saved(&mut self, entry: SavedMessage, saved: bool, cx: &mut Context<Self>) {151
let Some(engine_or_demo) = self.chat_action_engine(cx) else {152
return;153
};154
let restore = if saved {155
self.saved.insert(entry.clone());156
None157
} else {158
self.saved.remove(&entry.conversation_id, &entry.message_id)159
};160
cx.emit(AppEvent::Saved);161
cx.notify();162
let Some(engine) = engine_or_demo else {163
return;164
};165
let (conversation_id, message_id) =166
(entry.conversation_id.clone(), entry.message_id.clone());167
let root_id = (entry.root_id != entry.message_id).then(|| entry.root_id.clone());168
self.run_chat_action(169
if saved { "Save" } else { "Unsave" },170
async move {171
engine172
.set_saved(&conversation_id, &message_id, root_id.as_deref(), saved)173
.await174
},175
move |state, cx| {176
if saved {177
state178
.saved179
.remove(&entry.conversation_id, &entry.message_id);180
} else {181
state.saved.insert(restore.unwrap_or(entry));182
}183
cx.emit(AppEvent::Saved);184
cx.notify();185
},186
|_, _| {},187
cx,188
);189
}190
191
pub fn refresh_pins(&mut self, chat_id: &str, cx: &mut Context<Self>) {192
let Some(engine) = self.engine.clone() else {193
return;194
};195
let chat_id = chat_id.to_owned();196
let requested_id = chat_id.clone();197
let receiver = runtime::spawn(async move { engine.chat_pins(&requested_id).await });198
cx.spawn(async move |this, cx| {199
if let Ok(Ok(pins)) = receiver.await {200
this.update(cx, |state, cx| state.store_pins(&chat_id, pins, cx))201
.ok();202
}203
})204
.detach();205
}206
207
fn store_pins(&mut self, chat_id: &str, pins: Vec<PinnedMessage>, cx: &mut Context<Self>) {208
self.pins.insert(chat_id.to_owned(), pins);209
cx.emit(AppEvent::Pins(chat_id.to_owned()));210
cx.notify();211
}212
213
pub fn toggle_pinned(&mut self, chat_id: &str, message_id: &str, cx: &mut Context<Self>) {214
let pinned = self.is_pinned(chat_id, message_id);215
self.set_pinned(chat_id, message_id, !pinned, cx);216
}217
218
pub fn set_pinned(219
&mut self,220
chat_id: &str,221
message_id: &str,222
pinned: bool,223
cx: &mut Context<Self>,224
) {225
let Some(engine_or_demo) = self.chat_action_engine(cx) else {226
return;227
};228
let previous = self.pinned_messages(chat_id).to_vec();229
let parent_id = previous230
.iter()231
.find(|pin| pin.message_id == message_id)232
.and_then(|pin| pin.parent_id.clone());233
let mut updated: Vec<PinnedMessage> = previous234
.iter()235
.filter(|pin| pin.message_id != message_id)236
.cloned()237
.collect();238
if pinned {239
updated.insert(240
0,241
PinnedMessage {242
message_id: message_id.to_owned(),243
pinned_at: Some(Utc::now()),244
parent_id: None,245
},246
);247
}248
self.store_pins(chat_id, updated, cx);249
let Some(engine) = engine_or_demo else {250
return;251
};252
let (owned_chat, owned_message, revert_chat) = (253
chat_id.to_owned(),254
message_id.to_owned(),255
chat_id.to_owned(),256
);257
self.run_chat_action(258
if pinned { "Pin" } else { "Unpin" },259
async move {260
if pinned {261
engine.pin_message(&owned_chat, &owned_message).await262
} else {263
engine264
.unpin_message(&owned_chat, &owned_message, parent_id.as_deref())265
.await266
}267
},268
move |state, cx| state.store_pins(&revert_chat, previous, cx),269
|_, _| {},270
cx,271
);272
}273
274
pub fn copy_message_link(275
&mut self,276
conversation_id: &str,277
message_id: &str,278
cx: &mut Context<Self>,279
) {280
let Some(engine) = self.engine.clone() else {281
if !self.mode.demo {282
return;283
}284
let link = teams_core::chat_message_link(conversation_id, message_id, None);285
cx.write_to_clipboard(ClipboardItem::new_string(link));286
self.raise_notice("Link copied".to_owned(), None, cx);287
return;288
};289
let (conversation_id, message_id) = (conversation_id.to_owned(), message_id.to_owned());290
let receiver =291
runtime::spawn(async move { engine.message_link(&conversation_id, &message_id).await });292
cx.spawn(async move |this, cx| {293
let outcome = match receiver.await {294
Ok(Ok(link)) => Ok(link),295
Ok(Err(error)) => Err(short_error(&error)),296
Err(_) => Err("cancelled".to_owned()),297
};298
this.update(cx, |state, cx| match outcome {299
Ok(link) => {300
cx.write_to_clipboard(ClipboardItem::new_string(link));301
state.raise_notice("Link copied".to_owned(), None, cx);302
}303
Err(reason) => state.raise_notice(format!("Copy link failed: {reason}"), None, cx),304
})305
.ok();306
})307
.detach();308
}309
310
pub fn request_forward(311
&mut self,312
conversation_id: &str,313
message_id: &str,314
cx: &mut Context<Self>,315
) {316
if self.mode.read_only {317
self.raise_notice("Read-only mode: message not forwarded".to_owned(), None, cx);318
return;319
}320
let Some(record) = self.message_record(conversation_id, message_id) else {321
return;322
};323
let now = Local::now();324
self.forward_request = Some(ForwardSource {325
conversation_id: record.conversation_id.clone(),326
message_id: record.message_id.clone(),327
author: record328
.sender_name329
.clone()330
.unwrap_or_else(|| "Unknown".to_owned()),331
time: forward_time(record.created_at, now),332
text: message_text(&record),333
});334
cx.emit(AppEvent::Forward);335
cx.notify();336
}337
338
pub fn take_forward_request(&mut self) -> Option<ForwardSource> {339
self.forward_request.take()340
}341
342
pub fn forward_locally(343
&mut self,344
source: &ForwardSource,345
target: &Selection,346
comment: &str,347
cx: &mut Context<Self>,348
) {349
let Selection::Chat(chat_id) = target else {350
return;351
};352
let Some(chat) = self.sidebar.chats.iter().find(|chat| &chat.id == chat_id) else {353
return;354
};355
let (chat, record) =356
crate::demo::forwarded_message(chat, source, comment, chrono::Utc::now());357
let _ = self.store.upsert_chats(&[chat]);358
let _ = self.store.upsert_messages(&[record]);359
self.reload_sidebar(cx);360
cx.emit(AppEvent::Messages(chat_id.clone()));361
}362
363
pub fn mark_unread_from_message(364
&mut self,365
chat_id: &str,366
message_id: &str,367
cx: &mut Context<Self>,368
) {369
let Some(record) = self.message_record(chat_id, message_id) else {370
return;371
};372
self.mark_chat_unread_from(chat_id, Some(record.created_at), cx);373
}374
}375
376
fn forward_time(time: DateTime<Utc>, now: DateTime<Local>) -> String {377
format::list_time_label(time, now.date_naive(), now.offset().fix())378
}379
380
#[cfg(test)]381
mod tests {382
use chrono::{TimeZone, Utc};383
use teams_core::SavedMessage;384
385
use super::SavedSet;386
387
fn saved(message_id: &str) -> SavedMessage {388
SavedMessage {389
conversation_id: "chat".into(),390
message_id: message_id.into(),391
root_id: message_id.into(),392
author_id: None,393
author_name: None,394
preview: "text".into(),395
saved_at: Utc.with_ymd_and_hms(2026, 10, 9, 8, 0, 0).unwrap(),396
topic: None,397
}398
}399
400
#[test]401
fn saving_then_unsaving_a_message_updates_the_lookup() {402
let mut set = SavedSet::default();403
set.insert(saved("m1"));404
assert!(set.contains("chat", "m1"));405
assert!(!set.contains("other", "m1"));406
assert!(set.remove("chat", "m1").is_some());407
assert!(!set.contains("chat", "m1"));408
assert!(set.items().is_empty());409
}410
411
#[test]412
fn newest_saved_message_comes_first() {413
let mut set = SavedSet::default();414
set.insert(saved("m1"));415
set.insert(saved("m2"));416
set.insert(saved("m2"));417
let ids: Vec<&str> = set418
.items()419
.iter()420
.map(|item| item.message_id.as_str())421
.collect();422
assert_eq!(ids, vec!["m2", "m1"]);423
}424
425
#[test]426
fn replacing_the_set_rebuilds_the_lookup() {427
let mut set = SavedSet::default();428
set.insert(saved("m1"));429
set.replace(vec![saved("m2")]);430
assert!(!set.contains("chat", "m1"));431
assert!(set.contains("chat", "m2"));432
assert_eq!(433
set.remove("chat", "m2").map(|item| item.message_id),434
Some("m2".into())435
);436
assert_eq!(set.remove("chat", "m2"), None);437
}438
}@@ -70,5 +70,6 @@ pub fn pending_row(
70
70
delivery,
71
71
receipt: Receipt::Hidden,
72
72
own: true,
73
forwarded: false,
73
74
}
74
75
}
@@ -70,5 +70,6 @@ pub fn pending_row(70
delivery,70
delivery,71
receipt: Receipt::Hidden,71
receipt: Receipt::Hidden,72
own: true,72
own: true,73
forwarded: false,73
}74
}74
}75
}@@ -143,6 +143,7 @@ pub struct MessageRow {
143
143
pub delivery: Delivery,
144
144
pub own: bool,
145
145
pub receipt: Receipt,
146
pub forwarded: bool,
146
147
}
147
148
148
149
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -446,6 +447,7 @@ fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
446
447
}
447
448
448
449
const REPLY_EXCERPT_CHARS: usize = 90;
450
const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
449
451
450
452
pub fn message_text(record: &MessageRecord) -> String {
451
453
let own_spans: Vec<Span> = message_spans(record)
@@ -565,9 +567,14 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
565
567
delivery: Delivery::Delivered,
566
568
receipt: Receipt::Hidden,
567
569
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,
570
forwarded: !record.deleted && is_forwarded(&record.body_html),
568
571
}
569
572
}
570
573
574
pub fn is_forwarded(body_html: &str) -> bool {
575
body_html.contains(FORWARD_ITEMTYPE)
576
}
577
571
578
pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
572
579
let mut rows = Vec::with_capacity(records.len() + 1);
573
580
if has_older {
@@ -870,6 +877,23 @@ mod tests {
870
877
assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
871
878
}
872
879
880
#[test]
881
fn forwarded_messages_are_detected_by_the_forward_blockquote() {
882
assert!(is_forwarded(
883
r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#
884
));
885
assert!(!is_forwarded(
886
r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#
887
));
888
assert!(!is_forwarded("<p>plain</p>"));
889
let mut forwarded = record("f", None, 8, 6);
890
forwarded.body_html =
891
r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
892
assert!(message_row(&forwarded, &context()).forwarded);
893
forwarded.deleted = true;
894
assert!(!message_row(&forwarded, &context()).forwarded);
895
}
896
873
897
#[test]
874
898
fn editing_loads_the_message_formatted_without_its_reply_quote() {
875
899
let mut edited = record("a", None, 8, 6);
@@ -143,6 +143,7 @@ pub struct MessageRow {143
pub delivery: Delivery,143
pub delivery: Delivery,144
pub own: bool,144
pub own: bool,145
pub receipt: Receipt,145
pub receipt: Receipt,146
pub forwarded: bool,146
}147
}147
148
148
#[derive(Debug, Clone, PartialEq, Eq)]149
#[derive(Debug, Clone, PartialEq, Eq)]@@ -446,6 +447,7 @@ fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {446
}447
}447
448
448
const REPLY_EXCERPT_CHARS: usize = 90;449
const REPLY_EXCERPT_CHARS: usize = 90;450
const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";449
451
450
pub fn message_text(record: &MessageRecord) -> String {452
pub fn message_text(record: &MessageRecord) -> String {451
let own_spans: Vec<Span> = message_spans(record)453
let own_spans: Vec<Span> = message_spans(record)@@ -565,9 +567,14 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {565
delivery: Delivery::Delivered,567
delivery: Delivery::Delivered,566
receipt: Receipt::Hidden,568
receipt: Receipt::Hidden,567
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,569
own: context.my_user_id.is_some() && record.sender_id == context.my_user_id,570
forwarded: !record.deleted && is_forwarded(&record.body_html),568
}571
}569
}572
}570
573
574
pub fn is_forwarded(body_html: &str) -> bool {575
body_html.contains(FORWARD_ITEMTYPE)576
}577
571
pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {578
pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {572
let mut rows = Vec::with_capacity(records.len() + 1);579
let mut rows = Vec::with_capacity(records.len() + 1);573
if has_older {580
if has_older {@@ -870,6 +877,23 @@ mod tests {870
assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");877
assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");871
}878
}872
879
880
#[test]881
fn forwarded_messages_are_detected_by_the_forward_blockquote() {882
assert!(is_forwarded(883
r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#884
));885
assert!(!is_forwarded(886
r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#887
));888
assert!(!is_forwarded("<p>plain</p>"));889
let mut forwarded = record("f", None, 8, 6);890
forwarded.body_html =891
r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();892
assert!(message_row(&forwarded, &context()).forwarded);893
forwarded.deleted = true;894
assert!(!message_row(&forwarded, &context()).forwarded);895
}896
873
#[test]897
#[test]874
fn editing_loads_the_message_formatted_without_its_reply_quote() {898
fn editing_loads_the_message_formatted_without_its_reply_quote() {875
let mut edited = record("a", None, 8, 6);899
let mut edited = record("a", None, 8, 6);@@ -20,6 +20,7 @@ use store::{MessageRecord, OutboxState, OutboxTarget};
20
20
use teams_core::{FileCard, LinkPreview};
21
21
22
22
mod feed;
23
mod pins;
23
24
mod render_env;
24
25
mod scheduled;
25
26
@@ -159,6 +160,8 @@ pub struct ConversationView {
159
160
picker: Entity<ReactionPicker>,
160
161
reaction_details: Option<ReactionDetails>,
161
162
highlighted_message: Option<String>,
163
pin_index: usize,
164
pin_previews: HashMap<String, pins::PinPreview>,
162
165
notice: Option<String>,
163
166
scheduled_failure: Option<scheduled::ScheduledFailure>,
164
167
scheduled_in_flight: HashSet<String>,
@@ -407,6 +410,8 @@ impl ConversationView {
407
410
picker,
408
411
reaction_details: None,
409
412
highlighted_message: None,
413
pin_index: 0,
414
pin_previews: HashMap::new(),
410
415
notice: None,
411
416
scheduled_failure: None,
412
417
scheduled_in_flight: HashSet::new(),
@@ -483,6 +488,7 @@ impl ConversationView {
483
488
if is_current {
484
489
self.rebuild(false, cx);
485
490
self.mark_read(ReadTrigger::Incoming, cx);
491
self.on_pins_changed(conversation_id, cx);
486
492
}
487
493
}
488
494
AppEvent::Images(keys) => self.remeasure_images(keys, cx),
@@ -500,7 +506,9 @@ impl ConversationView {
500
506
self.refresh_reactor_names(cx);
501
507
cx.notify();
502
508
}
503
AppEvent::TaskDialog | AppEvent::LocalPreviews => {}
509
AppEvent::TaskDialog | AppEvent::LocalPreviews | AppEvent::Forward => {}
510
AppEvent::Saved => cx.notify(),
511
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
504
512
AppEvent::Typing => cx.notify(),
505
513
AppEvent::Scheduled => self.rebuild(false, cx),
506
514
AppEvent::Outbox(conversation_id) => {
@@ -682,6 +690,11 @@ impl ConversationView {
682
690
self.rebuild(true, cx);
683
691
self.start_fetch(cx);
684
692
self.mark_read(ReadTrigger::Open, cx);
693
self.refresh_pin_previews(cx);
694
if let Some(chat_id) = self.chat_id() {
695
self.app
696
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));
697
}
685
698
let target = self
686
699
.current
687
700
.as_ref()
@@ -2550,15 +2563,32 @@ impl ConversationView {
2550
2563
.ok();
2551
2564
})
2552
2565
};
2566
let chat_id = self.chat_id();
2567
let state = self.app.read(cx);
2568
let saved = self
2569
.conversation_id()
2570
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
2571
let pinned = chat_id
2572
.as_deref()
2573
.is_some_and(|chat_id| state.is_pinned(chat_id, key));
2574
let in_chat = chat_id.is_some();
2553
2575
MessageMenu {
2554
2576
key: key.to_owned(),
2555
2577
react,
2556
2578
reply: Some(action(|this, key, window, cx| {
2557
2579
this.begin_reply(key, window, cx)
2558
2580
})),
2581
forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
2582
copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
2559
2583
copy: action(|this, key, _, cx| this.copy_text(key, cx)),
2584
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
2585
saved,
2586
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
2587
pinned,
2560
2588
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
2561
2589
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
2590
mark_unread: (in_chat && !own)
2591
.then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2562
2592
pin,
2563
2593
hover,
2564
2594
picker: self.picker.clone(),
@@ -2962,6 +2992,7 @@ impl Render for ConversationView {
2962
2992
Some(current) => root.child(self.render_header(current, cx)),
2963
2993
None => root.child(self.draft.clone()),
2964
2994
};
2995
root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));
2965
2996
let sync_failed = self
2966
2997
.current
2967
2998
.as_ref()
@@ -20,6 +20,7 @@ use store::{MessageRecord, OutboxState, OutboxTarget};20
use teams_core::{FileCard, LinkPreview};20
use teams_core::{FileCard, LinkPreview};21
21
22
mod feed;22
mod feed;23
mod pins;23
mod render_env;24
mod render_env;24
mod scheduled;25
mod scheduled;25
26
@@ -159,6 +160,8 @@ pub struct ConversationView {159
picker: Entity<ReactionPicker>,160
picker: Entity<ReactionPicker>,160
reaction_details: Option<ReactionDetails>,161
reaction_details: Option<ReactionDetails>,161
highlighted_message: Option<String>,162
highlighted_message: Option<String>,163
pin_index: usize,164
pin_previews: HashMap<String, pins::PinPreview>,162
notice: Option<String>,165
notice: Option<String>,163
scheduled_failure: Option<scheduled::ScheduledFailure>,166
scheduled_failure: Option<scheduled::ScheduledFailure>,164
scheduled_in_flight: HashSet<String>,167
scheduled_in_flight: HashSet<String>,@@ -407,6 +410,8 @@ impl ConversationView {407
picker,410
picker,408
reaction_details: None,411
reaction_details: None,409
highlighted_message: None,412
highlighted_message: None,413
pin_index: 0,414
pin_previews: HashMap::new(),410
notice: None,415
notice: None,411
scheduled_failure: None,416
scheduled_failure: None,412
scheduled_in_flight: HashSet::new(),417
scheduled_in_flight: HashSet::new(),@@ -483,6 +488,7 @@ impl ConversationView {483
if is_current {488
if is_current {484
self.rebuild(false, cx);489
self.rebuild(false, cx);485
self.mark_read(ReadTrigger::Incoming, cx);490
self.mark_read(ReadTrigger::Incoming, cx);491
self.on_pins_changed(conversation_id, cx);486
}492
}487
}493
}488
AppEvent::Images(keys) => self.remeasure_images(keys, cx),494
AppEvent::Images(keys) => self.remeasure_images(keys, cx),@@ -500,7 +506,9 @@ impl ConversationView {500
self.refresh_reactor_names(cx);506
self.refresh_reactor_names(cx);501
cx.notify();507
cx.notify();502
}508
}503
AppEvent::TaskDialog | AppEvent::LocalPreviews => {}509
AppEvent::TaskDialog | AppEvent::LocalPreviews | AppEvent::Forward => {}510
AppEvent::Saved => cx.notify(),511
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),504
AppEvent::Typing => cx.notify(),512
AppEvent::Typing => cx.notify(),505
AppEvent::Scheduled => self.rebuild(false, cx),513
AppEvent::Scheduled => self.rebuild(false, cx),506
AppEvent::Outbox(conversation_id) => {514
AppEvent::Outbox(conversation_id) => {@@ -682,6 +690,11 @@ impl ConversationView {682
self.rebuild(true, cx);690
self.rebuild(true, cx);683
self.start_fetch(cx);691
self.start_fetch(cx);684
self.mark_read(ReadTrigger::Open, cx);692
self.mark_read(ReadTrigger::Open, cx);693
self.refresh_pin_previews(cx);694
if let Some(chat_id) = self.chat_id() {695
self.app696
.update(cx, |state, cx| state.refresh_pins(&chat_id, cx));697
}685
let target = self698
let target = self686
.current699
.current687
.as_ref()700
.as_ref()@@ -2550,15 +2563,32 @@ impl ConversationView {2550
.ok();2563
.ok();2551
})2564
})2552
};2565
};2566
let chat_id = self.chat_id();2567
let state = self.app.read(cx);2568
let saved = self2569
.conversation_id()2570
.is_some_and(|conversation_id| state.is_saved(&conversation_id, key));2571
let pinned = chat_id2572
.as_deref()2573
.is_some_and(|chat_id| state.is_pinned(chat_id, key));2574
let in_chat = chat_id.is_some();2553
MessageMenu {2575
MessageMenu {2554
key: key.to_owned(),2576
key: key.to_owned(),2555
react,2577
react,2556
reply: Some(action(|this, key, window, cx| {2578
reply: Some(action(|this, key, window, cx| {2557
this.begin_reply(key, window, cx)2579
this.begin_reply(key, window, cx)2558
})),2580
})),2581
forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),2582
copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),2559
copy: action(|this, key, _, cx| this.copy_text(key, cx)),2583
copy: action(|this, key, _, cx| this.copy_text(key, cx)),2584
save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),2585
saved,2586
toggle_pinned: in_chat.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),2587
pinned,2560
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),2588
edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),2561
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),2589
delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),2590
mark_unread: (in_chat && !own)2591
.then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),2562
pin,2592
pin,2563
hover,2593
hover,2564
picker: self.picker.clone(),2594
picker: self.picker.clone(),@@ -2962,6 +2992,7 @@ impl Render for ConversationView {2962
Some(current) => root.child(self.render_header(current, cx)),2992
Some(current) => root.child(self.render_header(current, cx)),2963
None => root.child(self.draft.clone()),2993
None => root.child(self.draft.clone()),2964
};2994
};2995
root = root.children(self.render_pin_banner(cx).filter(|_| !drafting));2965
let sync_failed = self2996
let sync_failed = self2966
.current2997
.current2967
.as_ref()2998
.as_ref()@@ -0,0 +1,174 @@
1
use std::rc::Rc;
2
3
use gpui_kit::*;
4
5
use super::ConversationView;
6
use crate::app_state::Selection;
7
use crate::rows::reply_excerpt;
8
use crate::views::message_actions::Action;
9
use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};
10
11
pub(super) struct PinPreview {
12
author: Option<String>,
13
text: String,
14
}
15
16
impl ConversationView {
17
pub(super) fn chat_id(&self) -> Option<String> {
18
match self.current.as_ref()?.selection {
19
Selection::Chat(ref chat_id) => Some(chat_id.clone()),
20
Selection::Channel(_) => None,
21
}
22
}
23
24
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {
25
self.pin_previews.clear();
26
self.pin_index = 0;
27
let Some(chat_id) = self.chat_id() else {
28
return;
29
};
30
self.update_pin_previews(&chat_id, cx);
31
cx.notify();
32
}
33
34
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {
35
if self.chat_id().as_deref() != Some(chat_id) {
36
return;
37
}
38
self.pin_index = 0;
39
self.update_pin_previews(chat_id, cx);
40
cx.notify();
41
}
42
43
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {
44
let state = self.app.read(cx);
45
let ids: Vec<String> = state
46
.pinned_messages(chat_id)
47
.iter()
48
.map(|pin| pin.message_id.clone())
49
.collect();
50
let records = state
51
.store
52
.messages_by_id(chat_id, &ids)
53
.unwrap_or_default();
54
self.pin_previews = records
55
.into_iter()
56
.map(|(message_id, record)| {
57
let preview = PinPreview {
58
author: record.sender_name.clone(),
59
text: reply_excerpt(&record),
60
};
61
(message_id, preview)
62
})
63
.collect();
64
let count = ids.len();
65
if self.pin_index >= count {
66
self.pin_index = 0;
67
}
68
}
69
70
fn pin_action(
71
&self,
72
view: WeakEntity<Self>,
73
run: fn(&mut Self, &mut Window, &mut Context<Self>),
74
) -> Action {
75
Rc::new(move |window, cx| {
76
view.update(cx, |this, cx| run(this, window, cx)).ok();
77
})
78
}
79
80
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
81
let chat_id = self.chat_id()?;
82
let pins = self.app.read(cx).pinned_messages(&chat_id);
83
let pin = pins.get(self.pin_index)?;
84
let preview = self.pin_previews.get(&pin.message_id);
85
let data = PinBannerData {
86
author: preview.and_then(|preview| preview.author.clone()),
87
preview: preview.map(|preview| preview.text.clone()),
88
position: self.pin_index,
89
total: pins.len(),
90
};
91
let view = cx.weak_entity();
92
let actions = PinBannerActions {
93
open: self.pin_action(view.clone(), |this, _, cx| this.open_shown_pin(cx)),
94
previous: self.pin_action(view.clone(), |this, _, cx| this.step_pin(-1, cx)),
95
next: self.pin_action(view.clone(), |this, _, cx| this.step_pin(1, cx)),
96
unpin: self.pin_action(view, |this, _, cx| this.unpin_shown_pin(cx)),
97
};
98
Some(render_pin_banner(data, actions))
99
}
100
101
fn shown_pin_id(&self, cx: &App) -> Option<String> {
102
let chat_id = self.chat_id()?;
103
self.app
104
.read(cx)
105
.pinned_messages(&chat_id)
106
.get(self.pin_index)
107
.map(|pin| pin.message_id.clone())
108
}
109
110
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {
111
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
112
return;
113
};
114
self.jump_to_message(&chat_id, &message_id, cx);
115
}
116
117
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {
118
let Some(chat_id) = self.chat_id() else {
119
return;
120
};
121
let total = self.app.read(cx).pinned_messages(&chat_id).len();
122
self.pin_index = cycle_pin(self.pin_index, total, delta);
123
cx.notify();
124
}
125
126
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {
127
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {
128
return;
129
};
130
self.app.update(cx, |state, cx| {
131
state.set_pinned(&chat_id, &message_id, false, cx)
132
});
133
}
134
135
pub(super) fn forward_message(&mut self, message_id: &str, cx: &mut Context<Self>) {
136
if let Some(conversation_id) = self.conversation_id() {
137
self.app.update(cx, |state, cx| {
138
state.request_forward(&conversation_id, message_id, cx)
139
});
140
}
141
}
142
143
pub(super) fn copy_link(&mut self, message_id: &str, cx: &mut Context<Self>) {
144
if let Some(conversation_id) = self.conversation_id() {
145
self.app.update(cx, |state, cx| {
146
state.copy_message_link(&conversation_id, message_id, cx)
147
});
148
}
149
}
150
151
pub(super) fn toggle_saved(&mut self, message_id: &str, cx: &mut Context<Self>) {
152
if let Some(conversation_id) = self.conversation_id() {
153
self.app.update(cx, |state, cx| {
154
state.toggle_saved(&conversation_id, message_id, cx)
155
});
156
}
157
}
158
159
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
160
if let Some(chat_id) = self.chat_id() {
161
self.app.update(cx, |state, cx| {
162
state.toggle_pinned(&chat_id, message_id, cx)
163
});
164
}
165
}
166
167
pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
168
if let Some(chat_id) = self.chat_id() {
169
self.app.update(cx, |state, cx| {
170
state.mark_unread_from_message(&chat_id, message_id, cx)
171
});
172
}
173
}
174
}
@@ -0,0 +1,174 @@1
use std::rc::Rc;2
3
use gpui_kit::*;4
5
use super::ConversationView;6
use crate::app_state::Selection;7
use crate::rows::reply_excerpt;8
use crate::views::message_actions::Action;9
use crate::views::pin_banner::{PinBannerActions, PinBannerData, cycle_pin, render_pin_banner};10
11
pub(super) struct PinPreview {12
author: Option<String>,13
text: String,14
}15
16
impl ConversationView {17
pub(super) fn chat_id(&self) -> Option<String> {18
match self.current.as_ref()?.selection {19
Selection::Chat(ref chat_id) => Some(chat_id.clone()),20
Selection::Channel(_) => None,21
}22
}23
24
pub(super) fn refresh_pin_previews(&mut self, cx: &mut Context<Self>) {25
self.pin_previews.clear();26
self.pin_index = 0;27
let Some(chat_id) = self.chat_id() else {28
return;29
};30
self.update_pin_previews(&chat_id, cx);31
cx.notify();32
}33
34
pub(super) fn on_pins_changed(&mut self, chat_id: &str, cx: &mut Context<Self>) {35
if self.chat_id().as_deref() != Some(chat_id) {36
return;37
}38
self.pin_index = 0;39
self.update_pin_previews(chat_id, cx);40
cx.notify();41
}42
43
fn update_pin_previews(&mut self, chat_id: &str, cx: &mut Context<Self>) {44
let state = self.app.read(cx);45
let ids: Vec<String> = state46
.pinned_messages(chat_id)47
.iter()48
.map(|pin| pin.message_id.clone())49
.collect();50
let records = state51
.store52
.messages_by_id(chat_id, &ids)53
.unwrap_or_default();54
self.pin_previews = records55
.into_iter()56
.map(|(message_id, record)| {57
let preview = PinPreview {58
author: record.sender_name.clone(),59
text: reply_excerpt(&record),60
};61
(message_id, preview)62
})63
.collect();64
let count = ids.len();65
if self.pin_index >= count {66
self.pin_index = 0;67
}68
}69
70
fn pin_action(71
&self,72
view: WeakEntity<Self>,73
run: fn(&mut Self, &mut Window, &mut Context<Self>),74
) -> Action {75
Rc::new(move |window, cx| {76
view.update(cx, |this, cx| run(this, window, cx)).ok();77
})78
}79
80
pub(super) fn render_pin_banner(&self, cx: &mut Context<Self>) -> Option<AnyElement> {81
let chat_id = self.chat_id()?;82
let pins = self.app.read(cx).pinned_messages(&chat_id);83
let pin = pins.get(self.pin_index)?;84
let preview = self.pin_previews.get(&pin.message_id);85
let data = PinBannerData {86
author: preview.and_then(|preview| preview.author.clone()),87
preview: preview.map(|preview| preview.text.clone()),88
position: self.pin_index,89
total: pins.len(),90
};91
let view = cx.weak_entity();92
let actions = PinBannerActions {93
open: self.pin_action(view.clone(), |this, _, cx| this.open_shown_pin(cx)),94
previous: self.pin_action(view.clone(), |this, _, cx| this.step_pin(-1, cx)),95
next: self.pin_action(view.clone(), |this, _, cx| this.step_pin(1, cx)),96
unpin: self.pin_action(view, |this, _, cx| this.unpin_shown_pin(cx)),97
};98
Some(render_pin_banner(data, actions))99
}100
101
fn shown_pin_id(&self, cx: &App) -> Option<String> {102
let chat_id = self.chat_id()?;103
self.app104
.read(cx)105
.pinned_messages(&chat_id)106
.get(self.pin_index)107
.map(|pin| pin.message_id.clone())108
}109
110
fn open_shown_pin(&mut self, cx: &mut Context<Self>) {111
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {112
return;113
};114
self.jump_to_message(&chat_id, &message_id, cx);115
}116
117
fn step_pin(&mut self, delta: isize, cx: &mut Context<Self>) {118
let Some(chat_id) = self.chat_id() else {119
return;120
};121
let total = self.app.read(cx).pinned_messages(&chat_id).len();122
self.pin_index = cycle_pin(self.pin_index, total, delta);123
cx.notify();124
}125
126
fn unpin_shown_pin(&mut self, cx: &mut Context<Self>) {127
let (Some(chat_id), Some(message_id)) = (self.chat_id(), self.shown_pin_id(cx)) else {128
return;129
};130
self.app.update(cx, |state, cx| {131
state.set_pinned(&chat_id, &message_id, false, cx)132
});133
}134
135
pub(super) fn forward_message(&mut self, message_id: &str, cx: &mut Context<Self>) {136
if let Some(conversation_id) = self.conversation_id() {137
self.app.update(cx, |state, cx| {138
state.request_forward(&conversation_id, message_id, cx)139
});140
}141
}142
143
pub(super) fn copy_link(&mut self, message_id: &str, cx: &mut Context<Self>) {144
if let Some(conversation_id) = self.conversation_id() {145
self.app.update(cx, |state, cx| {146
state.copy_message_link(&conversation_id, message_id, cx)147
});148
}149
}150
151
pub(super) fn toggle_saved(&mut self, message_id: &str, cx: &mut Context<Self>) {152
if let Some(conversation_id) = self.conversation_id() {153
self.app.update(cx, |state, cx| {154
state.toggle_saved(&conversation_id, message_id, cx)155
});156
}157
}158
159
pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {160
if let Some(chat_id) = self.chat_id() {161
self.app.update(cx, |state, cx| {162
state.toggle_pinned(&chat_id, message_id, cx)163
});164
}165
}166
167
pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {168
if let Some(chat_id) = self.chat_id() {169
self.app.update(cx, |state, cx| {170
state.mark_unread_from_message(&chat_id, message_id, cx)171
});172
}173
}174
}@@ -201,6 +201,10 @@ impl RenderEnv {
201
201
reaction_controls,
202
202
files,
203
203
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
204
saved: self
205
.app
206
.read(cx)
207
.is_saved(&message.conversation_id, &message.key),
204
208
}
205
209
}
206
210
@@ -201,6 +201,10 @@ impl RenderEnv {201
reaction_controls,201
reaction_controls,202
files,202
files,203
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),203
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),204
saved: self205
.app206
.read(cx)207
.is_saved(&message.conversation_id, &message.key),204
}208
}205
}209
}206
210
@@ -0,0 +1,561 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{
3
button::{Button, ButtonVariants as _},
4
h_flex,
5
input::{Input, InputEvent, InputState},
6
v_flex,
7
};
8
use gpui_kit::prelude::FluentBuilder as _;
9
use gpui_kit::*;
10
11
use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
12
use super::widgets::{icon, symbol};
13
use crate::app_state::{AppState, Selection};
14
use crate::fuzzy;
15
use crate::message_actions::ForwardSource;
16
use crate::notice::short_error;
17
use crate::runtime;
18
use crate::theme;
19
20
const MAX_RESULTS: usize = 8;
21
const CARD_WIDTH: f32 = 480.;
22
const CARD_RADIUS: f32 = 12.;
23
const CARD_PADDING: f32 = 16.;
24
const CARD_MARGIN: f32 = 32.;
25
const SECTION_GAP: f32 = 12.;
26
const BACKDROP_OPACITY: f32 = 0.55;
27
const ROW_HEIGHT: f32 = 40.;
28
const AVATAR_SIZE: f32 = 28.;
29
const PREVIEW_LINES: usize = 4;
30
const CLOSE_SIZE: f32 = 28.;
31
const FIELD_HEIGHT: f32 = 36.;
32
const BUTTON_HEIGHT: f32 = 32.;
33
const DISABLED_OPACITY: f32 = 0.4;
34
const EMPTY_PREVIEW: &str = "Attachment";
35
36
pub enum ForwardDialogEvent {
37
Close,
38
Sent { target: Selection, title: String },
39
}
40
41
pub struct ForwardDialog {
42
app: Entity<AppState>,
43
source: ForwardSource,
44
candidates: Vec<(String, Candidate)>,
45
search: Entity<InputState>,
46
comment: Entity<InputState>,
47
results: Vec<Candidate>,
48
highlighted: usize,
49
target: Option<Candidate>,
50
sending: bool,
51
error: Option<String>,
52
_subscriptions: [Subscription; 2],
53
}
54
55
impl EventEmitter<ForwardDialogEvent> for ForwardDialog {}
56
57
pub fn visible_candidates(candidates: &[(String, Candidate)], query: &str) -> Vec<Candidate> {
58
fuzzy::rank(query, candidates, MAX_RESULTS)
59
}
60
61
pub fn can_forward(target: Option<&Candidate>, sending: bool) -> bool {
62
target.is_some() && !sending
63
}
64
65
impl ForwardDialog {
66
pub fn new(
67
app: Entity<AppState>,
68
source: ForwardSource,
69
candidates: Vec<(String, Candidate)>,
70
window: &mut Window,
71
cx: &mut Context<Self>,
72
) -> Self {
73
let search =
74
cx.new(|cx| InputState::new(window, cx).placeholder("Search chats and channels"));
75
let comment =
76
cx.new(|cx| InputState::new(window, cx).placeholder("Add a message (optional)"));
77
let subscriptions = [
78
cx.subscribe_in(&search, window, Self::on_search_event),
79
cx.subscribe_in(&comment, window, Self::on_comment_event),
80
];
81
search.update(cx, |input, cx| input.focus(window, cx));
82
let results = visible_candidates(&candidates, "");
83
ForwardDialog {
84
app,
85
source,
86
candidates,
87
search,
88
comment,
89
results,
90
highlighted: 0,
91
target: None,
92
sending: false,
93
error: None,
94
_subscriptions: subscriptions,
95
}
96
}
97
98
fn on_search_event(
99
&mut self,
100
input: &Entity<InputState>,
101
event: &InputEvent,
102
window: &mut Window,
103
cx: &mut Context<Self>,
104
) {
105
match event {
106
InputEvent::Change => {
107
let query = input.read(cx).value().to_string();
108
self.results = visible_candidates(&self.candidates, &query);
109
self.highlighted = 0;
110
cx.notify();
111
}
112
InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),
113
_ => {}
114
}
115
}
116
117
fn on_comment_event(
118
&mut self,
119
_: &Entity<InputState>,
120
event: &InputEvent,
121
_: &mut Window,
122
cx: &mut Context<Self>,
123
) {
124
if matches!(event, InputEvent::PressEnter { .. }) {
125
self.send(cx);
126
}
127
}
128
129
fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
130
let Some(candidate) = self.results.get(index).cloned() else {
131
return;
132
};
133
self.highlighted = index;
134
self.target = Some(candidate);
135
self.error = None;
136
self.comment.update(cx, |input, cx| input.focus(window, cx));
137
cx.notify();
138
}
139
140
fn clear_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {
141
self.target = None;
142
self.error = None;
143
self.search.update(cx, |input, cx| input.focus(window, cx));
144
cx.notify();
145
}
146
147
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
148
match event.keystroke.key.as_str() {
149
"escape" => cx.emit(ForwardDialogEvent::Close),
150
"down" if self.target.is_none() => {
151
self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());
152
cx.notify();
153
}
154
"up" if self.target.is_none() => {
155
self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());
156
cx.notify();
157
}
158
_ => {}
159
}
160
}
161
162
fn send(&mut self, cx: &mut Context<Self>) {
163
let Some(target) = self.target.clone().filter(|_| !self.sending) else {
164
return;
165
};
166
let comment = self.comment.read(cx).value().trim().to_owned();
167
let state = self.app.read(cx);
168
if state.mode.read_only {
169
self.error = Some("Read-only mode: message not forwarded".to_owned());
170
cx.notify();
171
return;
172
}
173
let sent = ForwardDialogEvent::Sent {
174
target: target.selection.clone(),
175
title: target.title.clone(),
176
};
177
let Some(engine) = state.engine.clone() else {
178
if state.mode.demo {
179
let source = self.source.clone();
180
self.app.update(cx, |state, cx| {
181
state.forward_locally(&source, &target.selection, &comment, cx)
182
});
183
cx.emit(sent);
184
} else {
185
self.error = Some("Not connected".to_owned());
186
cx.notify();
187
}
188
return;
189
};
190
self.sending = true;
191
self.error = None;
192
let source = self.source.clone();
193
let target_id = target.selection.conversation_id().to_owned();
194
let receiver = runtime::spawn(async move {
195
engine
196
.forward_messages(
197
&source.conversation_id,
198
&target_id,
199
&[source.message_id],
200
&comment,
201
)
202
.await
203
});
204
cx.spawn(async move |this, cx| {
205
let outcome = match receiver.await {
206
Ok(Ok(_)) => Ok(()),
207
Ok(Err(error)) => Err(short_error(&error)),
208
Err(_) => Err("cancelled".to_owned()),
209
};
210
this.update(cx, |this, cx| {
211
this.sending = false;
212
match outcome {
213
Ok(()) => cx.emit(sent),
214
Err(reason) => this.error = Some(reason),
215
}
216
cx.notify();
217
})
218
.ok();
219
})
220
.detach();
221
cx.notify();
222
}
223
224
fn header(&self, cx: &mut Context<Self>) -> Div {
225
h_flex()
226
.w_full()
227
.items_center()
228
.gap(px(SECTION_GAP))
229
.child(
230
div()
231
.flex_1()
232
.text_size(px(15.))
233
.font_weight(FontWeight::SEMIBOLD)
234
.child("Forward message"),
235
)
236
.child(
237
div()
238
.id("forward-close")
239
.size(px(CLOSE_SIZE))
240
.flex_none()
241
.flex()
242
.items_center()
243
.justify_center()
244
.rounded_full()
245
.cursor_pointer()
246
.hover(|button| button.bg(theme::row_hover()))
247
.on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close)))
248
.child(symbol("close", 16., theme::text_muted())),
249
)
250
}
251
252
fn target_field(&self, cx: &mut Context<Self>) -> AnyElement {
253
let field = h_flex()
254
.w_full()
255
.h(px(FIELD_HEIGHT))
256
.px(px(10.))
257
.gap(px(8.))
258
.items_center()
259
.rounded(px(6.))
260
.bg(theme::surface())
261
.border_1()
262
.border_color(theme::border());
263
match &self.target {
264
Some(target) => field
265
.child(
266
div()
267
.flex_1()
268
.min_w_0()
269
.truncate()
270
.text_size(px(13.))
271
.child(format!("To: {}", target.title)),
272
)
273
.child(
274
div()
275
.id("forward-clear-target")
276
.size(px(20.))
277
.flex_none()
278
.flex()
279
.items_center()
280
.justify_center()
281
.rounded(px(4.))
282
.cursor_pointer()
283
.hover(|button| button.bg(theme::row_hover()))
284
.on_click(cx.listener(|this, _, window, cx| this.clear_target(window, cx)))
285
.child(icon(IconName::X, 14., theme::text_muted())),
286
)
287
.into_any_element(),
288
None => field
289
.child(icon(IconName::Search, 14., theme::text_muted()))
290
.child(
291
div()
292
.flex_1()
293
.child(Input::new(&self.search).appearance(false).bordered(false)),
294
)
295
.into_any_element(),
296
}
297
}
298
299
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {
300
let directory = &self.app.read(cx).directory;
301
let selected_id = self
302
.target
303
.as_ref()
304
.map(|target| target.selection.conversation_id().to_owned());
305
let rows: Vec<AnyElement> = self
306
.results
307
.iter()
308
.enumerate()
309
.map(|(index, candidate)| {
310
let chosen = selected_id.as_deref() == Some(candidate.selection.conversation_id());
311
let highlighted = self.target.is_none() && index == self.highlighted;
312
h_flex()
313
.id(ElementId::Name(format!("forward-target-{index}").into()))
314
.h(px(ROW_HEIGHT))
315
.flex_none()
316
.px(px(8.))
317
.gap(px(10.))
318
.items_center()
319
.rounded(px(6.))
320
.cursor_pointer()
321
.when(highlighted || chosen, |row| row.bg(theme::surface_raised()))
322
.hover(|row| row.bg(theme::row_hover()))
323
.child(candidate_avatar(
324
directory,
325
&candidate.avatar,
326
AVATAR_SIZE,
327
theme::background(),
328
))
329
.child(
330
v_flex()
331
.flex_1()
332
.min_w_0()
333
.child(
334
div()
335
.truncate()
336
.text_size(px(14.))
337
.text_color(theme::text())
338
.child(candidate.title.clone()),
339
)
340
.child(
341
div()
342
.truncate()
343
.text_size(px(12.))
344
.text_color(theme::text_muted())
345
.child(candidate.subtitle.clone()),
346
),
347
)
348
.when(chosen, |row| {
349
row.child(icon(IconName::Check, 16., theme::accent_text()))
350
})
351
.on_click(
352
cx.listener(move |this, _, window, cx| this.choose(index, window, cx)),
353
)
354
.into_any_element()
355
})
356
.collect();
357
v_flex()
358
.id("forward-targets")
359
.w_full()
360
.max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))
361
.overflow_y_scroll()
362
.children(rows)
363
}
364
365
fn send_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {
366
let button = h_flex()
367
.id("forward-send")
368
.h(px(BUTTON_HEIGHT))
369
.px(px(16.))
370
.gap(px(6.))
371
.items_center()
372
.rounded(px(6.))
373
.bg(theme::accent())
374
.text_color(theme::on_accent())
375
.text_size(px(13.))
376
.font_weight(FontWeight::SEMIBOLD)
377
.when(self.sending, |button| {
378
button.child(icon(IconName::Loader, 14., theme::on_accent()))
379
})
380
.child("Forward");
381
if enabled {
382
button
383
.cursor_pointer()
384
.hover(|button| button.bg(theme::accent_text()))
385
.on_click(cx.listener(|this, _, _, cx| this.send(cx)))
386
} else {
387
button.opacity(DISABLED_OPACITY)
388
}
389
}
390
391
fn preview(&self) -> Div {
392
let text = match self.source.text.trim() {
393
"" => EMPTY_PREVIEW.to_owned(),
394
text => text.to_owned(),
395
};
396
v_flex()
397
.w_full()
398
.px(px(10.))
399
.py(px(6.))
400
.gap(px(2.))
401
.border_l(px(3.))
402
.border_color(theme::accent())
403
.rounded_r(px(4.))
404
.bg(theme::quote_fill())
405
.child(
406
h_flex()
407
.gap(px(8.))
408
.items_baseline()
409
.child(
410
div()
411
.text_size(px(12.))
412
.font_weight(FontWeight::SEMIBOLD)
413
.text_color(theme::text_soft())
414
.child(self.source.author.clone()),
415
)
416
.child(
417
div()
418
.text_size(px(11.))
419
.text_color(theme::text_muted())
420
.child(self.source.time.clone()),
421
),
422
)
423
.child(
424
div()
425
.line_clamp(PREVIEW_LINES)
426
.text_size(px(12.5))
427
.text_color(theme::text_muted())
428
.child(text),
429
)
430
}
431
}
432
433
impl Render for ForwardDialog {
434
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
435
let enabled = can_forward(self.target.as_ref(), self.sending);
436
div()
437
.id("forward-layer")
438
.absolute()
439
.top_0()
440
.left_0()
441
.size_full()
442
.flex()
443
.items_center()
444
.justify_center()
445
.child(
446
div()
447
.id("forward-backdrop")
448
.absolute()
449
.top_0()
450
.left_0()
451
.size_full()
452
.bg(black().opacity(BACKDROP_OPACITY))
453
.occlude()
454
.on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close))),
455
)
456
.child(
457
v_flex()
458
.id("forward-card")
459
.w(px(CARD_WIDTH))
460
.max_w(relative(1.))
461
.max_h(relative(1.))
462
.m(px(CARD_MARGIN))
463
.p(px(CARD_PADDING))
464
.gap(px(SECTION_GAP))
465
.rounded(px(CARD_RADIUS))
466
.bg(theme::background())
467
.border_1()
468
.border_color(theme::border_strong())
469
.text_color(theme::text())
470
.shadow_lg()
471
.occlude()
472
.on_key_down(cx.listener(Self::on_key_down))
473
.child(self.header(cx))
474
.child(self.target_field(cx))
475
.child(self.list(cx))
476
.child(self.preview())
477
.child(Input::new(&self.comment))
478
.children(self.error.clone().map(|error| {
479
div()
480
.text_size(px(12.))
481
.text_color(theme::red_tint())
482
.child(error)
483
}))
484
.child(
485
h_flex()
486
.w_full()
487
.justify_end()
488
.gap(px(8.))
489
.child(
490
Button::new("forward-cancel")
491
.ghost()
492
.label("Cancel")
493
.on_click(cx.listener(|_, _, _, cx| {
494
cx.emit(ForwardDialogEvent::Close)
495
})),
496
)
497
.child(self.send_button(enabled, cx)),
498
),
499
)
500
}
501
}
502
503
#[cfg(test)]
504
mod tests {
505
use super::{MAX_RESULTS, can_forward, visible_candidates};
506
use crate::app_state::Selection;
507
use crate::views::switcher::{Candidate, CandidateAvatar};
508
509
fn candidates(titles: &[&str]) -> Vec<(String, Candidate)> {
510
titles
511
.iter()
512
.map(|title| {
513
(
514
(*title).to_owned(),
515
Candidate {
516
title: (*title).to_owned(),
517
subtitle: "Chat".to_owned(),
518
avatar: CandidateAvatar::Team {
519
name: (*title).to_owned(),
520
key: (*title).to_owned(),
521
},
522
selection: Selection::Chat(format!("id-{title}")),
523
},
524
)
525
})
526
.collect()
527
}
528
529
fn titles(found: &[Candidate]) -> Vec<&str> {
530
found
531
.iter()
532
.map(|candidate| candidate.title.as_str())
533
.collect()
534
}
535
536
#[test]
537
fn empty_query_keeps_the_recent_order_and_caps_the_list() {
538
let many: Vec<String> = (0..12).map(|number| format!("Chat {number:02}")).collect();
539
let names: Vec<&str> = many.iter().map(String::as_str).collect();
540
let found = visible_candidates(&candidates(&names), "");
541
assert_eq!(found.len(), MAX_RESULTS);
542
assert_eq!(titles(&found)[0], "Chat 00");
543
assert_eq!(titles(&found)[7], "Chat 07");
544
}
545
546
#[test]
547
fn a_query_keeps_only_matching_targets() {
548
let found = visible_candidates(&candidates(&["Release", "Mara", "Atlas"]), "rel");
549
assert_eq!(titles(&found), vec!["Release"]);
550
assert!(visible_candidates(&candidates(&["Release"]), "zzz").is_empty());
551
}
552
553
#[test]
554
fn forwarding_needs_a_target_and_no_send_in_flight() {
555
let all = candidates(&["Release"]);
556
let target = &all[0].1;
557
assert!(!can_forward(None, false));
558
assert!(can_forward(Some(target), false));
559
assert!(!can_forward(Some(target), true));
560
}
561
}
@@ -0,0 +1,561 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{3
button::{Button, ButtonVariants as _},4
h_flex,5
input::{Input, InputEvent, InputState},6
v_flex,7
};8
use gpui_kit::prelude::FluentBuilder as _;9
use gpui_kit::*;10
11
use super::switcher::{Candidate, candidate_avatar, clamp_highlight};12
use super::widgets::{icon, symbol};13
use crate::app_state::{AppState, Selection};14
use crate::fuzzy;15
use crate::message_actions::ForwardSource;16
use crate::notice::short_error;17
use crate::runtime;18
use crate::theme;19
20
const MAX_RESULTS: usize = 8;21
const CARD_WIDTH: f32 = 480.;22
const CARD_RADIUS: f32 = 12.;23
const CARD_PADDING: f32 = 16.;24
const CARD_MARGIN: f32 = 32.;25
const SECTION_GAP: f32 = 12.;26
const BACKDROP_OPACITY: f32 = 0.55;27
const ROW_HEIGHT: f32 = 40.;28
const AVATAR_SIZE: f32 = 28.;29
const PREVIEW_LINES: usize = 4;30
const CLOSE_SIZE: f32 = 28.;31
const FIELD_HEIGHT: f32 = 36.;32
const BUTTON_HEIGHT: f32 = 32.;33
const DISABLED_OPACITY: f32 = 0.4;34
const EMPTY_PREVIEW: &str = "Attachment";35
36
pub enum ForwardDialogEvent {37
Close,38
Sent { target: Selection, title: String },39
}40
41
pub struct ForwardDialog {42
app: Entity<AppState>,43
source: ForwardSource,44
candidates: Vec<(String, Candidate)>,45
search: Entity<InputState>,46
comment: Entity<InputState>,47
results: Vec<Candidate>,48
highlighted: usize,49
target: Option<Candidate>,50
sending: bool,51
error: Option<String>,52
_subscriptions: [Subscription; 2],53
}54
55
impl EventEmitter<ForwardDialogEvent> for ForwardDialog {}56
57
pub fn visible_candidates(candidates: &[(String, Candidate)], query: &str) -> Vec<Candidate> {58
fuzzy::rank(query, candidates, MAX_RESULTS)59
}60
61
pub fn can_forward(target: Option<&Candidate>, sending: bool) -> bool {62
target.is_some() && !sending63
}64
65
impl ForwardDialog {66
pub fn new(67
app: Entity<AppState>,68
source: ForwardSource,69
candidates: Vec<(String, Candidate)>,70
window: &mut Window,71
cx: &mut Context<Self>,72
) -> Self {73
let search =74
cx.new(|cx| InputState::new(window, cx).placeholder("Search chats and channels"));75
let comment =76
cx.new(|cx| InputState::new(window, cx).placeholder("Add a message (optional)"));77
let subscriptions = [78
cx.subscribe_in(&search, window, Self::on_search_event),79
cx.subscribe_in(&comment, window, Self::on_comment_event),80
];81
search.update(cx, |input, cx| input.focus(window, cx));82
let results = visible_candidates(&candidates, "");83
ForwardDialog {84
app,85
source,86
candidates,87
search,88
comment,89
results,90
highlighted: 0,91
target: None,92
sending: false,93
error: None,94
_subscriptions: subscriptions,95
}96
}97
98
fn on_search_event(99
&mut self,100
input: &Entity<InputState>,101
event: &InputEvent,102
window: &mut Window,103
cx: &mut Context<Self>,104
) {105
match event {106
InputEvent::Change => {107
let query = input.read(cx).value().to_string();108
self.results = visible_candidates(&self.candidates, &query);109
self.highlighted = 0;110
cx.notify();111
}112
InputEvent::PressEnter { .. } => self.choose(self.highlighted, window, cx),113
_ => {}114
}115
}116
117
fn on_comment_event(118
&mut self,119
_: &Entity<InputState>,120
event: &InputEvent,121
_: &mut Window,122
cx: &mut Context<Self>,123
) {124
if matches!(event, InputEvent::PressEnter { .. }) {125
self.send(cx);126
}127
}128
129
fn choose(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {130
let Some(candidate) = self.results.get(index).cloned() else {131
return;132
};133
self.highlighted = index;134
self.target = Some(candidate);135
self.error = None;136
self.comment.update(cx, |input, cx| input.focus(window, cx));137
cx.notify();138
}139
140
fn clear_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {141
self.target = None;142
self.error = None;143
self.search.update(cx, |input, cx| input.focus(window, cx));144
cx.notify();145
}146
147
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {148
match event.keystroke.key.as_str() {149
"escape" => cx.emit(ForwardDialogEvent::Close),150
"down" if self.target.is_none() => {151
self.highlighted = clamp_highlight(self.highlighted, 1, self.results.len());152
cx.notify();153
}154
"up" if self.target.is_none() => {155
self.highlighted = clamp_highlight(self.highlighted, -1, self.results.len());156
cx.notify();157
}158
_ => {}159
}160
}161
162
fn send(&mut self, cx: &mut Context<Self>) {163
let Some(target) = self.target.clone().filter(|_| !self.sending) else {164
return;165
};166
let comment = self.comment.read(cx).value().trim().to_owned();167
let state = self.app.read(cx);168
if state.mode.read_only {169
self.error = Some("Read-only mode: message not forwarded".to_owned());170
cx.notify();171
return;172
}173
let sent = ForwardDialogEvent::Sent {174
target: target.selection.clone(),175
title: target.title.clone(),176
};177
let Some(engine) = state.engine.clone() else {178
if state.mode.demo {179
let source = self.source.clone();180
self.app.update(cx, |state, cx| {181
state.forward_locally(&source, &target.selection, &comment, cx)182
});183
cx.emit(sent);184
} else {185
self.error = Some("Not connected".to_owned());186
cx.notify();187
}188
return;189
};190
self.sending = true;191
self.error = None;192
let source = self.source.clone();193
let target_id = target.selection.conversation_id().to_owned();194
let receiver = runtime::spawn(async move {195
engine196
.forward_messages(197
&source.conversation_id,198
&target_id,199
&[source.message_id],200
&comment,201
)202
.await203
});204
cx.spawn(async move |this, cx| {205
let outcome = match receiver.await {206
Ok(Ok(_)) => Ok(()),207
Ok(Err(error)) => Err(short_error(&error)),208
Err(_) => Err("cancelled".to_owned()),209
};210
this.update(cx, |this, cx| {211
this.sending = false;212
match outcome {213
Ok(()) => cx.emit(sent),214
Err(reason) => this.error = Some(reason),215
}216
cx.notify();217
})218
.ok();219
})220
.detach();221
cx.notify();222
}223
224
fn header(&self, cx: &mut Context<Self>) -> Div {225
h_flex()226
.w_full()227
.items_center()228
.gap(px(SECTION_GAP))229
.child(230
div()231
.flex_1()232
.text_size(px(15.))233
.font_weight(FontWeight::SEMIBOLD)234
.child("Forward message"),235
)236
.child(237
div()238
.id("forward-close")239
.size(px(CLOSE_SIZE))240
.flex_none()241
.flex()242
.items_center()243
.justify_center()244
.rounded_full()245
.cursor_pointer()246
.hover(|button| button.bg(theme::row_hover()))247
.on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close)))248
.child(symbol("close", 16., theme::text_muted())),249
)250
}251
252
fn target_field(&self, cx: &mut Context<Self>) -> AnyElement {253
let field = h_flex()254
.w_full()255
.h(px(FIELD_HEIGHT))256
.px(px(10.))257
.gap(px(8.))258
.items_center()259
.rounded(px(6.))260
.bg(theme::surface())261
.border_1()262
.border_color(theme::border());263
match &self.target {264
Some(target) => field265
.child(266
div()267
.flex_1()268
.min_w_0()269
.truncate()270
.text_size(px(13.))271
.child(format!("To: {}", target.title)),272
)273
.child(274
div()275
.id("forward-clear-target")276
.size(px(20.))277
.flex_none()278
.flex()279
.items_center()280
.justify_center()281
.rounded(px(4.))282
.cursor_pointer()283
.hover(|button| button.bg(theme::row_hover()))284
.on_click(cx.listener(|this, _, window, cx| this.clear_target(window, cx)))285
.child(icon(IconName::X, 14., theme::text_muted())),286
)287
.into_any_element(),288
None => field289
.child(icon(IconName::Search, 14., theme::text_muted()))290
.child(291
div()292
.flex_1()293
.child(Input::new(&self.search).appearance(false).bordered(false)),294
)295
.into_any_element(),296
}297
}298
299
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {300
let directory = &self.app.read(cx).directory;301
let selected_id = self302
.target303
.as_ref()304
.map(|target| target.selection.conversation_id().to_owned());305
let rows: Vec<AnyElement> = self306
.results307
.iter()308
.enumerate()309
.map(|(index, candidate)| {310
let chosen = selected_id.as_deref() == Some(candidate.selection.conversation_id());311
let highlighted = self.target.is_none() && index == self.highlighted;312
h_flex()313
.id(ElementId::Name(format!("forward-target-{index}").into()))314
.h(px(ROW_HEIGHT))315
.flex_none()316
.px(px(8.))317
.gap(px(10.))318
.items_center()319
.rounded(px(6.))320
.cursor_pointer()321
.when(highlighted || chosen, |row| row.bg(theme::surface_raised()))322
.hover(|row| row.bg(theme::row_hover()))323
.child(candidate_avatar(324
directory,325
&candidate.avatar,326
AVATAR_SIZE,327
theme::background(),328
))329
.child(330
v_flex()331
.flex_1()332
.min_w_0()333
.child(334
div()335
.truncate()336
.text_size(px(14.))337
.text_color(theme::text())338
.child(candidate.title.clone()),339
)340
.child(341
div()342
.truncate()343
.text_size(px(12.))344
.text_color(theme::text_muted())345
.child(candidate.subtitle.clone()),346
),347
)348
.when(chosen, |row| {349
row.child(icon(IconName::Check, 16., theme::accent_text()))350
})351
.on_click(352
cx.listener(move |this, _, window, cx| this.choose(index, window, cx)),353
)354
.into_any_element()355
})356
.collect();357
v_flex()358
.id("forward-targets")359
.w_full()360
.max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))361
.overflow_y_scroll()362
.children(rows)363
}364
365
fn send_button(&self, enabled: bool, cx: &mut Context<Self>) -> Stateful<Div> {366
let button = h_flex()367
.id("forward-send")368
.h(px(BUTTON_HEIGHT))369
.px(px(16.))370
.gap(px(6.))371
.items_center()372
.rounded(px(6.))373
.bg(theme::accent())374
.text_color(theme::on_accent())375
.text_size(px(13.))376
.font_weight(FontWeight::SEMIBOLD)377
.when(self.sending, |button| {378
button.child(icon(IconName::Loader, 14., theme::on_accent()))379
})380
.child("Forward");381
if enabled {382
button383
.cursor_pointer()384
.hover(|button| button.bg(theme::accent_text()))385
.on_click(cx.listener(|this, _, _, cx| this.send(cx)))386
} else {387
button.opacity(DISABLED_OPACITY)388
}389
}390
391
fn preview(&self) -> Div {392
let text = match self.source.text.trim() {393
"" => EMPTY_PREVIEW.to_owned(),394
text => text.to_owned(),395
};396
v_flex()397
.w_full()398
.px(px(10.))399
.py(px(6.))400
.gap(px(2.))401
.border_l(px(3.))402
.border_color(theme::accent())403
.rounded_r(px(4.))404
.bg(theme::quote_fill())405
.child(406
h_flex()407
.gap(px(8.))408
.items_baseline()409
.child(410
div()411
.text_size(px(12.))412
.font_weight(FontWeight::SEMIBOLD)413
.text_color(theme::text_soft())414
.child(self.source.author.clone()),415
)416
.child(417
div()418
.text_size(px(11.))419
.text_color(theme::text_muted())420
.child(self.source.time.clone()),421
),422
)423
.child(424
div()425
.line_clamp(PREVIEW_LINES)426
.text_size(px(12.5))427
.text_color(theme::text_muted())428
.child(text),429
)430
}431
}432
433
impl Render for ForwardDialog {434
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {435
let enabled = can_forward(self.target.as_ref(), self.sending);436
div()437
.id("forward-layer")438
.absolute()439
.top_0()440
.left_0()441
.size_full()442
.flex()443
.items_center()444
.justify_center()445
.child(446
div()447
.id("forward-backdrop")448
.absolute()449
.top_0()450
.left_0()451
.size_full()452
.bg(black().opacity(BACKDROP_OPACITY))453
.occlude()454
.on_click(cx.listener(|_, _, _, cx| cx.emit(ForwardDialogEvent::Close))),455
)456
.child(457
v_flex()458
.id("forward-card")459
.w(px(CARD_WIDTH))460
.max_w(relative(1.))461
.max_h(relative(1.))462
.m(px(CARD_MARGIN))463
.p(px(CARD_PADDING))464
.gap(px(SECTION_GAP))465
.rounded(px(CARD_RADIUS))466
.bg(theme::background())467
.border_1()468
.border_color(theme::border_strong())469
.text_color(theme::text())470
.shadow_lg()471
.occlude()472
.on_key_down(cx.listener(Self::on_key_down))473
.child(self.header(cx))474
.child(self.target_field(cx))475
.child(self.list(cx))476
.child(self.preview())477
.child(Input::new(&self.comment))478
.children(self.error.clone().map(|error| {479
div()480
.text_size(px(12.))481
.text_color(theme::red_tint())482
.child(error)483
}))484
.child(485
h_flex()486
.w_full()487
.justify_end()488
.gap(px(8.))489
.child(490
Button::new("forward-cancel")491
.ghost()492
.label("Cancel")493
.on_click(cx.listener(|_, _, _, cx| {494
cx.emit(ForwardDialogEvent::Close)495
})),496
)497
.child(self.send_button(enabled, cx)),498
),499
)500
}501
}502
503
#[cfg(test)]504
mod tests {505
use super::{MAX_RESULTS, can_forward, visible_candidates};506
use crate::app_state::Selection;507
use crate::views::switcher::{Candidate, CandidateAvatar};508
509
fn candidates(titles: &[&str]) -> Vec<(String, Candidate)> {510
titles511
.iter()512
.map(|title| {513
(514
(*title).to_owned(),515
Candidate {516
title: (*title).to_owned(),517
subtitle: "Chat".to_owned(),518
avatar: CandidateAvatar::Team {519
name: (*title).to_owned(),520
key: (*title).to_owned(),521
},522
selection: Selection::Chat(format!("id-{title}")),523
},524
)525
})526
.collect()527
}528
529
fn titles(found: &[Candidate]) -> Vec<&str> {530
found531
.iter()532
.map(|candidate| candidate.title.as_str())533
.collect()534
}535
536
#[test]537
fn empty_query_keeps_the_recent_order_and_caps_the_list() {538
let many: Vec<String> = (0..12).map(|number| format!("Chat {number:02}")).collect();539
let names: Vec<&str> = many.iter().map(String::as_str).collect();540
let found = visible_candidates(&candidates(&names), "");541
assert_eq!(found.len(), MAX_RESULTS);542
assert_eq!(titles(&found)[0], "Chat 00");543
assert_eq!(titles(&found)[7], "Chat 07");544
}545
546
#[test]547
fn a_query_keeps_only_matching_targets() {548
let found = visible_candidates(&candidates(&["Release", "Mara", "Atlas"]), "rel");549
assert_eq!(titles(&found), vec!["Release"]);550
assert!(visible_candidates(&candidates(&["Release"]), "zzz").is_empty());551
}552
553
#[test]554
fn forwarding_needs_a_target_and_no_send_in_flight() {555
let all = candidates(&["Release"]);556
let target = &all[0].1;557
assert!(!can_forward(None, false));558
assert!(can_forward(Some(target), false));559
assert!(!can_forward(Some(target), true));560
}561
}@@ -29,9 +29,16 @@ pub struct MessageMenu {
29
29
pub key: String,
30
30
pub react: PickHandler,
31
31
pub reply: Option<Action>,
32
pub forward: Option<Action>,
33
pub copy_link: Option<Action>,
32
34
pub copy: Action,
35
pub save: Option<Action>,
36
pub saved: bool,
37
pub toggle_pinned: Option<Action>,
38
pub pinned: bool,
33
39
pub edit: Option<Action>,
34
40
pub delete: Option<Action>,
41
pub mark_unread: Option<Action>,
35
42
pub pin: OpenChange,
36
43
pub hover: HoverChange,
37
44
pub picker: Entity<ReactionPicker>,
@@ -106,13 +113,19 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {
106
113
}
107
114
108
115
fn more_button(menu: &MessageMenu) -> AnyElement {
109
let (reply, copy, edit, delete, pin) = (
116
let (reply, forward, copy_link, copy, save, toggle_pinned, edit, delete, mark_unread, pin) = (
110
117
menu.reply.clone(),
118
menu.forward.clone(),
119
menu.copy_link.clone(),
111
120
menu.copy.clone(),
121
menu.save.clone(),
122
menu.toggle_pinned.clone(),
112
123
menu.edit.clone(),
113
124
menu.delete.clone(),
125
menu.mark_unread.clone(),
114
126
menu.pin.clone(),
115
127
);
128
let (saved, pinned) = (menu.saved, menu.pinned);
116
129
Button::new(element_id("message-more", &menu.key))
117
130
.icon(IconName::Ellipsis)
118
131
.ghost()
@@ -128,7 +141,27 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
128
141
if let Some(reply) = reply.clone() {
129
142
popup = popup.item(item("Reply with quote", IconName::Reply, reply));
130
143
}
144
if let Some(forward) = forward.clone() {
145
popup = popup.item(item("Forward", IconName::Forward, forward));
146
}
147
if let Some(copy_link) = copy_link.clone() {
148
popup = popup.item(item("Copy link", IconName::Link, copy_link));
149
}
131
150
popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));
151
if let Some(save) = save.clone() {
152
popup = popup.item(if saved {
153
item("Unsave message", IconName::BookmarkOff, save)
154
} else {
155
item("Save message", IconName::Bookmark, save)
156
});
157
}
158
if let Some(toggle_pinned) = toggle_pinned.clone() {
159
popup = popup.item(if pinned {
160
item("Unpin", IconName::PinOff, toggle_pinned)
161
} else {
162
item("Pin", IconName::Pin, toggle_pinned)
163
});
164
}
132
165
if let Some(edit) = edit.clone() {
133
166
popup = popup.item(item("Edit", IconName::Pencil, edit));
134
167
}
@@ -137,6 +170,10 @@ fn more_button(menu: &MessageMenu) -> AnyElement {
137
170
.separator()
138
171
.item(item("Delete", IconName::Trash, delete));
139
172
}
173
if let Some(mark_unread) = mark_unread.clone() {
174
let entry = item("Mark as unread", IconName::EyeOff, mark_unread);
175
popup = popup.separator().item(entry);
176
}
140
177
popup
141
178
})
142
179
.on_open_change(move |open, window, cx| pin(*open, window, cx))
@@ -29,9 +29,16 @@ pub struct MessageMenu {29
pub key: String,29
pub key: String,30
pub react: PickHandler,30
pub react: PickHandler,31
pub reply: Option<Action>,31
pub reply: Option<Action>,32
pub forward: Option<Action>,33
pub copy_link: Option<Action>,32
pub copy: Action,34
pub copy: Action,35
pub save: Option<Action>,36
pub saved: bool,37
pub toggle_pinned: Option<Action>,38
pub pinned: bool,33
pub edit: Option<Action>,39
pub edit: Option<Action>,34
pub delete: Option<Action>,40
pub delete: Option<Action>,41
pub mark_unread: Option<Action>,35
pub pin: OpenChange,42
pub pin: OpenChange,36
pub hover: HoverChange,43
pub hover: HoverChange,37
pub picker: Entity<ReactionPicker>,44
pub picker: Entity<ReactionPicker>,@@ -106,13 +113,19 @@ fn picker_button(menu: &MessageMenu) -> AnyElement {106
}113
}107
114
108
fn more_button(menu: &MessageMenu) -> AnyElement {115
fn more_button(menu: &MessageMenu) -> AnyElement {109
let (reply, copy, edit, delete, pin) = (116
let (reply, forward, copy_link, copy, save, toggle_pinned, edit, delete, mark_unread, pin) = (110
menu.reply.clone(),117
menu.reply.clone(),118
menu.forward.clone(),119
menu.copy_link.clone(),111
menu.copy.clone(),120
menu.copy.clone(),121
menu.save.clone(),122
menu.toggle_pinned.clone(),112
menu.edit.clone(),123
menu.edit.clone(),113
menu.delete.clone(),124
menu.delete.clone(),125
menu.mark_unread.clone(),114
menu.pin.clone(),126
menu.pin.clone(),115
);127
);128
let (saved, pinned) = (menu.saved, menu.pinned);116
Button::new(element_id("message-more", &menu.key))129
Button::new(element_id("message-more", &menu.key))117
.icon(IconName::Ellipsis)130
.icon(IconName::Ellipsis)118
.ghost()131
.ghost()@@ -128,7 +141,27 @@ fn more_button(menu: &MessageMenu) -> AnyElement {128
if let Some(reply) = reply.clone() {141
if let Some(reply) = reply.clone() {129
popup = popup.item(item("Reply with quote", IconName::Reply, reply));142
popup = popup.item(item("Reply with quote", IconName::Reply, reply));130
}143
}144
if let Some(forward) = forward.clone() {145
popup = popup.item(item("Forward", IconName::Forward, forward));146
}147
if let Some(copy_link) = copy_link.clone() {148
popup = popup.item(item("Copy link", IconName::Link, copy_link));149
}131
popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));150
popup = popup.item(item("Copy text", IconName::Copy, copy.clone()));151
if let Some(save) = save.clone() {152
popup = popup.item(if saved {153
item("Unsave message", IconName::BookmarkOff, save)154
} else {155
item("Save message", IconName::Bookmark, save)156
});157
}158
if let Some(toggle_pinned) = toggle_pinned.clone() {159
popup = popup.item(if pinned {160
item("Unpin", IconName::PinOff, toggle_pinned)161
} else {162
item("Pin", IconName::Pin, toggle_pinned)163
});164
}132
if let Some(edit) = edit.clone() {165
if let Some(edit) = edit.clone() {133
popup = popup.item(item("Edit", IconName::Pencil, edit));166
popup = popup.item(item("Edit", IconName::Pencil, edit));134
}167
}@@ -137,6 +170,10 @@ fn more_button(menu: &MessageMenu) -> AnyElement {137
.separator()170
.separator()138
.item(item("Delete", IconName::Trash, delete));171
.item(item("Delete", IconName::Trash, delete));139
}172
}173
if let Some(mark_unread) = mark_unread.clone() {174
let entry = item("Mark as unread", IconName::EyeOff, mark_unread);175
popup = popup.separator().item(entry);176
}140
popup177
popup141
})178
})142
.on_open_change(move |open, window, cx| pin(*open, window, cx))179
.on_open_change(move |open, window, cx| pin(*open, window, cx))@@ -1,3 +1,4 @@
1
use gpui_kit::assets::IconName;
1
2
use gpui_kit::component::{h_flex, v_flex};
2
3
use gpui_kit::prelude::FluentBuilder as _;
3
4
use gpui_kit::*;
@@ -11,7 +12,7 @@ use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11
12
use super::reaction_picker::PickHandler;
12
13
use super::reaction_pills::{ReactionControls, reaction_pills};
13
14
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
14
use super::widgets::symbol;
15
use super::widgets::{icon, symbol};
15
16
use crate::card_state::BotIdentity;
16
17
use crate::data::Directory;
17
18
use crate::render::Block;
@@ -29,6 +30,8 @@ const MAX_WIDTH_RATIO: f32 = 0.7;
29
30
const REACTION_FOOTER_HEIGHT: f32 = 24.;
30
31
const META_SIZE: f32 = 11.;
31
32
const META_CHECK_SIZE: f32 = 15.;
33
const SAVED_MARK_SIZE: f32 = 12.;
34
const FORWARDED_SIZE: f32 = 11.;
32
35
const FIGURE_SPACE_WIDTH: f32 = 7.4;
33
36
const PULSE_PERIOD: Duration = Duration::from_millis(1600);
34
37
const SKELETON_LINE_HEIGHT: f32 = 20.;
@@ -50,6 +53,7 @@ pub struct RowActions {
50
53
pub reaction_controls: Option<ReactionControls>,
51
54
pub files: Option<FileActions>,
52
55
pub highlighted: bool,
56
pub saved: bool,
53
57
}
54
58
55
59
const TOOLBAR_LIFT: f32 = 22.;
@@ -137,11 +141,15 @@ fn bubble(
137
141
})
138
142
});
139
143
let has_reactions = !row.reactions.is_empty();
144
let saved = extras.saved;
140
145
let mut content = v_flex().gap(px(6.));
146
if row.forwarded {
147
content = content.child(forwarded_header());
148
}
141
149
let padded_blocks = if has_reactions {
142
150
None
143
151
} else {
144
with_meta_room(&row.blocks, meta_room(row, own))
152
with_meta_room(&row.blocks, meta_room(row, own, saved))
145
153
};
146
154
let meta_inline = has_text(row) && padded_blocks.is_some();
147
155
if has_text(row) {
@@ -200,11 +208,11 @@ fn bubble(
200
208
.h(px(REACTION_FOOTER_HEIGHT))
201
209
.flex_none()
202
210
.items_center()
203
.child(bubble_meta(row, own)),
211
.child(bubble_meta(row, own, saved)),
204
212
),
205
213
);
206
214
} else if !meta_inline {
207
content = content.child(h_flex().justify_end().child(bubble_meta(row, own)));
215
content = content.child(h_flex().justify_end().child(bubble_meta(row, own, saved)));
208
216
}
209
217
element = element.child(content);
210
218
if meta_inline {
@@ -213,7 +221,7 @@ fn bubble(
213
221
.absolute()
214
222
.right(px(9.))
215
223
.bottom(px(5.))
216
.child(bubble_meta(row, own)),
224
.child(bubble_meta(row, own, saved)),
217
225
);
218
226
}
219
227
if let Some(menu) = extras.menu {
@@ -245,9 +253,20 @@ struct BubbleExtras {
245
253
react: Option<PickHandler>,
246
254
controls: Option<ReactionControls>,
247
255
files: Option<FileActions>,
256
saved: bool,
257
}
258
259
pub(super) fn forwarded_header() -> Div {
260
h_flex()
261
.gap(px(4.))
262
.items_center()
263
.text_size(px(FORWARDED_SIZE))
264
.text_color(theme::text_muted())
265
.child(icon(IconName::Forward, FORWARDED_SIZE, theme::text_muted()))
266
.child("Forwarded")
248
267
}
249
268
250
fn bubble_meta(row: &MessageRow, own: bool) -> Div {
269
fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {
251
270
let tint = if own {
252
271
theme::own_meta()
253
272
} else {
@@ -261,6 +280,13 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {
261
280
.italic()
262
281
.text_color(tint)
263
282
.when(row.edited, |meta| meta.child("Edited"))
283
.when(saved, |meta| {
284
meta.child(icon(
285
IconName::Bookmark,
286
SAVED_MARK_SIZE,
287
theme::accent_text(),
288
))
289
})
264
290
.child(row.time.clone())
265
291
.when(own && row.delivery == Delivery::Sending, |meta| {
266
292
meta.child(symbol("schedule", META_CHECK_SIZE, tint))
@@ -342,8 +368,11 @@ pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {
342
368
.into_any_element()
343
369
}
344
370
345
fn meta_room(row: &MessageRow, own: bool) -> usize {
371
fn meta_room(row: &MessageRow, own: bool, saved: bool) -> usize {
346
372
let mut width = 12. + row.time.chars().count() as f32 * 6.;
373
if saved {
374
width += SAVED_MARK_SIZE + 4.;
375
}
347
376
if row.edited {
348
377
width += 56.;
349
378
}
@@ -509,6 +538,7 @@ pub fn render_message_row(
509
538
reaction_controls,
510
539
files,
511
540
highlighted,
541
saved,
512
542
} = actions;
513
543
let extras = BubbleExtras {
514
544
hover: hovered,
@@ -517,6 +547,7 @@ pub fn render_message_row(
517
547
react,
518
548
controls: reaction_controls,
519
549
files,
550
saved,
520
551
};
521
552
let own = row.own;
522
553
let spacing = if row.series.has_prev {
@@ -1,3 +1,4 @@1
use gpui_kit::assets::IconName;1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::*;4
use gpui_kit::*;@@ -11,7 +12,7 @@ use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::reaction_picker::PickHandler;12
use super::reaction_picker::PickHandler;12
use super::reaction_pills::{ReactionControls, reaction_pills};13
use super::reaction_pills::{ReactionControls, reaction_pills};13
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};14
use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};14
use super::widgets::symbol;15
use super::widgets::{icon, symbol};15
use crate::card_state::BotIdentity;16
use crate::card_state::BotIdentity;16
use crate::data::Directory;17
use crate::data::Directory;17
use crate::render::Block;18
use crate::render::Block;@@ -29,6 +30,8 @@ const MAX_WIDTH_RATIO: f32 = 0.7;29
const REACTION_FOOTER_HEIGHT: f32 = 24.;30
const REACTION_FOOTER_HEIGHT: f32 = 24.;30
const META_SIZE: f32 = 11.;31
const META_SIZE: f32 = 11.;31
const META_CHECK_SIZE: f32 = 15.;32
const META_CHECK_SIZE: f32 = 15.;33
const SAVED_MARK_SIZE: f32 = 12.;34
const FORWARDED_SIZE: f32 = 11.;32
const FIGURE_SPACE_WIDTH: f32 = 7.4;35
const FIGURE_SPACE_WIDTH: f32 = 7.4;33
const PULSE_PERIOD: Duration = Duration::from_millis(1600);36
const PULSE_PERIOD: Duration = Duration::from_millis(1600);34
const SKELETON_LINE_HEIGHT: f32 = 20.;37
const SKELETON_LINE_HEIGHT: f32 = 20.;@@ -50,6 +53,7 @@ pub struct RowActions {50
pub reaction_controls: Option<ReactionControls>,53
pub reaction_controls: Option<ReactionControls>,51
pub files: Option<FileActions>,54
pub files: Option<FileActions>,52
pub highlighted: bool,55
pub highlighted: bool,56
pub saved: bool,53
}57
}54
58
55
const TOOLBAR_LIFT: f32 = 22.;59
const TOOLBAR_LIFT: f32 = 22.;@@ -137,11 +141,15 @@ fn bubble(137
})141
})138
});142
});139
let has_reactions = !row.reactions.is_empty();143
let has_reactions = !row.reactions.is_empty();144
let saved = extras.saved;140
let mut content = v_flex().gap(px(6.));145
let mut content = v_flex().gap(px(6.));146
if row.forwarded {147
content = content.child(forwarded_header());148
}141
let padded_blocks = if has_reactions {149
let padded_blocks = if has_reactions {142
None150
None143
} else {151
} else {144
with_meta_room(&row.blocks, meta_room(row, own))152
with_meta_room(&row.blocks, meta_room(row, own, saved))145
};153
};146
let meta_inline = has_text(row) && padded_blocks.is_some();154
let meta_inline = has_text(row) && padded_blocks.is_some();147
if has_text(row) {155
if has_text(row) {@@ -200,11 +208,11 @@ fn bubble(200
.h(px(REACTION_FOOTER_HEIGHT))208
.h(px(REACTION_FOOTER_HEIGHT))201
.flex_none()209
.flex_none()202
.items_center()210
.items_center()203
.child(bubble_meta(row, own)),211
.child(bubble_meta(row, own, saved)),204
),212
),205
);213
);206
} else if !meta_inline {214
} else if !meta_inline {207
content = content.child(h_flex().justify_end().child(bubble_meta(row, own)));215
content = content.child(h_flex().justify_end().child(bubble_meta(row, own, saved)));208
}216
}209
element = element.child(content);217
element = element.child(content);210
if meta_inline {218
if meta_inline {@@ -213,7 +221,7 @@ fn bubble(213
.absolute()221
.absolute()214
.right(px(9.))222
.right(px(9.))215
.bottom(px(5.))223
.bottom(px(5.))216
.child(bubble_meta(row, own)),224
.child(bubble_meta(row, own, saved)),217
);225
);218
}226
}219
if let Some(menu) = extras.menu {227
if let Some(menu) = extras.menu {@@ -245,9 +253,20 @@ struct BubbleExtras {245
react: Option<PickHandler>,253
react: Option<PickHandler>,246
controls: Option<ReactionControls>,254
controls: Option<ReactionControls>,247
files: Option<FileActions>,255
files: Option<FileActions>,256
saved: bool,257
}258
259
pub(super) fn forwarded_header() -> Div {260
h_flex()261
.gap(px(4.))262
.items_center()263
.text_size(px(FORWARDED_SIZE))264
.text_color(theme::text_muted())265
.child(icon(IconName::Forward, FORWARDED_SIZE, theme::text_muted()))266
.child("Forwarded")248
}267
}249
268
250
fn bubble_meta(row: &MessageRow, own: bool) -> Div {269
fn bubble_meta(row: &MessageRow, own: bool, saved: bool) -> Div {251
let tint = if own {270
let tint = if own {252
theme::own_meta()271
theme::own_meta()253
} else {272
} else {@@ -261,6 +280,13 @@ fn bubble_meta(row: &MessageRow, own: bool) -> Div {261
.italic()280
.italic()262
.text_color(tint)281
.text_color(tint)263
.when(row.edited, |meta| meta.child("Edited"))282
.when(row.edited, |meta| meta.child("Edited"))283
.when(saved, |meta| {284
meta.child(icon(285
IconName::Bookmark,286
SAVED_MARK_SIZE,287
theme::accent_text(),288
))289
})264
.child(row.time.clone())290
.child(row.time.clone())265
.when(own && row.delivery == Delivery::Sending, |meta| {291
.when(own && row.delivery == Delivery::Sending, |meta| {266
meta.child(symbol("schedule", META_CHECK_SIZE, tint))292
meta.child(symbol("schedule", META_CHECK_SIZE, tint))@@ -342,8 +368,11 @@ pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {342
.into_any_element()368
.into_any_element()343
}369
}344
370
345
fn meta_room(row: &MessageRow, own: bool) -> usize {371
fn meta_room(row: &MessageRow, own: bool, saved: bool) -> usize {346
let mut width = 12. + row.time.chars().count() as f32 * 6.;372
let mut width = 12. + row.time.chars().count() as f32 * 6.;373
if saved {374
width += SAVED_MARK_SIZE + 4.;375
}347
if row.edited {376
if row.edited {348
width += 56.;377
width += 56.;349
}378
}@@ -509,6 +538,7 @@ pub fn render_message_row(509
reaction_controls,538
reaction_controls,510
files,539
files,511
highlighted,540
highlighted,541
saved,512
} = actions;542
} = actions;513
let extras = BubbleExtras {543
let extras = BubbleExtras {514
hover: hovered,544
hover: hovered,@@ -517,6 +547,7 @@ pub fn render_message_row(517
react,547
react,518
controls: reaction_controls,548
controls: reaction_controls,519
files,549
files,550
saved,520
};551
};521
let own = row.own;552
let own = row.own;522
let spacing = if row.series.has_prev {553
let spacing = if row.series.has_prev {@@ -10,14 +10,17 @@ pub mod dialog_overlay;
10
10
pub mod draft_style;
11
11
pub mod emoji_popup;
12
12
pub mod format_toolbar;
13
pub mod forward_dialog;
13
14
pub mod link_preview;
14
15
pub mod fun_picker;
15
16
pub mod message_actions;
16
17
pub mod message_row;
17
18
pub mod new_chat;
19
pub mod pin_banner;
18
20
pub mod post_card;
19
21
pub mod reaction_picker;
20
22
pub mod reaction_pills;
23
pub mod saved_panel;
21
24
pub mod scheduled_toolbar;
22
25
pub mod shell;
23
26
pub mod sidebar;
@@ -10,14 +10,17 @@ pub mod dialog_overlay;10
pub mod draft_style;10
pub mod draft_style;11
pub mod emoji_popup;11
pub mod emoji_popup;12
pub mod format_toolbar;12
pub mod format_toolbar;13
pub mod forward_dialog;13
pub mod link_preview;14
pub mod link_preview;14
pub mod fun_picker;15
pub mod fun_picker;15
pub mod message_actions;16
pub mod message_actions;16
pub mod message_row;17
pub mod message_row;17
pub mod new_chat;18
pub mod new_chat;19
pub mod pin_banner;18
pub mod post_card;20
pub mod post_card;19
pub mod reaction_picker;21
pub mod reaction_picker;20
pub mod reaction_pills;22
pub mod reaction_pills;23
pub mod saved_panel;21
pub mod scheduled_toolbar;24
pub mod scheduled_toolbar;22
pub mod shell;25
pub mod shell;23
pub mod sidebar;26
pub mod sidebar;@@ -0,0 +1,157 @@
1
use gpui_kit::assets::IconName;
2
use gpui_kit::component::{h_flex, tooltip::Tooltip};
3
use gpui_kit::prelude::FluentBuilder as _;
4
use gpui_kit::*;
5
6
use super::message_actions::Action;
7
use super::widgets::icon;
8
use crate::theme;
9
10
const BANNER_HEIGHT: f32 = 40.;
11
const BANNER_PADDING: f32 = 20.;
12
const BUTTON_SIZE: f32 = 24.;
13
const FALLBACK_PREVIEW: &str = "Pinned message";
14
15
pub struct PinBannerData {
16
pub author: Option<String>,
17
pub preview: Option<String>,
18
pub position: usize,
19
pub total: usize,
20
}
21
22
pub struct PinBannerActions {
23
pub open: Action,
24
pub previous: Action,
25
pub next: Action,
26
pub unpin: Action,
27
}
28
29
pub fn cycle_pin(index: usize, length: usize, delta: isize) -> usize {
30
if length == 0 {
31
return 0;
32
}
33
(index as isize + delta).rem_euclid(length as isize) as usize
34
}
35
36
pub fn position_label(position: usize, total: usize) -> String {
37
format!("{} of {}", position + 1, total)
38
}
39
40
fn icon_button(id: &'static str, glyph: IconName, action: Action) -> Stateful<Div> {
41
div()
42
.id(id)
43
.size(px(BUTTON_SIZE))
44
.flex()
45
.flex_none()
46
.items_center()
47
.justify_center()
48
.rounded(px(6.))
49
.cursor_pointer()
50
.hover(|button| button.bg(theme::surface_raised()))
51
.child(icon(glyph, 14., theme::text_muted()))
52
.on_click(move |_, window, cx| {
53
cx.stop_propagation();
54
action(window, cx);
55
})
56
}
57
58
pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyElement {
59
let PinBannerData {
60
author,
61
preview,
62
position,
63
total,
64
} = data;
65
let PinBannerActions {
66
open,
67
previous,
68
next,
69
unpin,
70
} = actions;
71
h_flex()
72
.id("pin-banner")
73
.group("pin-banner")
74
.w_full()
75
.h(px(BANNER_HEIGHT))
76
.flex_none()
77
.px(px(BANNER_PADDING))
78
.gap(px(8.))
79
.items_center()
80
.bg(theme::surface())
81
.border_b_1()
82
.border_color(theme::border())
83
.cursor_pointer()
84
.hover(|banner| banner.bg(theme::surface_raised()))
85
.on_click(move |_, window, cx| open(window, cx))
86
.child(icon(IconName::Pin, 14., theme::accent_text()))
87
.child(
88
div()
89
.flex_none()
90
.text_size(px(12.))
91
.text_color(theme::text_muted())
92
.child("Pinned"),
93
)
94
.when_some(author, |banner, author| {
95
banner.child(
96
div()
97
.flex_none()
98
.text_size(px(13.))
99
.font_weight(FontWeight::SEMIBOLD)
100
.text_color(theme::text())
101
.child(author),
102
)
103
})
104
.child(
105
div()
106
.flex_1()
107
.min_w_0()
108
.truncate()
109
.text_size(px(13.))
110
.text_color(theme::text_soft())
111
.child(preview.unwrap_or_else(|| FALLBACK_PREVIEW.to_owned())),
112
)
113
.when(total > 1, |banner| {
114
banner
115
.child(
116
div()
117
.flex_none()
118
.text_size(px(12.))
119
.text_color(theme::text_muted())
120
.child(position_label(position, total)),
121
)
122
.child(icon_button("pin-previous", IconName::ChevronUp, previous))
123
.child(icon_button("pin-next", IconName::ChevronDown, next))
124
})
125
.child(
126
icon_button("pin-unpin", IconName::X, unpin)
127
.opacity(0.)
128
.group_hover("pin-banner", |button| button.opacity(1.))
129
.tooltip(|window, cx| Tooltip::new("Unpin for everyone").build(window, cx)),
130
)
131
.into_any_element()
132
}
133
134
#[cfg(test)]
135
mod tests {
136
use super::{cycle_pin, position_label};
137
138
#[test]
139
fn cycling_wraps_around_both_ends() {
140
assert_eq!(cycle_pin(0, 3, 1), 1);
141
assert_eq!(cycle_pin(2, 3, 1), 0);
142
assert_eq!(cycle_pin(0, 3, -1), 2);
143
assert_eq!(cycle_pin(1, 3, -1), 0);
144
}
145
146
#[test]
147
fn cycling_an_empty_or_single_list_stays_put() {
148
assert_eq!(cycle_pin(0, 0, 1), 0);
149
assert_eq!(cycle_pin(0, 1, 1), 0);
150
assert_eq!(cycle_pin(0, 1, -1), 0);
151
}
152
153
#[test]
154
fn position_is_one_based() {
155
assert_eq!(position_label(0, 3), "1 of 3");
156
}
157
}
@@ -0,0 +1,157 @@1
use gpui_kit::assets::IconName;2
use gpui_kit::component::{h_flex, tooltip::Tooltip};3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;5
6
use super::message_actions::Action;7
use super::widgets::icon;8
use crate::theme;9
10
const BANNER_HEIGHT: f32 = 40.;11
const BANNER_PADDING: f32 = 20.;12
const BUTTON_SIZE: f32 = 24.;13
const FALLBACK_PREVIEW: &str = "Pinned message";14
15
pub struct PinBannerData {16
pub author: Option<String>,17
pub preview: Option<String>,18
pub position: usize,19
pub total: usize,20
}21
22
pub struct PinBannerActions {23
pub open: Action,24
pub previous: Action,25
pub next: Action,26
pub unpin: Action,27
}28
29
pub fn cycle_pin(index: usize, length: usize, delta: isize) -> usize {30
if length == 0 {31
return 0;32
}33
(index as isize + delta).rem_euclid(length as isize) as usize34
}35
36
pub fn position_label(position: usize, total: usize) -> String {37
format!("{} of {}", position + 1, total)38
}39
40
fn icon_button(id: &'static str, glyph: IconName, action: Action) -> Stateful<Div> {41
div()42
.id(id)43
.size(px(BUTTON_SIZE))44
.flex()45
.flex_none()46
.items_center()47
.justify_center()48
.rounded(px(6.))49
.cursor_pointer()50
.hover(|button| button.bg(theme::surface_raised()))51
.child(icon(glyph, 14., theme::text_muted()))52
.on_click(move |_, window, cx| {53
cx.stop_propagation();54
action(window, cx);55
})56
}57
58
pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyElement {59
let PinBannerData {60
author,61
preview,62
position,63
total,64
} = data;65
let PinBannerActions {66
open,67
previous,68
next,69
unpin,70
} = actions;71
h_flex()72
.id("pin-banner")73
.group("pin-banner")74
.w_full()75
.h(px(BANNER_HEIGHT))76
.flex_none()77
.px(px(BANNER_PADDING))78
.gap(px(8.))79
.items_center()80
.bg(theme::surface())81
.border_b_1()82
.border_color(theme::border())83
.cursor_pointer()84
.hover(|banner| banner.bg(theme::surface_raised()))85
.on_click(move |_, window, cx| open(window, cx))86
.child(icon(IconName::Pin, 14., theme::accent_text()))87
.child(88
div()89
.flex_none()90
.text_size(px(12.))91
.text_color(theme::text_muted())92
.child("Pinned"),93
)94
.when_some(author, |banner, author| {95
banner.child(96
div()97
.flex_none()98
.text_size(px(13.))99
.font_weight(FontWeight::SEMIBOLD)100
.text_color(theme::text())101
.child(author),102
)103
})104
.child(105
div()106
.flex_1()107
.min_w_0()108
.truncate()109
.text_size(px(13.))110
.text_color(theme::text_soft())111
.child(preview.unwrap_or_else(|| FALLBACK_PREVIEW.to_owned())),112
)113
.when(total > 1, |banner| {114
banner115
.child(116
div()117
.flex_none()118
.text_size(px(12.))119
.text_color(theme::text_muted())120
.child(position_label(position, total)),121
)122
.child(icon_button("pin-previous", IconName::ChevronUp, previous))123
.child(icon_button("pin-next", IconName::ChevronDown, next))124
})125
.child(126
icon_button("pin-unpin", IconName::X, unpin)127
.opacity(0.)128
.group_hover("pin-banner", |button| button.opacity(1.))129
.tooltip(|window, cx| Tooltip::new("Unpin for everyone").build(window, cx)),130
)131
.into_any_element()132
}133
134
#[cfg(test)]135
mod tests {136
use super::{cycle_pin, position_label};137
138
#[test]139
fn cycling_wraps_around_both_ends() {140
assert_eq!(cycle_pin(0, 3, 1), 1);141
assert_eq!(cycle_pin(2, 3, 1), 0);142
assert_eq!(cycle_pin(0, 3, -1), 2);143
assert_eq!(cycle_pin(1, 3, -1), 0);144
}145
146
#[test]147
fn cycling_an_empty_or_single_list_stays_put() {148
assert_eq!(cycle_pin(0, 0, 1), 0);149
assert_eq!(cycle_pin(0, 1, 1), 0);150
assert_eq!(cycle_pin(0, 1, -1), 0);151
}152
153
#[test]154
fn position_is_one_based() {155
assert_eq!(position_label(0, 3), "1 of 3");156
}157
}@@ -8,7 +8,7 @@ use super::attachments::{attachments_view, message_body};
8
8
use super::avatar::{bot_avatar, person_avatar};
9
9
use super::link_preview::link_preview_card;
10
10
use super::message_actions::message_toolbar;
11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, has_text};
11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
12
12
use super::reaction_pills::reaction_pills;
13
13
use super::scheduled_toolbar::scheduled_toolbar;
14
14
use super::widgets::{icon, symbol};
@@ -72,6 +72,9 @@ fn message_content(
72
72
.child(DELETED_PREVIEW),
73
73
);
74
74
}
75
if row.forwarded {
76
content = content.child(forwarded_header());
77
}
75
78
if has_text(row) {
76
79
content = content.child(
77
80
v_flex()
@@ -127,7 +130,7 @@ fn message_content(
127
130
content
128
131
}
129
132
130
fn message_header(row: &MessageRow, author: String) -> Div {
133
fn message_header(row: &MessageRow, author: String, saved: bool) -> Div {
131
134
h_flex()
132
135
.gap(px(6.))
133
136
.items_center()
@@ -145,6 +148,9 @@ fn message_header(row: &MessageRow, author: String) -> Div {
145
148
.child(row.time.clone()),
146
149
)
147
150
.when(row.edited, |line| line.child(edited_marker()))
151
.when(saved, |line| {
152
line.child(icon(IconName::Bookmark, 12., theme::accent_text()))
153
})
148
154
.when(row.delivery == Delivery::Sending, |line| {
149
155
line.child(symbol("schedule", 13., theme::text_muted()))
150
156
})
@@ -172,6 +178,7 @@ fn message_block(
172
178
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),
173
179
};
174
180
let content = message_content(row, index, directory, &actions, cx);
181
let saved = actions.saved;
175
182
let RowActions {
176
183
delivery,
177
184
reply,
@@ -186,7 +193,7 @@ fn message_block(
186
193
.flex_1()
187
194
.min_w_0()
188
195
.gap(px(6.))
189
.child(message_header(row, author))
196
.child(message_header(row, author, saved))
190
197
.when_some(
191
198
row.subject.clone().filter(|_| role == Role::Root),
192
199
|column, subject| {
@@ -8,7 +8,7 @@ use super::attachments::{attachments_view, message_body};8
use super::avatar::{bot_avatar, person_avatar};8
use super::avatar::{bot_avatar, person_avatar};9
use super::link_preview::link_preview_card;9
use super::link_preview::link_preview_card;10
use super::message_actions::message_toolbar;10
use super::message_actions::message_toolbar;11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, has_text};11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};12
use super::reaction_pills::reaction_pills;12
use super::reaction_pills::reaction_pills;13
use super::scheduled_toolbar::scheduled_toolbar;13
use super::scheduled_toolbar::scheduled_toolbar;14
use super::widgets::{icon, symbol};14
use super::widgets::{icon, symbol};@@ -72,6 +72,9 @@ fn message_content(72
.child(DELETED_PREVIEW),72
.child(DELETED_PREVIEW),73
);73
);74
}74
}75
if row.forwarded {76
content = content.child(forwarded_header());77
}75
if has_text(row) {78
if has_text(row) {76
content = content.child(79
content = content.child(77
v_flex()80
v_flex()@@ -127,7 +130,7 @@ fn message_content(127
content130
content128
}131
}129
132
130
fn message_header(row: &MessageRow, author: String) -> Div {133
fn message_header(row: &MessageRow, author: String, saved: bool) -> Div {131
h_flex()134
h_flex()132
.gap(px(6.))135
.gap(px(6.))133
.items_center()136
.items_center()@@ -145,6 +148,9 @@ fn message_header(row: &MessageRow, author: String) -> Div {145
.child(row.time.clone()),148
.child(row.time.clone()),146
)149
)147
.when(row.edited, |line| line.child(edited_marker()))150
.when(row.edited, |line| line.child(edited_marker()))151
.when(saved, |line| {152
line.child(icon(IconName::Bookmark, 12., theme::accent_text()))153
})148
.when(row.delivery == Delivery::Sending, |line| {154
.when(row.delivery == Delivery::Sending, |line| {149
line.child(symbol("schedule", 13., theme::text_muted()))155
line.child(symbol("schedule", 13., theme::text_muted()))150
})156
})@@ -172,6 +178,7 @@ fn message_block(172
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),178
None => person_avatar(directory, row.sender_id.as_deref(), &row.author, size),173
};179
};174
let content = message_content(row, index, directory, &actions, cx);180
let content = message_content(row, index, directory, &actions, cx);181
let saved = actions.saved;175
let RowActions {182
let RowActions {176
delivery,183
delivery,177
reply,184
reply,@@ -186,7 +193,7 @@ fn message_block(186
.flex_1()193
.flex_1()187
.min_w_0()194
.min_w_0()188
.gap(px(6.))195
.gap(px(6.))189
.child(message_header(row, author))196
.child(message_header(row, author, saved))190
.when_some(197
.when_some(191
row.subject.clone().filter(|_| role == Role::Root),198
row.subject.clone().filter(|_| role == Role::Root),192
|column, subject| {199
|column, subject| {@@ -0,0 +1,289 @@
1
use chrono::{DateTime, Local, Offset};
2
use gpui_kit::assets::IconName;
3
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
4
use gpui_kit::*;
5
use teams_core::SavedMessage;
6
7
use super::avatar::person_avatar;
8
use super::title_bar::TITLE_BAR_HEIGHT;
9
use super::widgets::icon;
10
use crate::app_state::{AppState, selection_title};
11
use crate::format;
12
use crate::notify::selection_for;
13
use crate::theme;
14
15
const PANEL_WIDTH: f32 = 420.;
16
const PANEL_MAX_HEIGHT_RATIO: f32 = 0.7;
17
const PANEL_MARGIN: f32 = 8.;
18
const AVATAR_SIZE: f32 = 32.;
19
const BUTTON_SIZE: f32 = 24.;
20
const PREVIEW_LINES: usize = 2;
21
const EMPTY_TEXT: &str = "No saved messages. Use Save message in the ... menu of a message.";
22
const UNKNOWN_AUTHOR: &str = "Unknown";
23
24
pub enum SavedPanelEvent {
25
Close,
26
Open {
27
conversation_id: String,
28
message_id: String,
29
},
30
}
31
32
pub struct SavedPanel {
33
app: Entity<AppState>,
34
focus_handle: FocusHandle,
35
scroll: ScrollHandle,
36
_observation: Subscription,
37
}
38
39
impl EventEmitter<SavedPanelEvent> for SavedPanel {}
40
41
pub fn count_label(count: usize) -> String {
42
match count {
43
0 => String::new(),
44
count => count.to_string(),
45
}
46
}
47
48
impl SavedPanel {
49
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
50
let focus_handle = cx.focus_handle();
51
window.focus(&focus_handle, cx);
52
let observation = cx.observe(&app, |_, _, cx| cx.notify());
53
app.update(cx, |state, cx| state.refresh_saved(cx));
54
SavedPanel {
55
app,
56
focus_handle,
57
scroll: ScrollHandle::new(),
58
_observation: observation,
59
}
60
}
61
62
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
63
if event.keystroke.key == "escape" {
64
cx.emit(SavedPanelEvent::Close);
65
}
66
}
67
68
fn header(&self, count: usize) -> Div {
69
h_flex()
70
.px(px(12.))
71
.pt(px(10.))
72
.pb(px(8.))
73
.gap(px(8.))
74
.items_center()
75
.border_b_1()
76
.border_color(theme::border())
77
.child(
78
div()
79
.text_size(px(15.))
80
.font_weight(FontWeight::SEMIBOLD)
81
.text_color(theme::text())
82
.child("Saved"),
83
)
84
.child(
85
div()
86
.text_size(px(12.))
87
.text_color(theme::text_muted())
88
.child(count_label(count)),
89
)
90
}
91
92
fn row(
93
&self,
94
item: &SavedMessage,
95
index: usize,
96
title: String,
97
panel: Entity<SavedPanel>,
98
cx: &App,
99
) -> AnyElement {
100
let app = self.app.clone();
101
let state = self.app.read(cx);
102
let now = Local::now();
103
let author = item.author_name.as_deref().unwrap_or(UNKNOWN_AUTHOR);
104
let group = SharedString::from(format!("saved-row-group-{index}"));
105
let (conversation_id, message_id) = (item.conversation_id.clone(), item.message_id.clone());
106
let unsave_item = item.clone();
107
h_flex()
108
.id(ElementId::Name(format!("saved-row-{index}").into()))
109
.group(group.clone())
110
.mx(px(6.))
111
.px(px(6.))
112
.py(px(8.))
113
.gap(px(10.))
114
.items_start()
115
.rounded(px(6.))
116
.cursor_pointer()
117
.hover(|row| row.bg(theme::row_hover()))
118
.child(div().flex_none().size(px(AVATAR_SIZE)).child(person_avatar(
119
&state.directory,
120
item.author_id.as_deref(),
121
author,
122
AVATAR_SIZE,
123
)))
124
.child(
125
v_flex()
126
.flex_1()
127
.min_w_0()
128
.gap(px(2.))
129
.child(
130
h_flex()
131
.gap(px(6.))
132
.items_baseline()
133
.child(
134
div()
135
.flex_none()
136
.text_size(px(13.))
137
.font_weight(FontWeight::SEMIBOLD)
138
.text_color(theme::text())
139
.child(author.to_owned()),
140
)
141
.child(
142
div()
143
.min_w_0()
144
.truncate()
145
.text_size(px(12.))
146
.text_color(theme::text_muted())
147
.child(title),
148
),
149
)
150
.child(
151
div()
152
.line_clamp(PREVIEW_LINES)
153
.text_size(px(12.5))
154
.text_color(theme::text_soft())
155
.child(item.preview.clone()),
156
),
157
)
158
.child(
159
v_flex()
160
.flex_none()
161
.items_end()
162
.gap(px(2.))
163
.child(
164
div()
165
.text_size(px(11.))
166
.text_color(theme::text_muted())
167
.child(saved_time(item.saved_at, now)),
168
)
169
.child(
170
div()
171
.id(ElementId::Name(format!("saved-unsave-{index}").into()))
172
.size(px(BUTTON_SIZE))
173
.flex()
174
.flex_none()
175
.items_center()
176
.justify_center()
177
.rounded(px(6.))
178
.cursor_pointer()
179
.opacity(0.)
180
.group_hover(group, |button| button.opacity(1.))
181
.hover(|button| button.bg(theme::border_strong()))
182
.child(icon(IconName::BookmarkOff, 14., theme::text_muted()))
183
.tooltip(|window, cx| Tooltip::new("Unsave").build(window, cx))
184
.on_click(move |_, _, cx| {
185
cx.stop_propagation();
186
let entry = unsave_item.clone();
187
app.update(cx, |state, cx| state.set_saved(entry, false, cx));
188
}),
189
),
190
)
191
.on_click(move |_, _, cx| {
192
let event = SavedPanelEvent::Open {
193
conversation_id: conversation_id.clone(),
194
message_id: message_id.clone(),
195
};
196
panel.update(cx, |_, cx| cx.emit(event));
197
})
198
.into_any_element()
199
}
200
}
201
202
fn saved_time(saved_at: DateTime<chrono::Utc>, now: DateTime<Local>) -> String {
203
format::list_time_label(saved_at, now.date_naive(), now.offset().fix())
204
}
205
206
impl Render for SavedPanel {
207
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
208
let panel = cx.entity();
209
let state = self.app.read(cx);
210
let items = state.saved.items().to_vec();
211
let mut rows: Vec<AnyElement> = items
212
.iter()
213
.enumerate()
214
.map(|(index, item)| {
215
let title = selection_for(&state.sidebar, &item.conversation_id)
216
.map(|selection| selection_title(&state.sidebar, &selection))
217
.or_else(|| item.topic.clone())
218
.unwrap_or_default();
219
self.row(item, index, title, panel.clone(), cx)
220
})
221
.collect();
222
if rows.is_empty() {
223
rows.push(
224
div()
225
.py(px(32.))
226
.px(px(24.))
227
.flex()
228
.justify_center()
229
.text_center()
230
.text_size(px(13.))
231
.text_color(theme::text_muted())
232
.child(EMPTY_TEXT)
233
.into_any_element(),
234
);
235
}
236
let max_height = f32::from(window.viewport_size().height) * PANEL_MAX_HEIGHT_RATIO;
237
div()
238
.id("saved-layer")
239
.absolute()
240
.top(px(TITLE_BAR_HEIGHT))
241
.left_0()
242
.right_0()
243
.bottom_0()
244
.occlude()
245
.flex()
246
.justify_end()
247
.items_start()
248
.p(px(PANEL_MARGIN))
249
.on_click(cx.listener(|_, _, _, cx| cx.emit(SavedPanelEvent::Close)))
250
.child(
251
v_flex()
252
.id("saved-card")
253
.track_focus(&self.focus_handle)
254
.w(px(PANEL_WIDTH))
255
.max_h(px(max_height))
256
.rounded(px(10.))
257
.border_1()
258
.border_color(theme::border_strong())
259
.bg(theme::surface())
260
.shadow_lg()
261
.overflow_hidden()
262
.occlude()
263
.on_click(|_, _, cx| cx.stop_propagation())
264
.on_key_down(cx.listener(Self::on_key_down))
265
.child(self.header(items.len()))
266
.child(
267
v_flex()
268
.id("saved-list")
269
.flex_1()
270
.min_h_0()
271
.py(px(4.))
272
.overflow_y_scroll()
273
.track_scroll(&self.scroll)
274
.children(rows),
275
),
276
)
277
}
278
}
279
280
#[cfg(test)]
281
mod tests {
282
use super::count_label;
283
284
#[test]
285
fn the_header_count_is_hidden_when_nothing_is_saved() {
286
assert_eq!(count_label(0), "");
287
assert_eq!(count_label(2), "2");
288
}
289
}
@@ -0,0 +1,289 @@1
use chrono::{DateTime, Local, Offset};2
use gpui_kit::assets::IconName;3
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};4
use gpui_kit::*;5
use teams_core::SavedMessage;6
7
use super::avatar::person_avatar;8
use super::title_bar::TITLE_BAR_HEIGHT;9
use super::widgets::icon;10
use crate::app_state::{AppState, selection_title};11
use crate::format;12
use crate::notify::selection_for;13
use crate::theme;14
15
const PANEL_WIDTH: f32 = 420.;16
const PANEL_MAX_HEIGHT_RATIO: f32 = 0.7;17
const PANEL_MARGIN: f32 = 8.;18
const AVATAR_SIZE: f32 = 32.;19
const BUTTON_SIZE: f32 = 24.;20
const PREVIEW_LINES: usize = 2;21
const EMPTY_TEXT: &str = "No saved messages. Use Save message in the ... menu of a message.";22
const UNKNOWN_AUTHOR: &str = "Unknown";23
24
pub enum SavedPanelEvent {25
Close,26
Open {27
conversation_id: String,28
message_id: String,29
},30
}31
32
pub struct SavedPanel {33
app: Entity<AppState>,34
focus_handle: FocusHandle,35
scroll: ScrollHandle,36
_observation: Subscription,37
}38
39
impl EventEmitter<SavedPanelEvent> for SavedPanel {}40
41
pub fn count_label(count: usize) -> String {42
match count {43
0 => String::new(),44
count => count.to_string(),45
}46
}47
48
impl SavedPanel {49
pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {50
let focus_handle = cx.focus_handle();51
window.focus(&focus_handle, cx);52
let observation = cx.observe(&app, |_, _, cx| cx.notify());53
app.update(cx, |state, cx| state.refresh_saved(cx));54
SavedPanel {55
app,56
focus_handle,57
scroll: ScrollHandle::new(),58
_observation: observation,59
}60
}61
62
fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {63
if event.keystroke.key == "escape" {64
cx.emit(SavedPanelEvent::Close);65
}66
}67
68
fn header(&self, count: usize) -> Div {69
h_flex()70
.px(px(12.))71
.pt(px(10.))72
.pb(px(8.))73
.gap(px(8.))74
.items_center()75
.border_b_1()76
.border_color(theme::border())77
.child(78
div()79
.text_size(px(15.))80
.font_weight(FontWeight::SEMIBOLD)81
.text_color(theme::text())82
.child("Saved"),83
)84
.child(85
div()86
.text_size(px(12.))87
.text_color(theme::text_muted())88
.child(count_label(count)),89
)90
}91
92
fn row(93
&self,94
item: &SavedMessage,95
index: usize,96
title: String,97
panel: Entity<SavedPanel>,98
cx: &App,99
) -> AnyElement {100
let app = self.app.clone();101
let state = self.app.read(cx);102
let now = Local::now();103
let author = item.author_name.as_deref().unwrap_or(UNKNOWN_AUTHOR);104
let group = SharedString::from(format!("saved-row-group-{index}"));105
let (conversation_id, message_id) = (item.conversation_id.clone(), item.message_id.clone());106
let unsave_item = item.clone();107
h_flex()108
.id(ElementId::Name(format!("saved-row-{index}").into()))109
.group(group.clone())110
.mx(px(6.))111
.px(px(6.))112
.py(px(8.))113
.gap(px(10.))114
.items_start()115
.rounded(px(6.))116
.cursor_pointer()117
.hover(|row| row.bg(theme::row_hover()))118
.child(div().flex_none().size(px(AVATAR_SIZE)).child(person_avatar(119
&state.directory,120
item.author_id.as_deref(),121
author,122
AVATAR_SIZE,123
)))124
.child(125
v_flex()126
.flex_1()127
.min_w_0()128
.gap(px(2.))129
.child(130
h_flex()131
.gap(px(6.))132
.items_baseline()133
.child(134
div()135
.flex_none()136
.text_size(px(13.))137
.font_weight(FontWeight::SEMIBOLD)138
.text_color(theme::text())139
.child(author.to_owned()),140
)141
.child(142
div()143
.min_w_0()144
.truncate()145
.text_size(px(12.))146
.text_color(theme::text_muted())147
.child(title),148
),149
)150
.child(151
div()152
.line_clamp(PREVIEW_LINES)153
.text_size(px(12.5))154
.text_color(theme::text_soft())155
.child(item.preview.clone()),156
),157
)158
.child(159
v_flex()160
.flex_none()161
.items_end()162
.gap(px(2.))163
.child(164
div()165
.text_size(px(11.))166
.text_color(theme::text_muted())167
.child(saved_time(item.saved_at, now)),168
)169
.child(170
div()171
.id(ElementId::Name(format!("saved-unsave-{index}").into()))172
.size(px(BUTTON_SIZE))173
.flex()174
.flex_none()175
.items_center()176
.justify_center()177
.rounded(px(6.))178
.cursor_pointer()179
.opacity(0.)180
.group_hover(group, |button| button.opacity(1.))181
.hover(|button| button.bg(theme::border_strong()))182
.child(icon(IconName::BookmarkOff, 14., theme::text_muted()))183
.tooltip(|window, cx| Tooltip::new("Unsave").build(window, cx))184
.on_click(move |_, _, cx| {185
cx.stop_propagation();186
let entry = unsave_item.clone();187
app.update(cx, |state, cx| state.set_saved(entry, false, cx));188
}),189
),190
)191
.on_click(move |_, _, cx| {192
let event = SavedPanelEvent::Open {193
conversation_id: conversation_id.clone(),194
message_id: message_id.clone(),195
};196
panel.update(cx, |_, cx| cx.emit(event));197
})198
.into_any_element()199
}200
}201
202
fn saved_time(saved_at: DateTime<chrono::Utc>, now: DateTime<Local>) -> String {203
format::list_time_label(saved_at, now.date_naive(), now.offset().fix())204
}205
206
impl Render for SavedPanel {207
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {208
let panel = cx.entity();209
let state = self.app.read(cx);210
let items = state.saved.items().to_vec();211
let mut rows: Vec<AnyElement> = items212
.iter()213
.enumerate()214
.map(|(index, item)| {215
let title = selection_for(&state.sidebar, &item.conversation_id)216
.map(|selection| selection_title(&state.sidebar, &selection))217
.or_else(|| item.topic.clone())218
.unwrap_or_default();219
self.row(item, index, title, panel.clone(), cx)220
})221
.collect();222
if rows.is_empty() {223
rows.push(224
div()225
.py(px(32.))226
.px(px(24.))227
.flex()228
.justify_center()229
.text_center()230
.text_size(px(13.))231
.text_color(theme::text_muted())232
.child(EMPTY_TEXT)233
.into_any_element(),234
);235
}236
let max_height = f32::from(window.viewport_size().height) * PANEL_MAX_HEIGHT_RATIO;237
div()238
.id("saved-layer")239
.absolute()240
.top(px(TITLE_BAR_HEIGHT))241
.left_0()242
.right_0()243
.bottom_0()244
.occlude()245
.flex()246
.justify_end()247
.items_start()248
.p(px(PANEL_MARGIN))249
.on_click(cx.listener(|_, _, _, cx| cx.emit(SavedPanelEvent::Close)))250
.child(251
v_flex()252
.id("saved-card")253
.track_focus(&self.focus_handle)254
.w(px(PANEL_WIDTH))255
.max_h(px(max_height))256
.rounded(px(10.))257
.border_1()258
.border_color(theme::border_strong())259
.bg(theme::surface())260
.shadow_lg()261
.overflow_hidden()262
.occlude()263
.on_click(|_, _, cx| cx.stop_propagation())264
.on_key_down(cx.listener(Self::on_key_down))265
.child(self.header(items.len()))266
.child(267
v_flex()268
.id("saved-list")269
.flex_1()270
.min_h_0()271
.py(px(4.))272
.overflow_y_scroll()273
.track_scroll(&self.scroll)274
.children(rows),275
),276
)277
}278
}279
280
#[cfg(test)]281
mod tests {282
use super::count_label;283
284
#[test]285
fn the_header_count_is_hidden_when_nothing_is_saved() {286
assert_eq!(count_label(0), "");287
assert_eq!(count_label(2), "2");288
}289
}@@ -4,12 +4,15 @@ use gpui_kit::*;
4
4
use super::activity_panel::{ActivityPanel, ActivityPanelEvent};
5
5
use super::conversation::{ConversationView, ReplyToHovered};
6
6
use super::dialog_overlay::render_task_dialog;
7
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
8
use super::saved_panel::{SavedPanel, SavedPanelEvent};
7
9
use super::sidebar::SidebarView;
8
10
use super::status_bar::render_status_bar;
9
11
use super::switcher::{Switcher, SwitcherEvent, candidates_from};
10
12
use super::title_bar::render_title_bar;
11
13
use crate::activity::ActivityCenter;
12
14
use crate::app_state::{AppEvent, AppState, Selection};
15
use crate::notice::NoticeAction;
13
16
use crate::notify::{NotificationCenter, selection_for};
14
17
use crate::theme;
15
18
use crate::updater::{self, IdleInputs, UpdateStatus};
@@ -50,6 +53,8 @@ pub struct AppShell {
50
53
notifications: Entity<NotificationCenter>,
51
54
activity: Entity<ActivityCenter>,
52
55
activity_panel: Option<Entity<ActivityPanel>>,
56
saved_panel: Option<Entity<SavedPanel>>,
57
forward_dialog: Option<Entity<ForwardDialog>>,
53
58
focus_handle: FocusHandle,
54
59
open_target: Option<OpenTarget>,
55
60
update: UpdateStatus,
@@ -67,12 +72,16 @@ impl AppShell {
67
72
) -> Self {
68
73
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));
69
74
let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
70
let subscription = cx.subscribe(&state, |this, _, event: &AppEvent, cx| {
71
if matches!(event, AppEvent::Sidebar | AppEvent::Status) {
72
this.apply_open_target(cx);
73
}
74
cx.notify();
75
});
75
let subscription =
76
cx.subscribe_in(&state, window, |this, _, event: &AppEvent, window, cx| {
77
if matches!(event, AppEvent::Sidebar | AppEvent::Status) {
78
this.apply_open_target(cx);
79
}
80
if matches!(event, AppEvent::Forward) {
81
this.open_forward_dialog(window, cx);
82
}
83
cx.notify();
84
});
76
85
let focus_handle = cx.focus_handle();
77
86
window.focus(&focus_handle, cx);
78
87
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
@@ -88,6 +97,8 @@ impl AppShell {
88
97
notifications,
89
98
activity,
90
99
activity_panel: None,
100
saved_panel: None,
101
forward_dialog: None,
91
102
focus_handle,
92
103
open_target,
93
104
update: UpdateStatus::UpToDate,
@@ -204,6 +215,7 @@ impl AppShell {
204
215
return;
205
216
}
206
217
self.activity_panel = None;
218
self.saved_panel = None;
207
219
let candidates = candidates_from(self.state.read(cx));
208
220
let app = self.state.clone();
209
221
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -245,6 +257,7 @@ impl AppShell {
245
257
return;
246
258
}
247
259
self.switcher = None;
260
self.saved_panel = None;
248
261
let (app, activity) = (self.state.clone(), self.activity.clone());
249
262
let panel = cx.new(|cx| ActivityPanel::new(app, activity, window, cx));
250
263
cx.subscribe_in(
@@ -283,6 +296,78 @@ impl AppShell {
283
296
self.activity_panel = Some(panel);
284
297
cx.notify();
285
298
}
299
fn toggle_saved_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {
300
if self.saved_panel.take().is_some() {
301
window.focus(&self.focus_handle, cx);
302
cx.notify();
303
return;
304
}
305
self.switcher = None;
306
self.activity_panel = None;
307
let app = self.state.clone();
308
let panel = cx.new(|cx| SavedPanel::new(app, window, cx));
309
cx.subscribe_in(
310
&panel,
311
window,
312
|this, _, event: &SavedPanelEvent, window, cx| {
313
this.saved_panel = None;
314
window.focus(&this.focus_handle, cx);
315
if let SavedPanelEvent::Open {
316
conversation_id,
317
message_id,
318
} = event
319
{
320
let selection = selection_for(&this.state.read(cx).sidebar, conversation_id);
321
if let Some(selection) = selection {
322
let message_id = message_id.clone();
323
this.state.update(cx, |state, cx| {
324
state.jump_to_message(selection, message_id, cx)
325
});
326
}
327
}
328
cx.notify();
329
},
330
)
331
.detach();
332
self.saved_panel = Some(panel);
333
cx.notify();
334
}
335
336
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
337
let Some(source) = self
338
.state
339
.update(cx, |state, _| state.take_forward_request())
340
else {
341
return;
342
};
343
self.switcher = None;
344
self.activity_panel = None;
345
self.saved_panel = None;
346
let candidates = candidates_from(self.state.read(cx));
347
let app = self.state.clone();
348
let dialog = cx.new(|cx| ForwardDialog::new(app, source, candidates, window, cx));
349
cx.subscribe_in(
350
&dialog,
351
window,
352
|this, _, event: &ForwardDialogEvent, window, cx| {
353
this.forward_dialog = None;
354
window.focus(&this.focus_handle, cx);
355
if let ForwardDialogEvent::Sent { target, title } = event {
356
let target = target.clone();
357
let open = NoticeAction::new("Open", move |state, cx| {
358
state.select(target.clone(), cx)
359
});
360
this.state.update(cx, |state, cx| {
361
state.raise_notice(format!("Forwarded to {title}"), Some(open), cx)
362
});
363
}
364
cx.notify();
365
},
366
)
367
.detach();
368
self.forward_dialog = Some(dialog);
369
cx.notify();
370
}
286
371
}
287
372
288
373
impl Render for AppShell {
@@ -321,6 +406,7 @@ impl Render for AppShell {
321
406
&state.directory,
322
407
self.activity.read(cx).feed().unread_count(),
323
408
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),
409
cx.listener(|this, _, window, cx| this.toggle_saved_panel(window, cx)),
324
410
cx.listener(|this, _, window, cx| this.toggle_activity_panel(window, cx)),
325
411
);
326
412
div()
@@ -359,8 +445,10 @@ impl Render for AppShell {
359
445
.child(status),
360
446
)
361
447
.children(self.activity_panel.clone())
448
.children(self.saved_panel.clone())
362
449
.children(self.switcher.clone())
363
450
.children(render_task_dialog(self.state.read(cx), cx))
451
.children(self.forward_dialog.clone())
364
452
.child(crate::frame_log::probe("last"))
365
453
}
366
454
}
@@ -4,12 +4,15 @@ use gpui_kit::*;4
use super::activity_panel::{ActivityPanel, ActivityPanelEvent};4
use super::activity_panel::{ActivityPanel, ActivityPanelEvent};5
use super::conversation::{ConversationView, ReplyToHovered};5
use super::conversation::{ConversationView, ReplyToHovered};6
use super::dialog_overlay::render_task_dialog;6
use super::dialog_overlay::render_task_dialog;7
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};8
use super::saved_panel::{SavedPanel, SavedPanelEvent};7
use super::sidebar::SidebarView;9
use super::sidebar::SidebarView;8
use super::status_bar::render_status_bar;10
use super::status_bar::render_status_bar;9
use super::switcher::{Switcher, SwitcherEvent, candidates_from};11
use super::switcher::{Switcher, SwitcherEvent, candidates_from};10
use super::title_bar::render_title_bar;12
use super::title_bar::render_title_bar;11
use crate::activity::ActivityCenter;13
use crate::activity::ActivityCenter;12
use crate::app_state::{AppEvent, AppState, Selection};14
use crate::app_state::{AppEvent, AppState, Selection};15
use crate::notice::NoticeAction;13
use crate::notify::{NotificationCenter, selection_for};16
use crate::notify::{NotificationCenter, selection_for};14
use crate::theme;17
use crate::theme;15
use crate::updater::{self, IdleInputs, UpdateStatus};18
use crate::updater::{self, IdleInputs, UpdateStatus};@@ -50,6 +53,8 @@ pub struct AppShell {50
notifications: Entity<NotificationCenter>,53
notifications: Entity<NotificationCenter>,51
activity: Entity<ActivityCenter>,54
activity: Entity<ActivityCenter>,52
activity_panel: Option<Entity<ActivityPanel>>,55
activity_panel: Option<Entity<ActivityPanel>>,56
saved_panel: Option<Entity<SavedPanel>>,57
forward_dialog: Option<Entity<ForwardDialog>>,53
focus_handle: FocusHandle,58
focus_handle: FocusHandle,54
open_target: Option<OpenTarget>,59
open_target: Option<OpenTarget>,55
update: UpdateStatus,60
update: UpdateStatus,@@ -67,12 +72,16 @@ impl AppShell {67
) -> Self {72
) -> Self {68
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));73
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), cx));69
let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));74
let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));70
let subscription = cx.subscribe(&state, |this, _, event: &AppEvent, cx| {75
let subscription =71
if matches!(event, AppEvent::Sidebar | AppEvent::Status) {76
cx.subscribe_in(&state, window, |this, _, event: &AppEvent, window, cx| {72
this.apply_open_target(cx);77
if matches!(event, AppEvent::Sidebar | AppEvent::Status) {73
}78
this.apply_open_target(cx);74
cx.notify();79
}75
});80
if matches!(event, AppEvent::Forward) {81
this.open_forward_dialog(window, cx);82
}83
cx.notify();84
});76
let focus_handle = cx.focus_handle();85
let focus_handle = cx.focus_handle();77
window.focus(&focus_handle, cx);86
window.focus(&focus_handle, cx);78
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));87
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));@@ -88,6 +97,8 @@ impl AppShell {88
notifications,97
notifications,89
activity,98
activity,90
activity_panel: None,99
activity_panel: None,100
saved_panel: None,101
forward_dialog: None,91
focus_handle,102
focus_handle,92
open_target,103
open_target,93
update: UpdateStatus::UpToDate,104
update: UpdateStatus::UpToDate,@@ -204,6 +215,7 @@ impl AppShell {204
return;215
return;205
}216
}206
self.activity_panel = None;217
self.activity_panel = None;218
self.saved_panel = None;207
let candidates = candidates_from(self.state.read(cx));219
let candidates = candidates_from(self.state.read(cx));208
let app = self.state.clone();220
let app = self.state.clone();209
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));221
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));@@ -245,6 +257,7 @@ impl AppShell {245
return;257
return;246
}258
}247
self.switcher = None;259
self.switcher = None;260
self.saved_panel = None;248
let (app, activity) = (self.state.clone(), self.activity.clone());261
let (app, activity) = (self.state.clone(), self.activity.clone());249
let panel = cx.new(|cx| ActivityPanel::new(app, activity, window, cx));262
let panel = cx.new(|cx| ActivityPanel::new(app, activity, window, cx));250
cx.subscribe_in(263
cx.subscribe_in(@@ -283,6 +296,78 @@ impl AppShell {283
self.activity_panel = Some(panel);296
self.activity_panel = Some(panel);284
cx.notify();297
cx.notify();285
}298
}299
fn toggle_saved_panel(&mut self, window: &mut Window, cx: &mut Context<Self>) {300
if self.saved_panel.take().is_some() {301
window.focus(&self.focus_handle, cx);302
cx.notify();303
return;304
}305
self.switcher = None;306
self.activity_panel = None;307
let app = self.state.clone();308
let panel = cx.new(|cx| SavedPanel::new(app, window, cx));309
cx.subscribe_in(310
&panel,311
window,312
|this, _, event: &SavedPanelEvent, window, cx| {313
this.saved_panel = None;314
window.focus(&this.focus_handle, cx);315
if let SavedPanelEvent::Open {316
conversation_id,317
message_id,318
} = event319
{320
let selection = selection_for(&this.state.read(cx).sidebar, conversation_id);321
if let Some(selection) = selection {322
let message_id = message_id.clone();323
this.state.update(cx, |state, cx| {324
state.jump_to_message(selection, message_id, cx)325
});326
}327
}328
cx.notify();329
},330
)331
.detach();332
self.saved_panel = Some(panel);333
cx.notify();334
}335
336
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {337
let Some(source) = self338
.state339
.update(cx, |state, _| state.take_forward_request())340
else {341
return;342
};343
self.switcher = None;344
self.activity_panel = None;345
self.saved_panel = None;346
let candidates = candidates_from(self.state.read(cx));347
let app = self.state.clone();348
let dialog = cx.new(|cx| ForwardDialog::new(app, source, candidates, window, cx));349
cx.subscribe_in(350
&dialog,351
window,352
|this, _, event: &ForwardDialogEvent, window, cx| {353
this.forward_dialog = None;354
window.focus(&this.focus_handle, cx);355
if let ForwardDialogEvent::Sent { target, title } = event {356
let target = target.clone();357
let open = NoticeAction::new("Open", move |state, cx| {358
state.select(target.clone(), cx)359
});360
this.state.update(cx, |state, cx| {361
state.raise_notice(format!("Forwarded to {title}"), Some(open), cx)362
});363
}364
cx.notify();365
},366
)367
.detach();368
self.forward_dialog = Some(dialog);369
cx.notify();370
}286
}371
}287
372
288
impl Render for AppShell {373
impl Render for AppShell {@@ -321,6 +406,7 @@ impl Render for AppShell {321
&state.directory,406
&state.directory,322
self.activity.read(cx).feed().unread_count(),407
self.activity.read(cx).feed().unread_count(),323
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),408
cx.listener(|this, _, window, cx| this.toggle_switcher("", window, cx)),409
cx.listener(|this, _, window, cx| this.toggle_saved_panel(window, cx)),324
cx.listener(|this, _, window, cx| this.toggle_activity_panel(window, cx)),410
cx.listener(|this, _, window, cx| this.toggle_activity_panel(window, cx)),325
);411
);326
div()412
div()@@ -359,8 +445,10 @@ impl Render for AppShell {359
.child(status),445
.child(status),360
)446
)361
.children(self.activity_panel.clone())447
.children(self.activity_panel.clone())448
.children(self.saved_panel.clone())362
.children(self.switcher.clone())449
.children(self.switcher.clone())363
.children(render_task_dialog(self.state.read(cx), cx))450
.children(render_task_dialog(self.state.read(cx), cx))451
.children(self.forward_dialog.clone())364
.child(crate::frame_log::probe("last"))452
.child(crate::frame_log::probe("last"))365
}453
}366
}454
}@@ -16,7 +16,7 @@ use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};
16
16
use super::avatar::{person_avatar, spec_avatar, square_avatar};
17
17
use super::widgets::icon;
18
18
use crate::app_state::{AppState, Selection, chat_title};
19
use crate::data::is_one_on_one;
19
use crate::data::{Directory, is_one_on_one};
20
20
use crate::format;
21
21
use crate::fuzzy;
22
22
use crate::sidebar_model::{AvatarSpec, avatar_for};
@@ -164,6 +164,20 @@ pub fn candidates_from(state: &AppState) -> Vec<(String, Candidate)> {
164
164
chats.chain(channels).collect()
165
165
}
166
166
167
pub fn candidate_avatar(
168
directory: &Directory,
169
avatar: &CandidateAvatar,
170
size: f32,
171
ring: Hsla,
172
) -> AnyElement {
173
match avatar {
174
CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, size, ring),
175
CandidateAvatar::Team { name, key } => {
176
square_avatar(name, key, size, size / 4.).into_any_element()
177
}
178
}
179
}
180
167
181
pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {
168
182
if length == 0 {
169
183
return 0;
@@ -315,12 +329,7 @@ impl Render for Switcher {
315
329
rows.push(group_header(last_group));
316
330
}
317
331
let selection = candidate.selection.clone();
318
let avatar = match &candidate.avatar {
319
CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, 28., theme::surface()),
320
CandidateAvatar::Team { name, key } => {
321
square_avatar(name, key, 28., 7.).into_any_element()
322
}
323
};
332
let avatar = candidate_avatar(directory, &candidate.avatar, 28., theme::surface());
324
333
let kind_icon = match candidate.selection {
325
334
Selection::Chat(_) => IconName::MessageCircle,
326
335
Selection::Channel(_) => IconName::Hash,
@@ -16,7 +16,7 @@ use teams_core::{HIGHLIGHT_END, HIGHLIGHT_START};16
use super::avatar::{person_avatar, spec_avatar, square_avatar};16
use super::avatar::{person_avatar, spec_avatar, square_avatar};17
use super::widgets::icon;17
use super::widgets::icon;18
use crate::app_state::{AppState, Selection, chat_title};18
use crate::app_state::{AppState, Selection, chat_title};19
use crate::data::is_one_on_one;19
use crate::data::{Directory, is_one_on_one};20
use crate::format;20
use crate::format;21
use crate::fuzzy;21
use crate::fuzzy;22
use crate::sidebar_model::{AvatarSpec, avatar_for};22
use crate::sidebar_model::{AvatarSpec, avatar_for};@@ -164,6 +164,20 @@ pub fn candidates_from(state: &AppState) -> Vec<(String, Candidate)> {164
chats.chain(channels).collect()164
chats.chain(channels).collect()165
}165
}166
166
167
pub fn candidate_avatar(168
directory: &Directory,169
avatar: &CandidateAvatar,170
size: f32,171
ring: Hsla,172
) -> AnyElement {173
match avatar {174
CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, size, ring),175
CandidateAvatar::Team { name, key } => {176
square_avatar(name, key, size, size / 4.).into_any_element()177
}178
}179
}180
167
pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {181
pub fn clamp_highlight(current: usize, delta: isize, length: usize) -> usize {168
if length == 0 {182
if length == 0 {169
return 0;183
return 0;@@ -315,12 +329,7 @@ impl Render for Switcher {315
rows.push(group_header(last_group));329
rows.push(group_header(last_group));316
}330
}317
let selection = candidate.selection.clone();331
let selection = candidate.selection.clone();318
let avatar = match &candidate.avatar {332
let avatar = candidate_avatar(directory, &candidate.avatar, 28., theme::surface());319
CandidateAvatar::Chat(spec) => spec_avatar(directory, spec, 28., theme::surface()),320
CandidateAvatar::Team { name, key } => {321
square_avatar(name, key, 28., 7.).into_any_element()322
}323
};324
let kind_icon = match candidate.selection {333
let kind_icon = match candidate.selection {325
Selection::Chat(_) => IconName::MessageCircle,334
Selection::Chat(_) => IconName::MessageCircle,326
Selection::Channel(_) => IconName::Hash,335
Selection::Channel(_) => IconName::Hash,@@ -28,8 +28,22 @@ pub fn render_title_bar(
28
28
directory: &Directory,
29
29
activity_unread: usize,
30
30
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
31
on_saved: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
31
32
on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
32
33
) -> impl IntoElement {
34
let saved = div()
35
.id("title-saved")
36
.occlude()
37
.size(px(28.))
38
.flex()
39
.flex_none()
40
.items_center()
41
.justify_center()
42
.rounded(px(6.))
43
.cursor_pointer()
44
.hover(|button| button.bg(theme::surface()))
45
.child(icon(IconName::Bookmark, 18., theme::text_muted()))
46
.on_click(on_saved);
33
47
let notifications = div()
34
48
.id("title-notifications")
35
49
.relative()
@@ -117,6 +131,7 @@ pub fn render_title_bar(
117
131
.child(crate::APP_NAME),
118
132
)
119
133
.child(div().flex_1().flex().justify_center().child(search))
134
.child(saved)
120
135
.child(notifications)
121
136
.children(own)
122
137
.child(div().w(px(4.))),
@@ -28,8 +28,22 @@ pub fn render_title_bar(28
directory: &Directory,28
directory: &Directory,29
activity_unread: usize,29
activity_unread: usize,30
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,30
on_search: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,31
on_saved: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,31
on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,32
on_notifications: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,32
) -> impl IntoElement {33
) -> impl IntoElement {34
let saved = div()35
.id("title-saved")36
.occlude()37
.size(px(28.))38
.flex()39
.flex_none()40
.items_center()41
.justify_center()42
.rounded(px(6.))43
.cursor_pointer()44
.hover(|button| button.bg(theme::surface()))45
.child(icon(IconName::Bookmark, 18., theme::text_muted()))46
.on_click(on_saved);33
let notifications = div()47
let notifications = div()34
.id("title-notifications")48
.id("title-notifications")35
.relative()49
.relative()@@ -117,6 +131,7 @@ pub fn render_title_bar(117
.child(crate::APP_NAME),131
.child(crate::APP_NAME),118
)132
)119
.child(div().flex_1().flex().justify_center().child(search))133
.child(div().flex_1().flex().justify_center().child(search))134
.child(saved)120
.child(notifications)135
.child(notifications)121
.children(own)136
.children(own)122
.child(div().w(px(4.))),137
.child(div().w(px(4.))),@@ -63,6 +63,7 @@
63
63
if (resourceType === 'NewMessage') {
64
64
if (/^Control\/(Clear)?Typing/.test(messageType)) return 'typing';
65
65
if (messageType === 'ThreadActivity/MemberConsumptionHorizonUpdate') return 'read_receipt';
66
if (messageType === 'ThreadActivity/PinnedItemsUpdate') return 'pins_changed';
66
67
if (/^ThreadActivity\//.test(messageType)) return 'thread_activity';
67
68
return /^Control\//.test(messageType) ? 'control' : 'new_message';
68
69
}
@@ -63,6 +63,7 @@63
if (resourceType === 'NewMessage') {63
if (resourceType === 'NewMessage') {64
if (/^Control\/(Clear)?Typing/.test(messageType)) return 'typing';64
if (/^Control\/(Clear)?Typing/.test(messageType)) return 'typing';65
if (messageType === 'ThreadActivity/MemberConsumptionHorizonUpdate') return 'read_receipt';65
if (messageType === 'ThreadActivity/MemberConsumptionHorizonUpdate') return 'read_receipt';66
if (messageType === 'ThreadActivity/PinnedItemsUpdate') return 'pins_changed';66
if (/^ThreadActivity\//.test(messageType)) return 'thread_activity';67
if (/^ThreadActivity\//.test(messageType)) return 'thread_activity';67
return /^Control\//.test(messageType) ? 'control' : 'new_message';68
return /^Control\//.test(messageType) ? 'control' : 'new_message';68
}69
}@@ -75,6 +75,7 @@ fn kind_name(kind: EventKind) -> &'static str {
75
75
EventKind::ThreadUpdate => "thread_update",
76
76
EventKind::Typing => "typing",
77
77
EventKind::ReadReceipt => "read_receipt",
78
EventKind::PinsChanged => "pins_changed",
78
79
EventKind::ThreadActivity => "thread_activity",
79
80
EventKind::Control => "control",
80
81
EventKind::Other => "other",
@@ -75,6 +75,7 @@ fn kind_name(kind: EventKind) -> &'static str {75
EventKind::ThreadUpdate => "thread_update",75
EventKind::ThreadUpdate => "thread_update",76
EventKind::Typing => "typing",76
EventKind::Typing => "typing",77
EventKind::ReadReceipt => "read_receipt",77
EventKind::ReadReceipt => "read_receipt",78
EventKind::PinsChanged => "pins_changed",78
EventKind::ThreadActivity => "thread_activity",79
EventKind::ThreadActivity => "thread_activity",79
EventKind::Control => "control",80
EventKind::Control => "control",80
EventKind::Other => "other",81
EventKind::Other => "other",@@ -0,0 +1,221 @@
1
use chrono::Utc;
2
use serde_json::{Value, json};
3
use session::{Method, Request};
4
5
use crate::error::{Error, Result};
6
use crate::messages::{MessageTransport, Messages, encode, ensure_success};
7
8
pub const MAX_FORWARD_MESSAGES: usize = 5;
9
const FORWARD_TEMPLATE: &str = "basic_forward_message_template";
10
11
#[derive(Debug, Clone, PartialEq, Eq)]
12
pub struct ForwardResult {
13
pub thread_id: String,
14
pub message_id: String,
15
}
16
17
fn forward_body(target_conversation_id: &str, message_ids: &[String], comment_html: &str) -> Value {
18
json!({
19
"targetThreadIds": [target_conversation_id],
20
"messageIds": message_ids,
21
"additionalMessage": {
22
"clientmessageid": Utc::now().timestamp_millis().to_string(),
23
"content": comment_html,
24
"messagetype": "RichText/Html",
25
"contenttype": "text",
26
"imdisplayname": "",
27
"properties": {"importance": "", "subject": ""},
28
},
29
"templateId": FORWARD_TEMPLATE,
30
})
31
}
32
33
fn parse_forward_result(body: &Value) -> Result<ForwardResult> {
34
let entry = body
35
.as_array()
36
.and_then(|entries| entries.first())
37
.ok_or_else(|| Error::UnexpectedAnswer("no forward result".into()))?;
38
let status = entry
39
.get("statusCode")
40
.and_then(Value::as_u64)
41
.and_then(|status| u16::try_from(status).ok())
42
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no statusCode".into()))?;
43
if !(200..300).contains(&status) {
44
return Err(Error::Session(session::Error::api(
45
status,
46
"chatsvc",
47
entry.clone(),
48
)));
49
}
50
let text = |key: &str| match entry.get(key) {
51
Some(Value::String(text)) => Some(text.clone()),
52
Some(Value::Number(number)) => Some(number.to_string()),
53
_ => None,
54
};
55
Ok(ForwardResult {
56
thread_id: text("threadId")
57
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no threadId".into()))?,
58
message_id: text("messageId")
59
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no messageId".into()))?,
60
})
61
}
62
63
impl<T: MessageTransport> Messages<T> {
64
pub fn forward_url(&self, source_conversation_id: &str) -> String {
65
format!(
66
"{}/{}/messages/forward",
67
self.base_url,
68
encode(source_conversation_id)
69
)
70
}
71
72
/// `message_ids` holds 1 to 5 ids, oldest first.
73
pub async fn forward_messages(
74
&self,
75
source_conversation_id: &str,
76
target_conversation_id: &str,
77
message_ids: &[String],
78
comment_html: &str,
79
) -> Result<ForwardResult> {
80
if message_ids.is_empty() || message_ids.len() > MAX_FORWARD_MESSAGES {
81
return Err(Error::UnexpectedAnswer(format!(
82
"forwarding needs 1 to {MAX_FORWARD_MESSAGES} messages"
83
)));
84
}
85
let body = forward_body(target_conversation_id, message_ids, comment_html);
86
let answer = self
87
.transport
88
.send(Request::with_body(
89
Method::Post,
90
self.forward_url(source_conversation_id),
91
body,
92
))
93
.await?;
94
ensure_success(&answer)?;
95
parse_forward_result(&answer.body)
96
}
97
}
98
99
#[cfg(test)]
100
mod tests {
101
use std::sync::Mutex;
102
103
use session::ApiResponse;
104
105
use super::*;
106
107
struct Canned {
108
status: u16,
109
body: Value,
110
requests: Mutex<Vec<Request>>,
111
}
112
113
impl MessageTransport for Canned {
114
async fn send(&self, request: Request) -> Result<ApiResponse> {
115
self.requests.lock().unwrap().push(request);
116
Ok(ApiResponse {
117
status: self.status,
118
body: self.body.clone(),
119
retry_after: None,
120
})
121
}
122
}
123
124
fn canned(status: u16, body: Value) -> Messages<Canned> {
125
Messages::with_transport(
126
Canned {
127
status,
128
body,
129
requests: Mutex::new(Vec::new()),
130
},
131
"emea",
132
)
133
}
134
135
fn ids(values: &[&str]) -> Vec<String> {
136
values.iter().map(|value| (*value).to_owned()).collect()
137
}
138
139
#[tokio::test]
140
async fn posts_forward_body_to_encoded_source() {
141
let messages = canned(
142
200,
143
json!([{"statusCode": 201, "threadId": "19:notes@thread.v2", "messageId": "1791368146075"}]),
144
);
145
let result = messages
146
.forward_messages(
147
"19:src@thread.v2",
148
"48:notes",
149
&ids(&["1", "2"]),
150
"<p>fyi</p>",
151
)
152
.await
153
.unwrap();
154
assert_eq!(
155
result,
156
ForwardResult {
157
thread_id: "19:notes@thread.v2".into(),
158
message_id: "1791368146075".into(),
159
}
160
);
161
let requests = messages.transport.requests.lock().unwrap();
162
assert_eq!(requests[0].method, Method::Post);
163
assert_eq!(
164
requests[0].url,
165
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Asrc%40thread.v2/messages/forward"
166
);
167
let body = requests[0].body.as_ref().unwrap();
168
assert_eq!(body["targetThreadIds"], json!(["48:notes"]));
169
assert_eq!(body["messageIds"], json!(["1", "2"]));
170
assert_eq!(body["templateId"], "basic_forward_message_template");
171
assert_eq!(body["additionalMessage"]["content"], "<p>fyi</p>");
172
assert_eq!(body["additionalMessage"]["messagetype"], "RichText/Html");
173
assert_eq!(body["additionalMessage"]["contenttype"], "text");
174
assert!(
175
body["additionalMessage"]["clientmessageid"]
176
.as_str()
177
.unwrap()
178
.parse::<i64>()
179
.is_ok()
180
);
181
}
182
183
#[tokio::test]
184
async fn failing_target_status_is_an_error() {
185
let messages = canned(
186
200,
187
json!([{"statusCode": 403, "threadId": "t", "messageId": "1"}]),
188
);
189
assert!(
190
messages
191
.forward_messages("a", "b", &ids(&["1"]), "")
192
.await
193
.is_err()
194
);
195
}
196
197
#[tokio::test]
198
async fn http_failure_and_empty_answer_are_errors() {
199
let failing = canned(500, json!({}));
200
assert!(
201
failing
202
.forward_messages("a", "b", &ids(&["1"]), "")
203
.await
204
.is_err()
205
);
206
let empty = canned(200, json!([]));
207
assert!(matches!(
208
empty.forward_messages("a", "b", &ids(&["1"]), "").await,
209
Err(Error::UnexpectedAnswer(_))
210
));
211
}
212
213
#[tokio::test]
214
async fn message_count_is_limited_before_sending() {
215
let messages = canned(200, json!([]));
216
assert!(messages.forward_messages("a", "b", &[], "").await.is_err());
217
let six = ids(&["1", "2", "3", "4", "5", "6"]);
218
assert!(messages.forward_messages("a", "b", &six, "").await.is_err());
219
assert!(messages.transport.requests.lock().unwrap().is_empty());
220
}
221
}
@@ -0,0 +1,221 @@1
use chrono::Utc;2
use serde_json::{Value, json};3
use session::{Method, Request};4
5
use crate::error::{Error, Result};6
use crate::messages::{MessageTransport, Messages, encode, ensure_success};7
8
pub const MAX_FORWARD_MESSAGES: usize = 5;9
const FORWARD_TEMPLATE: &str = "basic_forward_message_template";10
11
#[derive(Debug, Clone, PartialEq, Eq)]12
pub struct ForwardResult {13
pub thread_id: String,14
pub message_id: String,15
}16
17
fn forward_body(target_conversation_id: &str, message_ids: &[String], comment_html: &str) -> Value {18
json!({19
"targetThreadIds": [target_conversation_id],20
"messageIds": message_ids,21
"additionalMessage": {22
"clientmessageid": Utc::now().timestamp_millis().to_string(),23
"content": comment_html,24
"messagetype": "RichText/Html",25
"contenttype": "text",26
"imdisplayname": "",27
"properties": {"importance": "", "subject": ""},28
},29
"templateId": FORWARD_TEMPLATE,30
})31
}32
33
fn parse_forward_result(body: &Value) -> Result<ForwardResult> {34
let entry = body35
.as_array()36
.and_then(|entries| entries.first())37
.ok_or_else(|| Error::UnexpectedAnswer("no forward result".into()))?;38
let status = entry39
.get("statusCode")40
.and_then(Value::as_u64)41
.and_then(|status| u16::try_from(status).ok())42
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no statusCode".into()))?;43
if !(200..300).contains(&status) {44
return Err(Error::Session(session::Error::api(45
status,46
"chatsvc",47
entry.clone(),48
)));49
}50
let text = |key: &str| match entry.get(key) {51
Some(Value::String(text)) => Some(text.clone()),52
Some(Value::Number(number)) => Some(number.to_string()),53
_ => None,54
};55
Ok(ForwardResult {56
thread_id: text("threadId")57
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no threadId".into()))?,58
message_id: text("messageId")59
.ok_or_else(|| Error::UnexpectedAnswer("forward result has no messageId".into()))?,60
})61
}62
63
impl<T: MessageTransport> Messages<T> {64
pub fn forward_url(&self, source_conversation_id: &str) -> String {65
format!(66
"{}/{}/messages/forward",67
self.base_url,68
encode(source_conversation_id)69
)70
}71
72
/// `message_ids` holds 1 to 5 ids, oldest first.73
pub async fn forward_messages(74
&self,75
source_conversation_id: &str,76
target_conversation_id: &str,77
message_ids: &[String],78
comment_html: &str,79
) -> Result<ForwardResult> {80
if message_ids.is_empty() || message_ids.len() > MAX_FORWARD_MESSAGES {81
return Err(Error::UnexpectedAnswer(format!(82
"forwarding needs 1 to {MAX_FORWARD_MESSAGES} messages"83
)));84
}85
let body = forward_body(target_conversation_id, message_ids, comment_html);86
let answer = self87
.transport88
.send(Request::with_body(89
Method::Post,90
self.forward_url(source_conversation_id),91
body,92
))93
.await?;94
ensure_success(&answer)?;95
parse_forward_result(&answer.body)96
}97
}98
99
#[cfg(test)]100
mod tests {101
use std::sync::Mutex;102
103
use session::ApiResponse;104
105
use super::*;106
107
struct Canned {108
status: u16,109
body: Value,110
requests: Mutex<Vec<Request>>,111
}112
113
impl MessageTransport for Canned {114
async fn send(&self, request: Request) -> Result<ApiResponse> {115
self.requests.lock().unwrap().push(request);116
Ok(ApiResponse {117
status: self.status,118
body: self.body.clone(),119
retry_after: None,120
})121
}122
}123
124
fn canned(status: u16, body: Value) -> Messages<Canned> {125
Messages::with_transport(126
Canned {127
status,128
body,129
requests: Mutex::new(Vec::new()),130
},131
"emea",132
)133
}134
135
fn ids(values: &[&str]) -> Vec<String> {136
values.iter().map(|value| (*value).to_owned()).collect()137
}138
139
#[tokio::test]140
async fn posts_forward_body_to_encoded_source() {141
let messages = canned(142
200,143
json!([{"statusCode": 201, "threadId": "19:notes@thread.v2", "messageId": "1791368146075"}]),144
);145
let result = messages146
.forward_messages(147
"19:src@thread.v2",148
"48:notes",149
&ids(&["1", "2"]),150
"<p>fyi</p>",151
)152
.await153
.unwrap();154
assert_eq!(155
result,156
ForwardResult {157
thread_id: "19:notes@thread.v2".into(),158
message_id: "1791368146075".into(),159
}160
);161
let requests = messages.transport.requests.lock().unwrap();162
assert_eq!(requests[0].method, Method::Post);163
assert_eq!(164
requests[0].url,165
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Asrc%40thread.v2/messages/forward"166
);167
let body = requests[0].body.as_ref().unwrap();168
assert_eq!(body["targetThreadIds"], json!(["48:notes"]));169
assert_eq!(body["messageIds"], json!(["1", "2"]));170
assert_eq!(body["templateId"], "basic_forward_message_template");171
assert_eq!(body["additionalMessage"]["content"], "<p>fyi</p>");172
assert_eq!(body["additionalMessage"]["messagetype"], "RichText/Html");173
assert_eq!(body["additionalMessage"]["contenttype"], "text");174
assert!(175
body["additionalMessage"]["clientmessageid"]176
.as_str()177
.unwrap()178
.parse::<i64>()179
.is_ok()180
);181
}182
183
#[tokio::test]184
async fn failing_target_status_is_an_error() {185
let messages = canned(186
200,187
json!([{"statusCode": 403, "threadId": "t", "messageId": "1"}]),188
);189
assert!(190
messages191
.forward_messages("a", "b", &ids(&["1"]), "")192
.await193
.is_err()194
);195
}196
197
#[tokio::test]198
async fn http_failure_and_empty_answer_are_errors() {199
let failing = canned(500, json!({}));200
assert!(201
failing202
.forward_messages("a", "b", &ids(&["1"]), "")203
.await204
.is_err()205
);206
let empty = canned(200, json!([]));207
assert!(matches!(208
empty.forward_messages("a", "b", &ids(&["1"]), "").await,209
Err(Error::UnexpectedAnswer(_))210
));211
}212
213
#[tokio::test]214
async fn message_count_is_limited_before_sending() {215
let messages = canned(200, json!([]));216
assert!(messages.forward_messages("a", "b", &[], "").await.is_err());217
let six = ids(&["1", "2", "3", "4", "5", "6"]);218
assert!(messages.forward_messages("a", "b", &six, "").await.is_err());219
assert!(messages.transport.requests.lock().unwrap().is_empty());220
}221
}@@ -2,14 +2,16 @@ pub mod cards;
2
2
pub mod conversations;
3
3
pub mod drafts;
4
4
mod error;
5
pub mod links;
5
pub mod forward;
6
6
pub mod gifs;
7
pub mod links;
7
8
mod mask;
8
9
pub mod messages;
9
10
pub mod pins;
10
11
pub mod reactions;
11
12
pub mod realtime;
12
13
pub mod receipts;
14
pub mod saved;
13
15
14
16
pub use cards::{
15
17
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -17,12 +19,14 @@ pub use cards::{
17
19
pub use conversations::Conversations;
18
20
pub use drafts::{ScheduledDraft, ScheduledDrafts};
19
21
pub use error::{Error, Result};
22
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};
20
23
pub use gifs::{Gif, Gifs};
21
pub use mask::mask_conversation_id;
22
24
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
25
pub use mask::mask_conversation_id;
23
26
pub use messages::{ConversationRef, Messages};
24
27
pub use pins::{
25
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
28
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,
29
TeamLayout,
26
30
};
27
31
pub use reactions::{emotion_key, emotion_keys};
28
32
pub use realtime::{
@@ -30,3 +34,4 @@ pub use realtime::{
30
34
StatusKind, TrouterEndpoint, TypingEvent,
31
35
};
32
36
pub use receipts::{MemberHorizon, Receipts};
37
pub use saved::SavedMessage;
@@ -2,14 +2,16 @@ pub mod cards;2
pub mod conversations;2
pub mod conversations;3
pub mod drafts;3
pub mod drafts;4
mod error;4
mod error;5
pub mod links;5
pub mod forward;6
pub mod gifs;6
pub mod gifs;7
pub mod links;7
mod mask;8
mod mask;8
pub mod messages;9
pub mod messages;9
pub mod pins;10
pub mod pins;10
pub mod reactions;11
pub mod reactions;11
pub mod realtime;12
pub mod realtime;12
pub mod receipts;13
pub mod receipts;14
pub mod saved;13
15
14
pub use cards::{16
pub use cards::{15
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,17
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,@@ -17,12 +19,14 @@ pub use cards::{17
pub use conversations::Conversations;19
pub use conversations::Conversations;18
pub use drafts::{ScheduledDraft, ScheduledDrafts};20
pub use drafts::{ScheduledDraft, ScheduledDrafts};19
pub use error::{Error, Result};21
pub use error::{Error, Result};22
pub use forward::{ForwardResult, MAX_FORWARD_MESSAGES};20
pub use gifs::{Gif, Gifs};23
pub use gifs::{Gif, Gifs};21
pub use mask::mask_conversation_id;22
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};24
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};25
pub use mask::mask_conversation_id;23
pub use messages::{ConversationRef, Messages};26
pub use messages::{ConversationRef, Messages};24
pub use pins::{27
pub use pins::{25
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,28
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, PinnedMessage, Pins,29
TeamLayout,26
};30
};27
pub use reactions::{emotion_key, emotion_keys};31
pub use reactions::{emotion_key, emotion_keys};28
pub use realtime::{32
pub use realtime::{@@ -30,3 +34,4 @@ pub use realtime::{30
StatusKind, TrouterEndpoint, TypingEvent,34
StatusKind, TrouterEndpoint, TypingEvent,31
};35
};32
pub use receipts::{MemberHorizon, Receipts};36
pub use receipts::{MemberHorizon, Receipts};37
pub use saved::SavedMessage;@@ -1,6 +1,7 @@
1
1
mod channels;
2
2
mod chats;
3
3
mod folders;
4
mod pinbar;
4
5
mod state;
5
6
mod teams;
6
7
mod transport;
@@ -8,6 +9,7 @@ mod transport;
8
9
use session::Session;
9
10
10
11
pub use folders::{Folder, FolderKind, Folders};
12
pub use pinbar::PinnedMessage;
11
13
pub use state::{PinnedChannels, PinnedChats};
12
14
pub use teams::{ChannelLayout, TeamLayout};
13
15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};
@@ -17,6 +19,7 @@ pub const DEFAULT_REGION: &str = "emea";
17
19
pub struct Pins<T: CsaTransport = SessionTransport> {
18
20
transport: T,
19
21
base_url: String,
22
api_url: String,
20
23
}
21
24
22
25
impl Pins<SessionTransport> {
@@ -36,6 +39,7 @@ impl<T: CsaTransport> Pins<T> {
36
39
base_url: format!(
37
40
"https://teams.cloud.microsoft/api/csa/{region}/api/v1/teams/users/me"
38
41
),
42
api_url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1"),
39
43
}
40
44
}
41
45
}
@@ -1,6 +1,7 @@1
mod channels;1
mod channels;2
mod chats;2
mod chats;3
mod folders;3
mod folders;4
mod pinbar;4
mod state;5
mod state;5
mod teams;6
mod teams;6
mod transport;7
mod transport;@@ -8,6 +9,7 @@ mod transport;8
use session::Session;9
use session::Session;9
10
10
pub use folders::{Folder, FolderKind, Folders};11
pub use folders::{Folder, FolderKind, Folders};12
pub use pinbar::PinnedMessage;11
pub use state::{PinnedChannels, PinnedChats};13
pub use state::{PinnedChannels, PinnedChats};12
pub use teams::{ChannelLayout, TeamLayout};14
pub use teams::{ChannelLayout, TeamLayout};13
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};15
pub use transport::{CSA_RESOURCE, CSA_SCOPE, CsaTransport, SessionTransport};@@ -17,6 +19,7 @@ pub const DEFAULT_REGION: &str = "emea";17
pub struct Pins<T: CsaTransport = SessionTransport> {19
pub struct Pins<T: CsaTransport = SessionTransport> {18
transport: T,20
transport: T,19
base_url: String,21
base_url: String,22
api_url: String,20
}23
}21
24
22
impl Pins<SessionTransport> {25
impl Pins<SessionTransport> {@@ -36,6 +39,7 @@ impl<T: CsaTransport> Pins<T> {36
base_url: format!(39
base_url: format!(37
"https://teams.cloud.microsoft/api/csa/{region}/api/v1/teams/users/me"40
"https://teams.cloud.microsoft/api/csa/{region}/api/v1/teams/users/me"38
),41
),42
api_url: format!("https://teams.cloud.microsoft/api/csa/{region}/api/v1"),39
}43
}40
}44
}41
}45
}@@ -0,0 +1,268 @@
1
use std::cmp::Reverse;
2
3
use chrono::{DateTime, Utc};
4
use serde_json::{Value, json};
5
use session::{Method, Request};
6
7
use super::Pins;
8
use super::chats::{api_error, ensure_success};
9
use super::transport::CsaTransport;
10
use crate::error::{Error, Result};
11
use crate::messages::encode;
12
13
const PIN_MESSAGE_TYPE: &str = "pinmsg";
14
const FOLDER_TYPE: &str = "folder";
15
16
#[derive(Debug, Clone, PartialEq, Eq)]
17
pub struct PinnedMessage {
18
pub message_id: String,
19
pub pinned_at: Option<DateTime<Utc>>,
20
pub parent_id: Option<String>,
21
}
22
23
fn pinned_message(item: &Value, parent_id: Option<&str>) -> Option<PinnedMessage> {
24
if item.get("type")?.as_str()? != PIN_MESSAGE_TYPE {
25
return None;
26
}
27
let message_id = item
28
.get("pinBarItemId")
29
.and_then(Value::as_str)
30
.or_else(|| item.pointer("/pinnedMessageProperties/messageId")?.as_str())?
31
.to_owned();
32
let pinned_at = item
33
.pointer("/pinnedMessageProperties/pinnedDateTime")
34
.and_then(|value| match value {
35
Value::String(text) => text.parse::<i64>().ok(),
36
other => other.as_i64(),
37
})
38
.and_then(DateTime::from_timestamp_millis);
39
Some(PinnedMessage {
40
message_id,
41
pinned_at,
42
parent_id: parent_id.map(str::to_owned),
43
})
44
}
45
46
pub fn parse_chat_pins(body: &Value) -> Result<Vec<PinnedMessage>> {
47
let children = body
48
.get("children")
49
.and_then(Value::as_array)
50
.ok_or_else(|| Error::UnexpectedAnswer("pinbar children missing".into()))?;
51
let mut pins = Vec::new();
52
for child in children {
53
if child.get("type").and_then(Value::as_str) == Some(FOLDER_TYPE) {
54
let folder_id = child.get("pinBarItemId").and_then(Value::as_str);
55
let nested = child.get("children").and_then(Value::as_array);
56
pins.extend(
57
nested
58
.into_iter()
59
.flatten()
60
.filter_map(|item| pinned_message(item, folder_id)),
61
);
62
} else {
63
pins.extend(pinned_message(child, None));
64
}
65
}
66
pins.sort_by_key(|pin| Reverse(pin.pinned_at));
67
Ok(pins)
68
}
69
70
fn pin_body(chat_id: &str, message_id: &str, parent_id: &str, operation: &str) -> Value {
71
let mut body = json!({
72
"pinbarId": chat_id,
73
"pinbarItemType": PIN_MESSAGE_TYPE,
74
"pinbarItemId": message_id,
75
"pinbarParentItemId": parent_id,
76
"pinbarOperation": operation,
77
"pinnedMessageProperties": {"messageId": message_id, "rootMessageId": message_id},
78
});
79
if operation == "add" {
80
body["pinbarItemPosition"] = json!(0);
81
}
82
body
83
}
84
85
impl<T: CsaTransport> Pins<T> {
86
pub fn pinbar_url(&self, chat_id: &str) -> String {
87
format!("{}/chats/{}/pinbar", self.api_url, encode(chat_id))
88
}
89
90
/// Newest pin first, with the folder id of pins that live in a folder.
91
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
92
let answer = self
93
.transport
94
.send(Request::get(self.pinbar_url(chat_id)))
95
.await?;
96
ensure_success(&answer)?;
97
parse_chat_pins(&answer.body)
98
}
99
100
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
101
let body = pin_body(chat_id, message_id, "", "add");
102
self.write_pinbar(Method::Post, chat_id, body).await
103
}
104
105
/// `parent_id` is the folder id from `chat_pins`, `None` for a pin at the root.
106
pub async fn unpin_message(
107
&self,
108
chat_id: &str,
109
message_id: &str,
110
parent_id: Option<&str>,
111
) -> Result<()> {
112
let body = pin_body(chat_id, message_id, parent_id.unwrap_or_default(), "remove");
113
self.write_pinbar(Method::Delete, chat_id, body).await
114
}
115
116
async fn write_pinbar(&self, method: Method, chat_id: &str, body: Value) -> Result<()> {
117
let answer = self
118
.transport
119
.send(Request::with_body(method, self.pinbar_url(chat_id), body))
120
.await?;
121
if answer.is_success() {
122
Ok(())
123
} else {
124
Err(api_error(&answer))
125
}
126
}
127
}
128
129
#[cfg(test)]
130
mod tests {
131
use std::sync::Mutex;
132
133
use session::ApiResponse;
134
135
use super::*;
136
137
struct Canned {
138
status: u16,
139
body: Value,
140
requests: Mutex<Vec<Request>>,
141
}
142
143
impl CsaTransport for Canned {
144
async fn send(&self, request: Request) -> Result<ApiResponse> {
145
self.requests.lock().unwrap().push(request);
146
Ok(ApiResponse {
147
status: self.status,
148
body: self.body.clone(),
149
retry_after: None,
150
})
151
}
152
}
153
154
fn canned(status: u16, body: Value) -> Pins<Canned> {
155
Pins::with_transport(
156
Canned {
157
status,
158
body,
159
requests: Mutex::new(Vec::new()),
160
},
161
"emea",
162
)
163
}
164
165
fn pinmsg(message_id: &str, pinned_at: &str) -> Value {
166
json!({
167
"type": "pinmsg",
168
"pinBarItemId": message_id,
169
"pinnedMessageProperties": {
170
"messageId": message_id,
171
"rootMessageId": message_id,
172
"pinnedDateTime": pinned_at,
173
},
174
})
175
}
176
177
#[tokio::test]
178
async fn reads_root_and_folder_pins_newest_first() {
179
let body = json!({
180
"pinBarId": "19:abc@thread.v2",
181
"children": [
182
pinmsg("100", "1791368000000"),
183
{"type": "folder", "pinBarItemId": "default-pinmsg-folder::g1", "children": [
184
pinmsg("300", "1791368300000"),
185
{"type": "tab", "pinBarItemId": "t"},
186
pinmsg("200", "1791368200000"),
187
]},
188
{"type": "tab", "pinBarItemId": "t2"},
189
]
190
});
191
let pins = canned(200, body);
192
let found = pins.chat_pins("19:abc@thread.v2").await.unwrap();
193
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();
194
assert_eq!(ids, ["300", "200", "100"]);
195
assert_eq!(
196
found[0].parent_id.as_deref(),
197
Some("default-pinmsg-folder::g1")
198
);
199
assert_eq!(found[2].parent_id, None);
200
assert_eq!(
201
found[2].pinned_at.map(|time| time.timestamp_millis()),
202
Some(1791368000000)
203
);
204
let requests = pins.transport.requests.lock().unwrap();
205
assert_eq!(requests[0].method, Method::Get);
206
assert_eq!(
207
requests[0].url,
208
"https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar"
209
);
210
}
211
212
#[tokio::test]
213
async fn pin_posts_add_body_at_position_zero() {
214
let pins = canned(201, json!({"pinBarItemId": "100"}));
215
pins.pin_message("19:abc@thread.v2", "100").await.unwrap();
216
let requests = pins.transport.requests.lock().unwrap();
217
assert_eq!(requests[0].method, Method::Post);
218
assert_eq!(
219
requests[0].url,
220
"https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar"
221
);
222
assert_eq!(
223
requests[0].body,
224
Some(json!({
225
"pinbarId": "19:abc@thread.v2",
226
"pinbarItemType": "pinmsg",
227
"pinbarItemId": "100",
228
"pinbarParentItemId": "",
229
"pinbarItemPosition": 0,
230
"pinbarOperation": "add",
231
"pinnedMessageProperties": {"messageId": "100", "rootMessageId": "100"},
232
}))
233
);
234
}
235
236
#[tokio::test]
237
async fn unpin_deletes_with_remove_and_folder_parent() {
238
let pins = canned(204, Value::Null);
239
pins.unpin_message("c", "100", Some("default-pinmsg-folder::g1"))
240
.await
241
.unwrap();
242
pins.unpin_message("c", "100", None).await.unwrap();
243
let requests = pins.transport.requests.lock().unwrap();
244
assert_eq!(requests[0].method, Method::Delete);
245
let body = requests[0].body.as_ref().unwrap();
246
assert_eq!(body["pinbarOperation"], "remove");
247
assert_eq!(body["pinbarParentItemId"], "default-pinmsg-folder::g1");
248
assert!(body.get("pinbarItemPosition").is_none());
249
assert_eq!(requests[1].body.as_ref().unwrap()["pinbarParentItemId"], "");
250
}
251
252
#[tokio::test]
253
async fn failures_are_errors() {
254
let pins = canned(403, json!({}));
255
assert!(pins.chat_pins("c").await.is_err());
256
assert!(pins.pin_message("c", "1").await.is_err());
257
assert!(pins.unpin_message("c", "1", None).await.is_err());
258
}
259
260
#[tokio::test]
261
async fn pinbar_without_children_is_unexpected() {
262
let pins = canned(200, json!({"pinBarId": "c"}));
263
assert!(matches!(
264
pins.chat_pins("c").await,
265
Err(Error::UnexpectedAnswer(_))
266
));
267
}
268
}
@@ -0,0 +1,268 @@1
use std::cmp::Reverse;2
3
use chrono::{DateTime, Utc};4
use serde_json::{Value, json};5
use session::{Method, Request};6
7
use super::Pins;8
use super::chats::{api_error, ensure_success};9
use super::transport::CsaTransport;10
use crate::error::{Error, Result};11
use crate::messages::encode;12
13
const PIN_MESSAGE_TYPE: &str = "pinmsg";14
const FOLDER_TYPE: &str = "folder";15
16
#[derive(Debug, Clone, PartialEq, Eq)]17
pub struct PinnedMessage {18
pub message_id: String,19
pub pinned_at: Option<DateTime<Utc>>,20
pub parent_id: Option<String>,21
}22
23
fn pinned_message(item: &Value, parent_id: Option<&str>) -> Option<PinnedMessage> {24
if item.get("type")?.as_str()? != PIN_MESSAGE_TYPE {25
return None;26
}27
let message_id = item28
.get("pinBarItemId")29
.and_then(Value::as_str)30
.or_else(|| item.pointer("/pinnedMessageProperties/messageId")?.as_str())?31
.to_owned();32
let pinned_at = item33
.pointer("/pinnedMessageProperties/pinnedDateTime")34
.and_then(|value| match value {35
Value::String(text) => text.parse::<i64>().ok(),36
other => other.as_i64(),37
})38
.and_then(DateTime::from_timestamp_millis);39
Some(PinnedMessage {40
message_id,41
pinned_at,42
parent_id: parent_id.map(str::to_owned),43
})44
}45
46
pub fn parse_chat_pins(body: &Value) -> Result<Vec<PinnedMessage>> {47
let children = body48
.get("children")49
.and_then(Value::as_array)50
.ok_or_else(|| Error::UnexpectedAnswer("pinbar children missing".into()))?;51
let mut pins = Vec::new();52
for child in children {53
if child.get("type").and_then(Value::as_str) == Some(FOLDER_TYPE) {54
let folder_id = child.get("pinBarItemId").and_then(Value::as_str);55
let nested = child.get("children").and_then(Value::as_array);56
pins.extend(57
nested58
.into_iter()59
.flatten()60
.filter_map(|item| pinned_message(item, folder_id)),61
);62
} else {63
pins.extend(pinned_message(child, None));64
}65
}66
pins.sort_by_key(|pin| Reverse(pin.pinned_at));67
Ok(pins)68
}69
70
fn pin_body(chat_id: &str, message_id: &str, parent_id: &str, operation: &str) -> Value {71
let mut body = json!({72
"pinbarId": chat_id,73
"pinbarItemType": PIN_MESSAGE_TYPE,74
"pinbarItemId": message_id,75
"pinbarParentItemId": parent_id,76
"pinbarOperation": operation,77
"pinnedMessageProperties": {"messageId": message_id, "rootMessageId": message_id},78
});79
if operation == "add" {80
body["pinbarItemPosition"] = json!(0);81
}82
body83
}84
85
impl<T: CsaTransport> Pins<T> {86
pub fn pinbar_url(&self, chat_id: &str) -> String {87
format!("{}/chats/{}/pinbar", self.api_url, encode(chat_id))88
}89
90
/// Newest pin first, with the folder id of pins that live in a folder.91
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {92
let answer = self93
.transport94
.send(Request::get(self.pinbar_url(chat_id)))95
.await?;96
ensure_success(&answer)?;97
parse_chat_pins(&answer.body)98
}99
100
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {101
let body = pin_body(chat_id, message_id, "", "add");102
self.write_pinbar(Method::Post, chat_id, body).await103
}104
105
/// `parent_id` is the folder id from `chat_pins`, `None` for a pin at the root.106
pub async fn unpin_message(107
&self,108
chat_id: &str,109
message_id: &str,110
parent_id: Option<&str>,111
) -> Result<()> {112
let body = pin_body(chat_id, message_id, parent_id.unwrap_or_default(), "remove");113
self.write_pinbar(Method::Delete, chat_id, body).await114
}115
116
async fn write_pinbar(&self, method: Method, chat_id: &str, body: Value) -> Result<()> {117
let answer = self118
.transport119
.send(Request::with_body(method, self.pinbar_url(chat_id), body))120
.await?;121
if answer.is_success() {122
Ok(())123
} else {124
Err(api_error(&answer))125
}126
}127
}128
129
#[cfg(test)]130
mod tests {131
use std::sync::Mutex;132
133
use session::ApiResponse;134
135
use super::*;136
137
struct Canned {138
status: u16,139
body: Value,140
requests: Mutex<Vec<Request>>,141
}142
143
impl CsaTransport for Canned {144
async fn send(&self, request: Request) -> Result<ApiResponse> {145
self.requests.lock().unwrap().push(request);146
Ok(ApiResponse {147
status: self.status,148
body: self.body.clone(),149
retry_after: None,150
})151
}152
}153
154
fn canned(status: u16, body: Value) -> Pins<Canned> {155
Pins::with_transport(156
Canned {157
status,158
body,159
requests: Mutex::new(Vec::new()),160
},161
"emea",162
)163
}164
165
fn pinmsg(message_id: &str, pinned_at: &str) -> Value {166
json!({167
"type": "pinmsg",168
"pinBarItemId": message_id,169
"pinnedMessageProperties": {170
"messageId": message_id,171
"rootMessageId": message_id,172
"pinnedDateTime": pinned_at,173
},174
})175
}176
177
#[tokio::test]178
async fn reads_root_and_folder_pins_newest_first() {179
let body = json!({180
"pinBarId": "19:abc@thread.v2",181
"children": [182
pinmsg("100", "1791368000000"),183
{"type": "folder", "pinBarItemId": "default-pinmsg-folder::g1", "children": [184
pinmsg("300", "1791368300000"),185
{"type": "tab", "pinBarItemId": "t"},186
pinmsg("200", "1791368200000"),187
]},188
{"type": "tab", "pinBarItemId": "t2"},189
]190
});191
let pins = canned(200, body);192
let found = pins.chat_pins("19:abc@thread.v2").await.unwrap();193
let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect();194
assert_eq!(ids, ["300", "200", "100"]);195
assert_eq!(196
found[0].parent_id.as_deref(),197
Some("default-pinmsg-folder::g1")198
);199
assert_eq!(found[2].parent_id, None);200
assert_eq!(201
found[2].pinned_at.map(|time| time.timestamp_millis()),202
Some(1791368000000)203
);204
let requests = pins.transport.requests.lock().unwrap();205
assert_eq!(requests[0].method, Method::Get);206
assert_eq!(207
requests[0].url,208
"https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar"209
);210
}211
212
#[tokio::test]213
async fn pin_posts_add_body_at_position_zero() {214
let pins = canned(201, json!({"pinBarItemId": "100"}));215
pins.pin_message("19:abc@thread.v2", "100").await.unwrap();216
let requests = pins.transport.requests.lock().unwrap();217
assert_eq!(requests[0].method, Method::Post);218
assert_eq!(219
requests[0].url,220
"https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar"221
);222
assert_eq!(223
requests[0].body,224
Some(json!({225
"pinbarId": "19:abc@thread.v2",226
"pinbarItemType": "pinmsg",227
"pinbarItemId": "100",228
"pinbarParentItemId": "",229
"pinbarItemPosition": 0,230
"pinbarOperation": "add",231
"pinnedMessageProperties": {"messageId": "100", "rootMessageId": "100"},232
}))233
);234
}235
236
#[tokio::test]237
async fn unpin_deletes_with_remove_and_folder_parent() {238
let pins = canned(204, Value::Null);239
pins.unpin_message("c", "100", Some("default-pinmsg-folder::g1"))240
.await241
.unwrap();242
pins.unpin_message("c", "100", None).await.unwrap();243
let requests = pins.transport.requests.lock().unwrap();244
assert_eq!(requests[0].method, Method::Delete);245
let body = requests[0].body.as_ref().unwrap();246
assert_eq!(body["pinbarOperation"], "remove");247
assert_eq!(body["pinbarParentItemId"], "default-pinmsg-folder::g1");248
assert!(body.get("pinbarItemPosition").is_none());249
assert_eq!(requests[1].body.as_ref().unwrap()["pinbarParentItemId"], "");250
}251
252
#[tokio::test]253
async fn failures_are_errors() {254
let pins = canned(403, json!({}));255
assert!(pins.chat_pins("c").await.is_err());256
assert!(pins.pin_message("c", "1").await.is_err());257
assert!(pins.unpin_message("c", "1", None).await.is_err());258
}259
260
#[tokio::test]261
async fn pinbar_without_children_is_unexpected() {262
let pins = canned(200, json!({"pinBarId": "c"}));263
assert!(matches!(264
pins.chat_pins("c").await,265
Err(Error::UnexpectedAnswer(_))266
));267
}268
}@@ -16,6 +16,7 @@ pub enum EventKind {
16
16
ThreadUpdate,
17
17
Typing,
18
18
ReadReceipt,
19
PinsChanged,
19
20
ThreadActivity,
20
21
Control,
21
22
#[serde(other)]
@@ -258,6 +259,16 @@ mod tests {
258
259
assert_eq!(event.received_at.timestamp_millis(), 1791368146999);
259
260
}
260
261
262
#[test]
263
fn decodes_pins_changed_kind() {
264
let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"pins_changed",
265
"conversationId":"19:abc@thread.v2","receivedAt":1}"#;
266
let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {
267
panic!("expected message")
268
};
269
assert_eq!(event.kind, EventKind::PinsChanged);
270
}
271
261
272
#[test]
262
273
fn null_and_empty_ids_become_none() {
263
274
let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",
@@ -16,6 +16,7 @@ pub enum EventKind {16
ThreadUpdate,16
ThreadUpdate,17
Typing,17
Typing,18
ReadReceipt,18
ReadReceipt,19
PinsChanged,19
ThreadActivity,20
ThreadActivity,20
Control,21
Control,21
#[serde(other)]22
#[serde(other)]@@ -258,6 +259,16 @@ mod tests {258
assert_eq!(event.received_at.timestamp_millis(), 1791368146999);259
assert_eq!(event.received_at.timestamp_millis(), 1791368146999);259
}260
}260
261
262
#[test]263
fn decodes_pins_changed_kind() {264
let payload = r#"{"channel":"event","resourceType":"NewMessage","eventKind":"pins_changed",265
"conversationId":"19:abc@thread.v2","receivedAt":1}"#;266
let RealtimeEvent::Message(event) = decode_payload(payload).unwrap() else {267
panic!("expected message")268
};269
assert_eq!(event.kind, EventKind::PinsChanged);270
}271
261
#[test]272
#[test]262
fn null_and_empty_ids_become_none() {273
fn null_and_empty_ids_become_none() {263
let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",274
let payload = r#"{"channel":"event","resourceType":"typing","eventKind":"typing",@@ -0,0 +1,253 @@
1
use std::cmp::Reverse;
2
3
use chrono::{DateTime, Utc};
4
use serde_json::{Value, json};
5
use session::{Method, Request};
6
7
use crate::error::{Error, Result};
8
use crate::messages::{MessageTransport, Messages, encode, ensure_success};
9
10
const SAVED_CONVERSATION: &str = "48:saved";
11
const SAVED_ACTIVITY_TYPE: &str = "savedMessage";
12
const LIST_QUERY: &str = "view=msnp24Equivalent&pageSize=200&startTime=1";
13
14
#[derive(Debug, Clone, PartialEq, Eq)]
15
pub struct SavedMessage {
16
pub conversation_id: String,
17
pub message_id: String,
18
pub root_id: String,
19
pub author_id: Option<String>,
20
pub author_name: Option<String>,
21
pub preview: String,
22
pub saved_at: DateTime<Utc>,
23
pub topic: Option<String>,
24
}
25
26
fn text_or_number(value: &Value, key: &str) -> Option<String> {
27
match value.get(key)? {
28
Value::String(text) if !text.is_empty() => Some(text.clone()),
29
Value::Number(number) => Some(number.to_string()),
30
_ => None,
31
}
32
}
33
34
fn activity_of(message: &Value) -> Option<Value> {
35
match message.pointer("/properties/activity")? {
36
Value::String(text) => serde_json::from_str(text).ok(),
37
object @ Value::Object(_) => Some(object.clone()),
38
_ => None,
39
}
40
}
41
42
fn saved_message(message: &Value) -> Option<SavedMessage> {
43
let activity = activity_of(message)?;
44
if activity.get("activityType")?.as_str()? != SAVED_ACTIVITY_TYPE {
45
return None;
46
}
47
let message_id = text_or_number(&activity, "sourceMessageId")?;
48
let saved_at = DateTime::parse_from_rfc3339(activity.get("activityTimestamp")?.as_str()?)
49
.ok()?
50
.with_timezone(&Utc);
51
Some(SavedMessage {
52
conversation_id: text_or_number(&activity, "sourceThreadId")?,
53
root_id: text_or_number(&activity, "sourceReplyChainId")
54
.unwrap_or_else(|| message_id.clone()),
55
message_id,
56
author_id: text_or_number(&activity, "sourceUserId"),
57
author_name: text_or_number(&activity, "sourceUserImDisplayName"),
58
preview: text_or_number(&activity, "messagePreview").unwrap_or_default(),
59
saved_at,
60
topic: text_or_number(&activity, "sourceThreadTopic"),
61
})
62
}
63
64
pub fn parse_saved_messages(body: &Value) -> Result<Vec<SavedMessage>> {
65
let messages = body
66
.get("messages")
67
.and_then(Value::as_array)
68
.ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;
69
let mut saved: Vec<SavedMessage> = messages.iter().filter_map(saved_message).collect();
70
saved.sort_by_key(|entry| Reverse(entry.saved_at));
71
Ok(saved)
72
}
73
74
impl<T: MessageTransport> Messages<T> {
75
pub fn rc_metadata_url(&self, conversation_id: &str, root_id: &str) -> String {
76
format!(
77
"{}/{}/rcmetadata/{}",
78
self.base_url,
79
encode(conversation_id),
80
encode(root_id)
81
)
82
}
83
84
pub fn saved_list_url(&self) -> String {
85
format!(
86
"{}/{}/messages?{LIST_QUERY}",
87
self.base_url,
88
encode(SAVED_CONVERSATION)
89
)
90
}
91
92
/// `root_id` is the reply chain id: the message id in chats, the root post id in channels.
93
pub async fn set_saved(
94
&self,
95
conversation_id: &str,
96
root_id: &str,
97
message_id: &str,
98
saved: bool,
99
) -> Result<()> {
100
let message_number: u64 = message_id.parse().map_err(|_| {
101
Error::UnexpectedAnswer(format!("message id {message_id} is not numeric"))
102
})?;
103
let body = json!({"s": u8::from(saved), "mid": message_number});
104
let answer = self
105
.transport
106
.send(Request::with_body(
107
Method::Put,
108
self.rc_metadata_url(conversation_id, root_id),
109
body,
110
))
111
.await?;
112
ensure_success(&answer)
113
}
114
115
pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
116
let answer = self
117
.transport
118
.send(Request::get(self.saved_list_url()))
119
.await?;
120
ensure_success(&answer)?;
121
parse_saved_messages(&answer.body)
122
}
123
}
124
125
#[cfg(test)]
126
mod tests {
127
use std::sync::Mutex;
128
129
use session::ApiResponse;
130
131
use super::*;
132
133
struct Canned {
134
status: u16,
135
body: Value,
136
requests: Mutex<Vec<Request>>,
137
}
138
139
impl MessageTransport for Canned {
140
async fn send(&self, request: Request) -> Result<ApiResponse> {
141
self.requests.lock().unwrap().push(request);
142
Ok(ApiResponse {
143
status: self.status,
144
body: self.body.clone(),
145
retry_after: None,
146
})
147
}
148
}
149
150
fn canned(status: u16, body: Value) -> Messages<Canned> {
151
Messages::with_transport(
152
Canned {
153
status,
154
body,
155
requests: Mutex::new(Vec::new()),
156
},
157
"emea",
158
)
159
}
160
161
fn saved_entry(activity: Value) -> Value {
162
json!({"messagetype": "Text", "content": "", "properties": {"activity": activity}})
163
}
164
165
fn activity(message_id: u64, saved_at: &str) -> Value {
166
json!({
167
"activityType": "savedMessage",
168
"activitySubtype": "saved",
169
"sourceThreadId": "19:abc@thread.v2",
170
"sourceMessageId": message_id,
171
"sourceReplyChainId": 1791368000000u64,
172
"sourceUserId": "8:orgid:a",
173
"sourceUserImDisplayName": "Ada",
174
"messagePreview": "hello",
175
"activityTimestamp": saved_at,
176
"sourceThreadTopic": "Project",
177
})
178
}
179
180
#[tokio::test]
181
async fn save_puts_numeric_message_id() {
182
let messages = canned(200, json!({"conversationId": "c"}));
183
messages
184
.set_saved("19:abc@thread.v2", "1791368000000", "1791368000001", true)
185
.await
186
.unwrap();
187
messages
188
.set_saved("19:abc@thread.v2", "1791368000000", "1791368000001", false)
189
.await
190
.unwrap();
191
let requests = messages.transport.requests.lock().unwrap();
192
assert_eq!(requests[0].method, Method::Put);
193
assert_eq!(
194
requests[0].url,
195
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aabc%40thread.v2/rcmetadata/1791368000000"
196
);
197
assert_eq!(
198
requests[0].body,
199
Some(json!({"s": 1, "mid": 1791368000001u64}))
200
);
201
assert_eq!(
202
requests[1].body,
203
Some(json!({"s": 0, "mid": 1791368000001u64}))
204
);
205
}
206
207
#[tokio::test]
208
async fn save_rejects_non_numeric_ids_and_failures() {
209
let messages = canned(200, json!({}));
210
assert!(messages.set_saved("c", "1", "abc", true).await.is_err());
211
assert!(messages.transport.requests.lock().unwrap().is_empty());
212
let failing = canned(403, json!({}));
213
assert!(failing.set_saved("c", "1", "1", true).await.is_err());
214
}
215
216
#[tokio::test]
217
async fn lists_saved_newest_first_from_object_and_string_activity() {
218
let body = json!({"messages": [
219
saved_entry(activity(1791368000001, "2026-10-01T10:00:00.000Z")),
220
saved_entry(json!(activity(1791368000002, "2026-10-03T10:00:00.000Z").to_string())),
221
saved_entry(json!({"activityType": "mention", "sourceThreadId": "x"})),
222
json!({"messagetype": "Text", "properties": {}}),
223
saved_entry(json!("not json")),
224
]});
225
let messages = canned(200, body);
226
let saved = messages.list_saved().await.unwrap();
227
assert_eq!(saved.len(), 2);
228
assert_eq!(saved[0].message_id, "1791368000002");
229
assert_eq!(saved[1].message_id, "1791368000001");
230
assert_eq!(saved[1].conversation_id, "19:abc@thread.v2");
231
assert_eq!(saved[1].root_id, "1791368000000");
232
assert_eq!(saved[1].author_id.as_deref(), Some("8:orgid:a"));
233
assert_eq!(saved[1].author_name.as_deref(), Some("Ada"));
234
assert_eq!(saved[1].preview, "hello");
235
assert_eq!(saved[1].topic.as_deref(), Some("Project"));
236
assert_eq!(saved[1].saved_at.timestamp_millis(), 1_790_848_800_000);
237
let requests = messages.transport.requests.lock().unwrap();
238
assert_eq!(requests[0].method, Method::Get);
239
assert_eq!(
240
requests[0].url,
241
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Asaved/messages?view=msnp24Equivalent&pageSize=200&startTime=1"
242
);
243
}
244
245
#[tokio::test]
246
async fn list_without_messages_is_unexpected() {
247
let messages = canned(200, json!({}));
248
assert!(matches!(
249
messages.list_saved().await,
250
Err(Error::UnexpectedAnswer(_))
251
));
252
}
253
}
@@ -0,0 +1,253 @@1
use std::cmp::Reverse;2
3
use chrono::{DateTime, Utc};4
use serde_json::{Value, json};5
use session::{Method, Request};6
7
use crate::error::{Error, Result};8
use crate::messages::{MessageTransport, Messages, encode, ensure_success};9
10
const SAVED_CONVERSATION: &str = "48:saved";11
const SAVED_ACTIVITY_TYPE: &str = "savedMessage";12
const LIST_QUERY: &str = "view=msnp24Equivalent&pageSize=200&startTime=1";13
14
#[derive(Debug, Clone, PartialEq, Eq)]15
pub struct SavedMessage {16
pub conversation_id: String,17
pub message_id: String,18
pub root_id: String,19
pub author_id: Option<String>,20
pub author_name: Option<String>,21
pub preview: String,22
pub saved_at: DateTime<Utc>,23
pub topic: Option<String>,24
}25
26
fn text_or_number(value: &Value, key: &str) -> Option<String> {27
match value.get(key)? {28
Value::String(text) if !text.is_empty() => Some(text.clone()),29
Value::Number(number) => Some(number.to_string()),30
_ => None,31
}32
}33
34
fn activity_of(message: &Value) -> Option<Value> {35
match message.pointer("/properties/activity")? {36
Value::String(text) => serde_json::from_str(text).ok(),37
object @ Value::Object(_) => Some(object.clone()),38
_ => None,39
}40
}41
42
fn saved_message(message: &Value) -> Option<SavedMessage> {43
let activity = activity_of(message)?;44
if activity.get("activityType")?.as_str()? != SAVED_ACTIVITY_TYPE {45
return None;46
}47
let message_id = text_or_number(&activity, "sourceMessageId")?;48
let saved_at = DateTime::parse_from_rfc3339(activity.get("activityTimestamp")?.as_str()?)49
.ok()?50
.with_timezone(&Utc);51
Some(SavedMessage {52
conversation_id: text_or_number(&activity, "sourceThreadId")?,53
root_id: text_or_number(&activity, "sourceReplyChainId")54
.unwrap_or_else(|| message_id.clone()),55
message_id,56
author_id: text_or_number(&activity, "sourceUserId"),57
author_name: text_or_number(&activity, "sourceUserImDisplayName"),58
preview: text_or_number(&activity, "messagePreview").unwrap_or_default(),59
saved_at,60
topic: text_or_number(&activity, "sourceThreadTopic"),61
})62
}63
64
pub fn parse_saved_messages(body: &Value) -> Result<Vec<SavedMessage>> {65
let messages = body66
.get("messages")67
.and_then(Value::as_array)68
.ok_or_else(|| Error::UnexpectedAnswer("no messages list".into()))?;69
let mut saved: Vec<SavedMessage> = messages.iter().filter_map(saved_message).collect();70
saved.sort_by_key(|entry| Reverse(entry.saved_at));71
Ok(saved)72
}73
74
impl<T: MessageTransport> Messages<T> {75
pub fn rc_metadata_url(&self, conversation_id: &str, root_id: &str) -> String {76
format!(77
"{}/{}/rcmetadata/{}",78
self.base_url,79
encode(conversation_id),80
encode(root_id)81
)82
}83
84
pub fn saved_list_url(&self) -> String {85
format!(86
"{}/{}/messages?{LIST_QUERY}",87
self.base_url,88
encode(SAVED_CONVERSATION)89
)90
}91
92
/// `root_id` is the reply chain id: the message id in chats, the root post id in channels.93
pub async fn set_saved(94
&self,95
conversation_id: &str,96
root_id: &str,97
message_id: &str,98
saved: bool,99
) -> Result<()> {100
let message_number: u64 = message_id.parse().map_err(|_| {101
Error::UnexpectedAnswer(format!("message id {message_id} is not numeric"))102
})?;103
let body = json!({"s": u8::from(saved), "mid": message_number});104
let answer = self105
.transport106
.send(Request::with_body(107
Method::Put,108
self.rc_metadata_url(conversation_id, root_id),109
body,110
))111
.await?;112
ensure_success(&answer)113
}114
115
pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {116
let answer = self117
.transport118
.send(Request::get(self.saved_list_url()))119
.await?;120
ensure_success(&answer)?;121
parse_saved_messages(&answer.body)122
}123
}124
125
#[cfg(test)]126
mod tests {127
use std::sync::Mutex;128
129
use session::ApiResponse;130
131
use super::*;132
133
struct Canned {134
status: u16,135
body: Value,136
requests: Mutex<Vec<Request>>,137
}138
139
impl MessageTransport for Canned {140
async fn send(&self, request: Request) -> Result<ApiResponse> {141
self.requests.lock().unwrap().push(request);142
Ok(ApiResponse {143
status: self.status,144
body: self.body.clone(),145
retry_after: None,146
})147
}148
}149
150
fn canned(status: u16, body: Value) -> Messages<Canned> {151
Messages::with_transport(152
Canned {153
status,154
body,155
requests: Mutex::new(Vec::new()),156
},157
"emea",158
)159
}160
161
fn saved_entry(activity: Value) -> Value {162
json!({"messagetype": "Text", "content": "", "properties": {"activity": activity}})163
}164
165
fn activity(message_id: u64, saved_at: &str) -> Value {166
json!({167
"activityType": "savedMessage",168
"activitySubtype": "saved",169
"sourceThreadId": "19:abc@thread.v2",170
"sourceMessageId": message_id,171
"sourceReplyChainId": 1791368000000u64,172
"sourceUserId": "8:orgid:a",173
"sourceUserImDisplayName": "Ada",174
"messagePreview": "hello",175
"activityTimestamp": saved_at,176
"sourceThreadTopic": "Project",177
})178
}179
180
#[tokio::test]181
async fn save_puts_numeric_message_id() {182
let messages = canned(200, json!({"conversationId": "c"}));183
messages184
.set_saved("19:abc@thread.v2", "1791368000000", "1791368000001", true)185
.await186
.unwrap();187
messages188
.set_saved("19:abc@thread.v2", "1791368000000", "1791368000001", false)189
.await190
.unwrap();191
let requests = messages.transport.requests.lock().unwrap();192
assert_eq!(requests[0].method, Method::Put);193
assert_eq!(194
requests[0].url,195
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Aabc%40thread.v2/rcmetadata/1791368000000"196
);197
assert_eq!(198
requests[0].body,199
Some(json!({"s": 1, "mid": 1791368000001u64}))200
);201
assert_eq!(202
requests[1].body,203
Some(json!({"s": 0, "mid": 1791368000001u64}))204
);205
}206
207
#[tokio::test]208
async fn save_rejects_non_numeric_ids_and_failures() {209
let messages = canned(200, json!({}));210
assert!(messages.set_saved("c", "1", "abc", true).await.is_err());211
assert!(messages.transport.requests.lock().unwrap().is_empty());212
let failing = canned(403, json!({}));213
assert!(failing.set_saved("c", "1", "1", true).await.is_err());214
}215
216
#[tokio::test]217
async fn lists_saved_newest_first_from_object_and_string_activity() {218
let body = json!({"messages": [219
saved_entry(activity(1791368000001, "2026-10-01T10:00:00.000Z")),220
saved_entry(json!(activity(1791368000002, "2026-10-03T10:00:00.000Z").to_string())),221
saved_entry(json!({"activityType": "mention", "sourceThreadId": "x"})),222
json!({"messagetype": "Text", "properties": {}}),223
saved_entry(json!("not json")),224
]});225
let messages = canned(200, body);226
let saved = messages.list_saved().await.unwrap();227
assert_eq!(saved.len(), 2);228
assert_eq!(saved[0].message_id, "1791368000002");229
assert_eq!(saved[1].message_id, "1791368000001");230
assert_eq!(saved[1].conversation_id, "19:abc@thread.v2");231
assert_eq!(saved[1].root_id, "1791368000000");232
assert_eq!(saved[1].author_id.as_deref(), Some("8:orgid:a"));233
assert_eq!(saved[1].author_name.as_deref(), Some("Ada"));234
assert_eq!(saved[1].preview, "hello");235
assert_eq!(saved[1].topic.as_deref(), Some("Project"));236
assert_eq!(saved[1].saved_at.timestamp_millis(), 1_790_848_800_000);237
let requests = messages.transport.requests.lock().unwrap();238
assert_eq!(requests[0].method, Method::Get);239
assert_eq!(240
requests[0].url,241
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/48%3Asaved/messages?view=msnp24Equivalent&pageSize=200&startTime=1"242
);243
}244
245
#[tokio::test]246
async fn list_without_messages_is_unexpected() {247
let messages = canned(200, json!({}));248
assert!(matches!(249
messages.list_saved().await,250
Err(Error::UnexpectedAnswer(_))251
));252
}253
}@@ -13,6 +13,7 @@ chatsvc.workspace = true
13
13
chrono.workspace = true
14
14
futures-util.workspace = true
15
15
graph.workspace = true
16
percent-encoding.workspace = true
16
17
regex.workspace = true
17
18
scraper.workspace = true
18
19
session.workspace = true
@@ -13,6 +13,7 @@ chatsvc.workspace = true13
chrono.workspace = true13
chrono.workspace = true14
futures-util.workspace = true14
futures-util.workspace = true15
graph.workspace = true15
graph.workspace = true16
percent-encoding.workspace = true16
regex.workspace = true17
regex.workspace = true17
scraper.workspace = true18
scraper.workspace = true18
session.workspace = true19
session.workspace = true@@ -1,5 +1,5 @@
1
1
use chatsvc::ConversationRef;
2
use chrono::{Duration, Utc};
2
use chrono::{DateTime, Duration, Utc};
3
3
use graph::{
4
4
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,
5
5
};
@@ -376,7 +376,15 @@ impl<R: Remote> SyncEngine<R> {
376
376
.ok_or(Error::Unsupported(
377
377
"marking a chat without messages as unread",
378
378
))?;
379
let last_read_at = last_message_at - Duration::milliseconds(1);
379
self.mark_unread_from(chat_id, last_message_at).await
380
}
381
382
pub async fn mark_unread_from(
383
&self,
384
chat_id: &str,
385
message_created_at: DateTime<Utc>,
386
) -> Result<()> {
387
let last_read_at = message_created_at - Duration::milliseconds(1);
380
388
let user_id = self.my_user_id().await?;
381
389
let tenant_id = self.my_tenant_id(chat_id).await?;
382
390
self.remote
@@ -1,5 +1,5 @@1
use chatsvc::ConversationRef;1
use chatsvc::ConversationRef;2
use chrono::{Duration, Utc};2
use chrono::{DateTime, Duration, Utc};3
use graph::{3
use graph::{4
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,4
FileReference, MessageExtras, MessageTarget, OutgoingMention, UploadDestination, UploadedFile,5
};5
};@@ -376,7 +376,15 @@ impl<R: Remote> SyncEngine<R> {376
.ok_or(Error::Unsupported(376
.ok_or(Error::Unsupported(377
"marking a chat without messages as unread",377
"marking a chat without messages as unread",378
))?;378
))?;379
let last_read_at = last_message_at - Duration::milliseconds(1);379
self.mark_unread_from(chat_id, last_message_at).await380
}381
382
pub async fn mark_unread_from(383
&self,384
chat_id: &str,385
message_created_at: DateTime<Utc>,386
) -> Result<()> {387
let last_read_at = message_created_at - Duration::milliseconds(1);380
let user_id = self.my_user_id().await?;388
let user_id = self.my_user_id().await?;381
let tenant_id = self.my_tenant_id(chat_id).await?;389
let tenant_id = self.my_tenant_id(chat_id).await?;382
self.remote390
self.remote@@ -3,6 +3,7 @@ pub enum CoreEvent {
3
3
SidebarChanged,
4
4
MessagesChanged { conversation_id: String },
5
5
ReceiptsChanged { conversation_id: String },
6
PinsChanged { conversation_id: String },
6
7
AvatarsChanged { user_ids: Vec<String> },
7
8
ImagesChanged { keys: Vec<String> },
8
9
FoldersChanged,
@@ -3,6 +3,7 @@ pub enum CoreEvent {3
SidebarChanged,3
SidebarChanged,4
MessagesChanged { conversation_id: String },4
MessagesChanged { conversation_id: String },5
ReceiptsChanged { conversation_id: String },5
ReceiptsChanged { conversation_id: String },6
PinsChanged { conversation_id: String },6
AvatarsChanged { user_ids: Vec<String> },7
AvatarsChanged { user_ids: Vec<String> },7
ImagesChanged { keys: Vec<String> },8
ImagesChanged { keys: Vec<String> },8
FoldersChanged,9
FoldersChanged,@@ -8,8 +8,8 @@ mod download;
8
8
mod draft;
9
9
mod engine;
10
10
mod error;
11
mod external_image;
12
11
mod events;
12
mod external_image;
13
13
mod folders;
14
14
mod gifs;
15
15
mod image_size;
@@ -19,6 +19,8 @@ mod links;
19
19
mod mapping;
20
20
mod markdown;
21
21
mod mentions;
22
mod message_actions;
23
mod message_link;
22
24
mod people;
23
25
mod presence;
24
26
mod preview;
@@ -43,7 +45,7 @@ pub use card_inputs::{
43
45
MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,
44
46
collect_input_values, merge_input_data,
45
47
};
46
pub use chatsvc::{ChatApp, Gif, ScheduledDraft};
48
pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};
47
49
pub use draft::{
48
50
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
49
51
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,
@@ -51,17 +53,18 @@ pub use draft::{
51
53
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};
52
54
pub use error::{Error, Result};
53
55
pub use events::CoreEvent;
56
pub use external_image::external_image_url;
54
57
pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};
55
58
pub use graph::{
56
59
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,
57
60
UploadedFile,
58
61
};
59
pub use external_image::external_image_url;
60
62
pub use images::StoredImage;
61
63
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
62
64
pub use mapping::{chat_record, message_record};
63
65
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
64
66
pub use mentions::MentionInput;
67
pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
65
68
pub use people::{MentionCandidate, PersonCandidate, PersonSource};
66
69
pub use presence::{Availability, Presence};
67
70
pub use preview::preview_text;
@@ -8,8 +8,8 @@ mod download;8
mod draft;8
mod draft;9
mod engine;9
mod engine;10
mod error;10
mod error;11
mod external_image;12
mod events;11
mod events;12
mod external_image;13
mod folders;13
mod folders;14
mod gifs;14
mod gifs;15
mod image_size;15
mod image_size;@@ -19,6 +19,8 @@ mod links;19
mod mapping;19
mod mapping;20
mod markdown;20
mod markdown;21
mod mentions;21
mod mentions;22
mod message_actions;23
mod message_link;22
mod people;24
mod people;23
mod presence;25
mod presence;24
mod preview;26
mod preview;@@ -43,7 +45,7 @@ pub use card_inputs::{43
MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,45
MomentInput, NumberInput, TIME_PLACEHOLDER, TextInput, TextStyle, ToggleInput,44
collect_input_values, merge_input_data,46
collect_input_values, merge_input_data,45
};47
};46
pub use chatsvc::{ChatApp, Gif, ScheduledDraft};48
pub use chatsvc::{ChatApp, ForwardResult, Gif, PinnedMessage, SavedMessage, ScheduledDraft};47
pub use draft::{49
pub use draft::{48
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,50
Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,49
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,51
SizeStep, TypingStyle, changed_span, has_markdown, link_url, map_offset, reverse_edits,@@ -51,17 +53,18 @@ pub use draft::{51
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};53
pub use engine::{Delta, Me, SidebarSummary, SyncConfig, SyncEngine};52
pub use error::{Error, Result};54
pub use error::{Error, Result};53
pub use events::CoreEvent;55
pub use events::CoreEvent;56
pub use external_image::external_image_url;54
pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};57
pub use folders::{BoxFuture, ChatFolder, ChatsvcFolderSource, FolderKind, FolderSource};55
pub use graph::{58
pub use graph::{56
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,59
FileReference, HostedImage, KeptAttachment, MentionTarget, MessageExtras, SharedFile,57
UploadedFile,60
UploadedFile,58
};61
};59
pub use external_image::external_image_url;60
pub use images::StoredImage;62
pub use images::StoredImage;61
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};63
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};62
pub use mapping::{chat_record, message_record};64
pub use mapping::{chat_record, message_record};63
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};65
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};64
pub use mentions::MentionInput;66
pub use mentions::MentionInput;67
pub use message_link::{ChannelLinkInput, channel_message_link, chat_message_link};65
pub use people::{MentionCandidate, PersonCandidate, PersonSource};68
pub use people::{MentionCandidate, PersonCandidate, PersonSource};66
pub use presence::{Availability, Presence};69
pub use presence::{Availability, Presence};67
pub use preview::preview_text;70
pub use preview::preview_text;@@ -0,0 +1,164 @@
1
use chatsvc::{EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};
2
3
use crate::engine::{Conversation, SyncEngine};
4
use crate::error::{Error, Result};
5
use crate::events::CoreEvent;
6
use crate::markdown::markdown_to_html;
7
use crate::message_link::{ChannelLinkInput, channel_message_link, chat_message_link};
8
use crate::remote::Remote;
9
use crate::scheduled::NOTES_CHAT_ID;
10
11
impl<R: Remote> SyncEngine<R> {
12
/// `message_ids` holds 1 to 5 ids, oldest first.
13
pub async fn forward_messages(
14
&self,
15
source_conversation_id: &str,
16
target_conversation_id: &str,
17
message_ids: &[String],
18
comment_markdown: &str,
19
) -> Result<ForwardResult> {
20
let comment_html = if comment_markdown.is_empty() {
21
String::new()
22
} else {
23
markdown_to_html(comment_markdown)
24
};
25
let result = self
26
.remote
27
.forward_messages(
28
source_conversation_id,
29
target_conversation_id,
30
message_ids,
31
&comment_html,
32
)
33
.await?;
34
let refreshed = [result.thread_id.as_str(), target_conversation_id]
35
.into_iter()
36
.find(|conversation_id| self.resolve(conversation_id).is_ok());
37
if let Some(conversation_id) = refreshed
38
&& let Err(error) = self.fetch_newer(conversation_id).await
39
{
40
self.report(format!("cannot refresh a forward target: {error}"));
41
}
42
Ok(result)
43
}
44
45
/// `root_id` is the channel root post id, `None` in chats.
46
pub async fn set_saved(
47
&self,
48
conversation_id: &str,
49
message_id: &str,
50
root_id: Option<&str>,
51
saved: bool,
52
) -> Result<()> {
53
self.remote
54
.set_saved(
55
conversation_id,
56
root_id.unwrap_or(message_id),
57
message_id,
58
saved,
59
)
60
.await
61
}
62
63
pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
64
self.remote.list_saved().await
65
}
66
67
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
68
self.ensure_chat(chat_id)?;
69
self.remote.chat_pins(chat_id).await
70
}
71
72
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
73
self.ensure_chat(chat_id)?;
74
self.remote.pin_message(chat_id, message_id).await?;
75
self.announce_pins(chat_id);
76
Ok(())
77
}
78
79
pub async fn unpin_message(
80
&self,
81
chat_id: &str,
82
message_id: &str,
83
parent_id: Option<&str>,
84
) -> Result<()> {
85
self.ensure_chat(chat_id)?;
86
self.remote
87
.unpin_message(chat_id, message_id, parent_id)
88
.await?;
89
self.announce_pins(chat_id);
90
Ok(())
91
}
92
93
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {
94
let Conversation::Channel { team_id } = self.resolve(conversation_id)? else {
95
let notes_oid = if conversation_id == NOTES_CHAT_ID {
96
Some(self.my_user_id().await?)
97
} else {
98
None
99
};
100
return Ok(chat_message_link(
101
conversation_id,
102
message_id,
103
notes_oid.as_deref(),
104
));
105
};
106
let channel = self
107
.store
108
.channel(conversation_id)?
109
.ok_or_else(|| Error::UnknownConversation(conversation_id.to_owned()))?;
110
let team = self
111
.store
112
.team(&team_id)?
113
.ok_or_else(|| Error::UnknownConversation(team_id.clone()))?;
114
let record = self
115
.store
116
.messages_by_id(conversation_id, &[message_id.to_owned()])?
117
.remove(message_id)
118
.ok_or(Error::Unsupported("a link to an uncached message"))?;
119
let any_chat_id = self
120
.store
121
.sidebar()?
122
.chats
123
.into_iter()
124
.next()
125
.map(|chat| chat.id)
126
.ok_or(Error::Unsupported("a channel link without a known chat"))?;
127
let tenant_id = self.my_tenant_id(&any_chat_id).await?;
128
Ok(channel_message_link(&ChannelLinkInput {
129
tenant_id,
130
group_id: team_id,
131
channel_id: conversation_id.to_owned(),
132
team_name: team.name,
133
channel_name: channel.name,
134
root_id: record
135
.reply_to_id
136
.clone()
137
.unwrap_or_else(|| record.message_id.clone()),
138
message_id: record.message_id,
139
created_ms: record.created_at.timestamp_millis(),
140
}))
141
}
142
143
pub fn handle_pin_event(&self, event: &MessageEvent) {
144
if event.kind != EventKind::PinsChanged {
145
return;
146
}
147
if let Some(conversation_id) = event.conversation_id.as_deref() {
148
self.announce_pins(conversation_id);
149
}
150
}
151
152
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {
153
match self.resolve(conversation_id)? {
154
Conversation::Chat => Ok(()),
155
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),
156
}
157
}
158
159
fn announce_pins(&self, conversation_id: &str) {
160
let _ = self.events.send(CoreEvent::PinsChanged {
161
conversation_id: conversation_id.to_owned(),
162
});
163
}
164
}
@@ -0,0 +1,164 @@1
use chatsvc::{EventKind, ForwardResult, MessageEvent, PinnedMessage, SavedMessage};2
3
use crate::engine::{Conversation, SyncEngine};4
use crate::error::{Error, Result};5
use crate::events::CoreEvent;6
use crate::markdown::markdown_to_html;7
use crate::message_link::{ChannelLinkInput, channel_message_link, chat_message_link};8
use crate::remote::Remote;9
use crate::scheduled::NOTES_CHAT_ID;10
11
impl<R: Remote> SyncEngine<R> {12
/// `message_ids` holds 1 to 5 ids, oldest first.13
pub async fn forward_messages(14
&self,15
source_conversation_id: &str,16
target_conversation_id: &str,17
message_ids: &[String],18
comment_markdown: &str,19
) -> Result<ForwardResult> {20
let comment_html = if comment_markdown.is_empty() {21
String::new()22
} else {23
markdown_to_html(comment_markdown)24
};25
let result = self26
.remote27
.forward_messages(28
source_conversation_id,29
target_conversation_id,30
message_ids,31
&comment_html,32
)33
.await?;34
let refreshed = [result.thread_id.as_str(), target_conversation_id]35
.into_iter()36
.find(|conversation_id| self.resolve(conversation_id).is_ok());37
if let Some(conversation_id) = refreshed38
&& let Err(error) = self.fetch_newer(conversation_id).await39
{40
self.report(format!("cannot refresh a forward target: {error}"));41
}42
Ok(result)43
}44
45
/// `root_id` is the channel root post id, `None` in chats.46
pub async fn set_saved(47
&self,48
conversation_id: &str,49
message_id: &str,50
root_id: Option<&str>,51
saved: bool,52
) -> Result<()> {53
self.remote54
.set_saved(55
conversation_id,56
root_id.unwrap_or(message_id),57
message_id,58
saved,59
)60
.await61
}62
63
pub async fn list_saved(&self) -> Result<Vec<SavedMessage>> {64
self.remote.list_saved().await65
}66
67
pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {68
self.ensure_chat(chat_id)?;69
self.remote.chat_pins(chat_id).await70
}71
72
pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {73
self.ensure_chat(chat_id)?;74
self.remote.pin_message(chat_id, message_id).await?;75
self.announce_pins(chat_id);76
Ok(())77
}78
79
pub async fn unpin_message(80
&self,81
chat_id: &str,82
message_id: &str,83
parent_id: Option<&str>,84
) -> Result<()> {85
self.ensure_chat(chat_id)?;86
self.remote87
.unpin_message(chat_id, message_id, parent_id)88
.await?;89
self.announce_pins(chat_id);90
Ok(())91
}92
93
pub async fn message_link(&self, conversation_id: &str, message_id: &str) -> Result<String> {94
let Conversation::Channel { team_id } = self.resolve(conversation_id)? else {95
let notes_oid = if conversation_id == NOTES_CHAT_ID {96
Some(self.my_user_id().await?)97
} else {98
None99
};100
return Ok(chat_message_link(101
conversation_id,102
message_id,103
notes_oid.as_deref(),104
));105
};106
let channel = self107
.store108
.channel(conversation_id)?109
.ok_or_else(|| Error::UnknownConversation(conversation_id.to_owned()))?;110
let team = self111
.store112
.team(&team_id)?113
.ok_or_else(|| Error::UnknownConversation(team_id.clone()))?;114
let record = self115
.store116
.messages_by_id(conversation_id, &[message_id.to_owned()])?117
.remove(message_id)118
.ok_or(Error::Unsupported("a link to an uncached message"))?;119
let any_chat_id = self120
.store121
.sidebar()?122
.chats123
.into_iter()124
.next()125
.map(|chat| chat.id)126
.ok_or(Error::Unsupported("a channel link without a known chat"))?;127
let tenant_id = self.my_tenant_id(&any_chat_id).await?;128
Ok(channel_message_link(&ChannelLinkInput {129
tenant_id,130
group_id: team_id,131
channel_id: conversation_id.to_owned(),132
team_name: team.name,133
channel_name: channel.name,134
root_id: record135
.reply_to_id136
.clone()137
.unwrap_or_else(|| record.message_id.clone()),138
message_id: record.message_id,139
created_ms: record.created_at.timestamp_millis(),140
}))141
}142
143
pub fn handle_pin_event(&self, event: &MessageEvent) {144
if event.kind != EventKind::PinsChanged {145
return;146
}147
if let Some(conversation_id) = event.conversation_id.as_deref() {148
self.announce_pins(conversation_id);149
}150
}151
152
fn ensure_chat(&self, conversation_id: &str) -> Result<()> {153
match self.resolve(conversation_id)? {154
Conversation::Chat => Ok(()),155
Conversation::Channel { .. } => Err(Error::Unsupported("pinned messages in a channel")),156
}157
}158
159
fn announce_pins(&self, conversation_id: &str) {160
let _ = self.events.send(CoreEvent::PinsChanged {161
conversation_id: conversation_id.to_owned(),162
});163
}164
}@@ -0,0 +1,100 @@
1
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};
2
use serde_json::json;
3
4
const LINK_HOST: &str = "https://teams.microsoft.com";
5
6
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC
7
.remove(b'-')
8
.remove(b'_')
9
.remove(b'.')
10
.remove(b'!')
11
.remove(b'~')
12
.remove(b'*')
13
.remove(b'\'')
14
.remove(b'(')
15
.remove(b')');
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct ChannelLinkInput {
19
pub tenant_id: String,
20
pub group_id: String,
21
pub channel_id: String,
22
pub team_name: String,
23
pub channel_name: String,
24
pub root_id: String,
25
pub message_id: String,
26
pub created_ms: i64,
27
}
28
29
fn encode(value: &str) -> String {
30
utf8_percent_encode(value, ENCODE_COMPONENT).to_string()
31
}
32
33
/// `notes_oid` is the own object id, needed for the notes chat only.
34
pub fn chat_message_link(
35
conversation_id: &str,
36
message_id: &str,
37
notes_oid: Option<&str>,
38
) -> String {
39
let mut context = json!({"contextType": "chat"});
40
if let Some(oid) = notes_oid {
41
context["oid"] = json!(oid);
42
}
43
format!(
44
"{LINK_HOST}/l/message/{conversation_id}/{message_id}?context={}",
45
encode(&context.to_string())
46
)
47
}
48
49
pub fn channel_message_link(input: &ChannelLinkInput) -> String {
50
format!(
51
"{LINK_HOST}/l/message/{}/{}?tenantId={}&groupId={}&parentMessageId={}&teamName={}&channelName={}&createdTime={}",
52
input.channel_id,
53
input.message_id,
54
encode(&input.tenant_id),
55
encode(&input.group_id),
56
encode(&input.root_id),
57
encode(&input.team_name),
58
encode(&input.channel_name),
59
input.created_ms
60
)
61
}
62
63
#[cfg(test)]
64
mod tests {
65
use super::*;
66
67
#[test]
68
fn chat_link_keeps_ids_raw_and_encodes_context() {
69
assert_eq!(
70
chat_message_link("19:abc@thread.v2", "1791368000000", None),
71
"https://teams.microsoft.com/l/message/19:abc@thread.v2/1791368000000?context=%7B%22contextType%22%3A%22chat%22%7D"
72
);
73
}
74
75
#[test]
76
fn notes_link_carries_the_object_id() {
77
assert_eq!(
78
chat_message_link("48:notes", "1791368000000", Some("aa-bb")),
79
"https://teams.microsoft.com/l/message/48:notes/1791368000000?context=%7B%22contextType%22%3A%22chat%22%2C%22oid%22%3A%22aa-bb%22%7D"
80
);
81
}
82
83
#[test]
84
fn channel_link_encodes_names_and_orders_params() {
85
let input = ChannelLinkInput {
86
tenant_id: "tenant-1".into(),
87
group_id: "group-1".into(),
88
channel_id: "19:chan@thread.tacv2".into(),
89
team_name: "R&D Team".into(),
90
channel_name: "General: News".into(),
91
root_id: "1791368000000".into(),
92
message_id: "1791368000555".into(),
93
created_ms: 1791368000555,
94
};
95
assert_eq!(
96
channel_message_link(&input),
97
"https://teams.microsoft.com/l/message/19:chan@thread.tacv2/1791368000555?tenantId=tenant-1&groupId=group-1&parentMessageId=1791368000000&teamName=R%26D%20Team&channelName=General%3A%20News&createdTime=1791368000555"
98
);
99
}
100
}
@@ -0,0 +1,100 @@1
use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode};2
use serde_json::json;3
4
const LINK_HOST: &str = "https://teams.microsoft.com";5
6
const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC7
.remove(b'-')8
.remove(b'_')9
.remove(b'.')10
.remove(b'!')11
.remove(b'~')12
.remove(b'*')13
.remove(b'\'')14
.remove(b'(')15
.remove(b')');16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub struct ChannelLinkInput {19
pub tenant_id: String,20
pub group_id: String,21
pub channel_id: String,22
pub team_name: String,23
pub channel_name: String,24
pub root_id: String,25
pub message_id: String,26
pub created_ms: i64,27
}28
29
fn encode(value: &str) -> String {30
utf8_percent_encode(value, ENCODE_COMPONENT).to_string()31
}32
33
/// `notes_oid` is the own object id, needed for the notes chat only.34
pub fn chat_message_link(35
conversation_id: &str,36
message_id: &str,37
notes_oid: Option<&str>,38
) -> String {39
let mut context = json!({"contextType": "chat"});40
if let Some(oid) = notes_oid {41
context["oid"] = json!(oid);42
}43
format!(44
"{LINK_HOST}/l/message/{conversation_id}/{message_id}?context={}",45
encode(&context.to_string())46
)47
}48
49
pub fn channel_message_link(input: &ChannelLinkInput) -> String {50
format!(51
"{LINK_HOST}/l/message/{}/{}?tenantId={}&groupId={}&parentMessageId={}&teamName={}&channelName={}&createdTime={}",52
input.channel_id,53
input.message_id,54
encode(&input.tenant_id),55
encode(&input.group_id),56
encode(&input.root_id),57
encode(&input.team_name),58
encode(&input.channel_name),59
input.created_ms60
)61
}62
63
#[cfg(test)]64
mod tests {65
use super::*;66
67
#[test]68
fn chat_link_keeps_ids_raw_and_encodes_context() {69
assert_eq!(70
chat_message_link("19:abc@thread.v2", "1791368000000", None),71
"https://teams.microsoft.com/l/message/19:abc@thread.v2/1791368000000?context=%7B%22contextType%22%3A%22chat%22%7D"72
);73
}74
75
#[test]76
fn notes_link_carries_the_object_id() {77
assert_eq!(78
chat_message_link("48:notes", "1791368000000", Some("aa-bb")),79
"https://teams.microsoft.com/l/message/48:notes/1791368000000?context=%7B%22contextType%22%3A%22chat%22%2C%22oid%22%3A%22aa-bb%22%7D"80
);81
}82
83
#[test]84
fn channel_link_encodes_names_and_orders_params() {85
let input = ChannelLinkInput {86
tenant_id: "tenant-1".into(),87
group_id: "group-1".into(),88
channel_id: "19:chan@thread.tacv2".into(),89
team_name: "R&D Team".into(),90
channel_name: "General: News".into(),91
root_id: "1791368000000".into(),92
message_id: "1791368000555".into(),93
created_ms: 1791368000555,94
};95
assert_eq!(96
channel_message_link(&input),97
"https://teams.microsoft.com/l/message/19:chan@thread.tacv2/1791368000555?tenantId=tenant-1&groupId=group-1&parentMessageId=1791368000000&teamName=R%26D%20Team&channelName=General%3A%20News&createdTime=1791368000555"98
);99
}100
}@@ -1,7 +1,7 @@
1
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,
3
LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts, ScheduledDraft,
4
ScheduledDrafts,
2
CardActions, ChatApp, ConversationRef, Conversations, ForwardResult, Gif, Gifs, InvokeRequest,
3
InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages, PinnedMessage, Pins, Receipts,
4
SavedMessage, ScheduledDraft, ScheduledDrafts,
5
5
};
6
6
use chrono::{DateTime, Utc};
7
7
use graph::{
@@ -215,6 +215,47 @@ pub trait Remote {
215
215
Err(Error::Unsupported("read receipts"))
216
216
}
217
217
218
async fn forward_messages(
219
&self,
220
_source_conversation_id: &str,
221
_target_conversation_id: &str,
222
_message_ids: &[String],
223
_comment_html: &str,
224
) -> Result<ForwardResult> {
225
Err(Error::Unsupported("forwarding messages"))
226
}
227
228
async fn set_saved(
229
&self,
230
_conversation_id: &str,
231
_root_id: &str,
232
_message_id: &str,
233
_saved: bool,
234
) -> Result<()> {
235
Err(Error::Unsupported("saving messages"))
236
}
237
238
async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
239
Err(Error::Unsupported("saved messages"))
240
}
241
242
async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {
243
Err(Error::Unsupported("pinned messages"))
244
}
245
246
async fn pin_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
247
Err(Error::Unsupported("pinning messages"))
248
}
249
250
async fn unpin_message(
251
&self,
252
_chat_id: &str,
253
_message_id: &str,
254
_parent_id: Option<&str>,
255
) -> Result<()> {
256
Err(Error::Unsupported("pinning messages"))
257
}
258
218
259
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {
219
260
Err(Error::Unsupported("chat apps"))
220
261
}
@@ -625,6 +666,60 @@ impl Remote for Graph {
625
666
.await?)
626
667
}
627
668
669
async fn forward_messages(
670
&self,
671
source_conversation_id: &str,
672
target_conversation_id: &str,
673
message_ids: &[String],
674
comment_html: &str,
675
) -> Result<ForwardResult> {
676
Ok(Messages::new(self.session())
677
.forward_messages(
678
source_conversation_id,
679
target_conversation_id,
680
message_ids,
681
comment_html,
682
)
683
.await?)
684
}
685
686
async fn set_saved(
687
&self,
688
conversation_id: &str,
689
root_id: &str,
690
message_id: &str,
691
saved: bool,
692
) -> Result<()> {
693
Ok(Messages::new(self.session())
694
.set_saved(conversation_id, root_id, message_id, saved)
695
.await?)
696
}
697
698
async fn list_saved(&self) -> Result<Vec<SavedMessage>> {
699
Ok(Messages::new(self.session()).list_saved().await?)
700
}
701
702
async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {
703
Ok(Pins::new(self.session()).chat_pins(chat_id).await?)
704
}
705
706
async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
707
Ok(Pins::new(self.session())
708
.pin_message(chat_id, message_id)
709
.await?)
710
}
711
712
async fn unpin_message(
713
&self,
714
chat_id: &str,
715
message_id: &str,
716
parent_id: Option<&str>,
717
) -> Result<()> {
718
Ok(Pins::new(self.session())
719
.unpin_message(chat_id, message_id, parent_id)
720
.await?)
721
}
722
628
723
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {
629
724
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)
630
725
}
@@ -1,7 +1,7 @@1
use chatsvc::{1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, Conversations, Gif, Gifs, InvokeRequest, InvokeResponse,2
CardActions, ChatApp, ConversationRef, Conversations, ForwardResult, Gif, Gifs, InvokeRequest,3
LinkInfo, MemberHorizon, MessageLinks, Messages, Receipts, ScheduledDraft,3
InvokeResponse, LinkInfo, MemberHorizon, MessageLinks, Messages, PinnedMessage, Pins, Receipts,4
ScheduledDrafts,4
SavedMessage, ScheduledDraft, ScheduledDrafts,5
};5
};6
use chrono::{DateTime, Utc};6
use chrono::{DateTime, Utc};7
use graph::{7
use graph::{@@ -215,6 +215,47 @@ pub trait Remote {215
Err(Error::Unsupported("read receipts"))215
Err(Error::Unsupported("read receipts"))216
}216
}217
217
218
async fn forward_messages(219
&self,220
_source_conversation_id: &str,221
_target_conversation_id: &str,222
_message_ids: &[String],223
_comment_html: &str,224
) -> Result<ForwardResult> {225
Err(Error::Unsupported("forwarding messages"))226
}227
228
async fn set_saved(229
&self,230
_conversation_id: &str,231
_root_id: &str,232
_message_id: &str,233
_saved: bool,234
) -> Result<()> {235
Err(Error::Unsupported("saving messages"))236
}237
238
async fn list_saved(&self) -> Result<Vec<SavedMessage>> {239
Err(Error::Unsupported("saved messages"))240
}241
242
async fn chat_pins(&self, _chat_id: &str) -> Result<Vec<PinnedMessage>> {243
Err(Error::Unsupported("pinned messages"))244
}245
246
async fn pin_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {247
Err(Error::Unsupported("pinning messages"))248
}249
250
async fn unpin_message(251
&self,252
_chat_id: &str,253
_message_id: &str,254
_parent_id: Option<&str>,255
) -> Result<()> {256
Err(Error::Unsupported("pinning messages"))257
}258
218
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {259
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<ChatApp>> {219
Err(Error::Unsupported("chat apps"))260
Err(Error::Unsupported("chat apps"))220
}261
}@@ -625,6 +666,60 @@ impl Remote for Graph {625
.await?)666
.await?)626
}667
}627
668
669
async fn forward_messages(670
&self,671
source_conversation_id: &str,672
target_conversation_id: &str,673
message_ids: &[String],674
comment_html: &str,675
) -> Result<ForwardResult> {676
Ok(Messages::new(self.session())677
.forward_messages(678
source_conversation_id,679
target_conversation_id,680
message_ids,681
comment_html,682
)683
.await?)684
}685
686
async fn set_saved(687
&self,688
conversation_id: &str,689
root_id: &str,690
message_id: &str,691
saved: bool,692
) -> Result<()> {693
Ok(Messages::new(self.session())694
.set_saved(conversation_id, root_id, message_id, saved)695
.await?)696
}697
698
async fn list_saved(&self) -> Result<Vec<SavedMessage>> {699
Ok(Messages::new(self.session()).list_saved().await?)700
}701
702
async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> {703
Ok(Pins::new(self.session()).chat_pins(chat_id).await?)704
}705
706
async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {707
Ok(Pins::new(self.session())708
.pin_message(chat_id, message_id)709
.await?)710
}711
712
async fn unpin_message(713
&self,714
chat_id: &str,715
message_id: &str,716
parent_id: Option<&str>,717
) -> Result<()> {718
Ok(Pins::new(self.session())719
.unpin_message(chat_id, message_id, parent_id)720
.await?)721
}722
628
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {723
async fn chat_apps(&self, chat_id: &str) -> Result<Vec<ChatApp>> {629
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)724
Ok(CardActions::new(self.session()).chat_apps(chat_id).await?)630
}725
}@@ -634,6 +634,51 @@ impl Remote for Handle {
634
634
Ok(self.horizons.lock().unwrap().clone())
635
635
}
636
636
637
async fn forward_messages(
638
&self,
639
source_conversation_id: &str,
640
target_conversation_id: &str,
641
message_ids: &[String],
642
comment_html: &str,
643
) -> Result<chatsvc::ForwardResult> {
644
self.record(format!(
645
"forward {source_conversation_id} {target_conversation_id} {} {comment_html}",
646
message_ids.join(",")
647
));
648
Ok(chatsvc::ForwardResult {
649
thread_id: target_conversation_id.to_owned(),
650
message_id: "99".to_owned(),
651
})
652
}
653
654
async fn set_saved(
655
&self,
656
conversation_id: &str,
657
root_id: &str,
658
message_id: &str,
659
saved: bool,
660
) -> Result<()> {
661
self.record(format!(
662
"save {conversation_id} {root_id} {message_id} {saved}"
663
));
664
Ok(())
665
}
666
667
async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
668
self.record(format!("pin {chat_id} {message_id}"));
669
Ok(())
670
}
671
672
async fn unpin_message(
673
&self,
674
chat_id: &str,
675
message_id: &str,
676
parent_id: Option<&str>,
677
) -> Result<()> {
678
self.record(format!("unpin {chat_id} {message_id} {parent_id:?}"));
679
Ok(())
680
}
681
637
682
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {
638
683
*self.app_calls.lock().unwrap() += 1;
639
684
Ok(self.apps.lock().unwrap().clone())
@@ -3328,3 +3373,142 @@ async fn schedule_message_rejects_notes_and_chat_threads() {
3328
3373
));
3329
3374
assert!(fake.scheduled.lock().unwrap().is_empty());
3330
3375
}
3376
3377
#[tokio::test]
3378
async fn mark_unread_from_a_message_backs_up_one_millisecond() {
3379
let fake = Arc::new(Fake::default());
3380
let engine = chat_engine(&fake, small_pages()).await;
3381
let created_at = base() + Duration::minutes(2);
3382
engine.mark_unread_from(CHAT, created_at).await.unwrap();
3383
assert_eq!(
3384
fake.calls().last().unwrap(),
3385
&format!(
3386
"mark_unread {CHAT} {ME} tenant-1 {}",
3387
created_at.timestamp_millis() - 1
3388
)
3389
);
3390
}
3391
3392
#[tokio::test]
3393
async fn forward_converts_the_comment_and_fetches_the_target() {
3394
let fake = Arc::new(Fake::default());
3395
let engine = chat_engine(&fake, small_pages()).await;
3396
fake.set_chat_messages(vec![message(1, 1, "<p>one</p>")]);
3397
let ids = vec!["m0001".to_owned(), "m0002".to_owned()];
3398
let result = engine
3399
.forward_messages("19:source@thread.v2", CHAT, &ids, "**fyi**")
3400
.await
3401
.unwrap();
3402
assert_eq!(result.message_id, "99");
3403
assert_eq!(
3404
fake.calls().last().unwrap(),
3405
&format!(
3406
"forward 19:source@thread.v2 {CHAT} m0001,m0002 {}",
3407
teams_core::markdown_to_html("**fyi**")
3408
)
3409
);
3410
assert_eq!(engine.open_conversation(CHAT).unwrap().len(), 1);
3411
engine
3412
.forward_messages("19:source@thread.v2", CHAT, &ids, "")
3413
.await
3414
.unwrap();
3415
assert_eq!(
3416
fake.calls().last().unwrap(),
3417
&format!("forward 19:source@thread.v2 {CHAT} m0001,m0002 ")
3418
);
3419
}
3420
3421
#[tokio::test]
3422
async fn save_uses_the_message_id_as_root_in_chats() {
3423
let fake = Arc::new(Fake::default());
3424
let engine = chat_engine(&fake, small_pages()).await;
3425
engine.set_saved(CHAT, "5", None, true).await.unwrap();
3426
assert_eq!(
3427
fake.calls().last().unwrap(),
3428
&format!("save {CHAT} 5 5 true")
3429
);
3430
engine
3431
.set_saved(CHANNEL, "7", Some("3"), false)
3432
.await
3433
.unwrap();
3434
assert_eq!(
3435
fake.calls().last().unwrap(),
3436
&format!("save {CHANNEL} 3 7 false")
3437
);
3438
}
3439
3440
#[tokio::test]
3441
async fn pinning_announces_and_is_refused_in_channels() {
3442
let fake = Arc::new(Fake::default());
3443
let engine = channel_engine(&fake).await;
3444
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
3445
engine.refresh_sidebar().await.unwrap();
3446
let mut events = engine.subscribe();
3447
engine.pin_message(CHAT, "5").await.unwrap();
3448
assert_eq!(
3449
events.try_recv().unwrap(),
3450
CoreEvent::PinsChanged {
3451
conversation_id: CHAT.to_owned()
3452
}
3453
);
3454
engine
3455
.unpin_message(CHAT, "5", Some("folder-1"))
3456
.await
3457
.unwrap();
3458
assert_eq!(
3459
fake.calls().last().unwrap(),
3460
&format!("unpin {CHAT} 5 Some(\"folder-1\")")
3461
);
3462
assert!(matches!(
3463
engine.pin_message(CHANNEL, "5").await,
3464
Err(Error::Unsupported(_))
3465
));
3466
}
3467
3468
#[tokio::test]
3469
async fn pin_events_become_core_events() {
3470
let fake = Arc::new(Fake::default());
3471
let engine = chat_engine(&fake, small_pages()).await;
3472
let mut events = engine.subscribe();
3473
let mut event = read_event(Some(CHAT));
3474
engine.handle_pin_event(&event);
3475
assert!(events.try_recv().is_err());
3476
event.kind = chatsvc::EventKind::PinsChanged;
3477
engine.handle_pin_event(&event);
3478
assert_eq!(
3479
events.try_recv().unwrap(),
3480
CoreEvent::PinsChanged {
3481
conversation_id: CHAT.to_owned()
3482
}
3483
);
3484
}
3485
3486
#[tokio::test]
3487
async fn message_links_resolve_chat_notes_and_channel() {
3488
let fake = Arc::new(Fake::default());
3489
let engine = channel_engine(&fake).await;
3490
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
3491
engine.refresh_sidebar().await.unwrap();
3492
assert_eq!(
3493
engine.message_link(CHAT, "5").await.unwrap(),
3494
teams_core::chat_message_link(CHAT, "5", None)
3495
);
3496
engine.fetch_newer(CHANNEL).await.unwrap();
3497
let root = engine.open_conversation(CHANNEL).unwrap()[0].clone();
3498
assert_eq!(
3499
engine
3500
.message_link(CHANNEL, &root.message_id)
3501
.await
3502
.unwrap(),
3503
teams_core::channel_message_link(&teams_core::ChannelLinkInput {
3504
tenant_id: "tenant-1".into(),
3505
group_id: "team-1".into(),
3506
channel_id: CHANNEL.into(),
3507
team_name: "Squad".into(),
3508
channel_name: "General".into(),
3509
root_id: root.message_id.clone(),
3510
message_id: root.message_id.clone(),
3511
created_ms: root.created_at.timestamp_millis(),
3512
})
3513
);
3514
}
@@ -634,6 +634,51 @@ impl Remote for Handle {634
Ok(self.horizons.lock().unwrap().clone())634
Ok(self.horizons.lock().unwrap().clone())635
}635
}636
636
637
async fn forward_messages(638
&self,639
source_conversation_id: &str,640
target_conversation_id: &str,641
message_ids: &[String],642
comment_html: &str,643
) -> Result<chatsvc::ForwardResult> {644
self.record(format!(645
"forward {source_conversation_id} {target_conversation_id} {} {comment_html}",646
message_ids.join(",")647
));648
Ok(chatsvc::ForwardResult {649
thread_id: target_conversation_id.to_owned(),650
message_id: "99".to_owned(),651
})652
}653
654
async fn set_saved(655
&self,656
conversation_id: &str,657
root_id: &str,658
message_id: &str,659
saved: bool,660
) -> Result<()> {661
self.record(format!(662
"save {conversation_id} {root_id} {message_id} {saved}"663
));664
Ok(())665
}666
667
async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> {668
self.record(format!("pin {chat_id} {message_id}"));669
Ok(())670
}671
672
async fn unpin_message(673
&self,674
chat_id: &str,675
message_id: &str,676
parent_id: Option<&str>,677
) -> Result<()> {678
self.record(format!("unpin {chat_id} {message_id} {parent_id:?}"));679
Ok(())680
}681
637
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {682
async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> {638
*self.app_calls.lock().unwrap() += 1;683
*self.app_calls.lock().unwrap() += 1;639
Ok(self.apps.lock().unwrap().clone())684
Ok(self.apps.lock().unwrap().clone())@@ -3328,3 +3373,142 @@ async fn schedule_message_rejects_notes_and_chat_threads() {3328
));3373
));3329
assert!(fake.scheduled.lock().unwrap().is_empty());3374
assert!(fake.scheduled.lock().unwrap().is_empty());3330
}3375
}3376
3377
#[tokio::test]3378
async fn mark_unread_from_a_message_backs_up_one_millisecond() {3379
let fake = Arc::new(Fake::default());3380
let engine = chat_engine(&fake, small_pages()).await;3381
let created_at = base() + Duration::minutes(2);3382
engine.mark_unread_from(CHAT, created_at).await.unwrap();3383
assert_eq!(3384
fake.calls().last().unwrap(),3385
&format!(3386
"mark_unread {CHAT} {ME} tenant-1 {}",3387
created_at.timestamp_millis() - 13388
)3389
);3390
}3391
3392
#[tokio::test]3393
async fn forward_converts_the_comment_and_fetches_the_target() {3394
let fake = Arc::new(Fake::default());3395
let engine = chat_engine(&fake, small_pages()).await;3396
fake.set_chat_messages(vec![message(1, 1, "<p>one</p>")]);3397
let ids = vec!["m0001".to_owned(), "m0002".to_owned()];3398
let result = engine3399
.forward_messages("19:source@thread.v2", CHAT, &ids, "**fyi**")3400
.await3401
.unwrap();3402
assert_eq!(result.message_id, "99");3403
assert_eq!(3404
fake.calls().last().unwrap(),3405
&format!(3406
"forward 19:source@thread.v2 {CHAT} m0001,m0002 {}",3407
teams_core::markdown_to_html("**fyi**")3408
)3409
);3410
assert_eq!(engine.open_conversation(CHAT).unwrap().len(), 1);3411
engine3412
.forward_messages("19:source@thread.v2", CHAT, &ids, "")3413
.await3414
.unwrap();3415
assert_eq!(3416
fake.calls().last().unwrap(),3417
&format!("forward 19:source@thread.v2 {CHAT} m0001,m0002 ")3418
);3419
}3420
3421
#[tokio::test]3422
async fn save_uses_the_message_id_as_root_in_chats() {3423
let fake = Arc::new(Fake::default());3424
let engine = chat_engine(&fake, small_pages()).await;3425
engine.set_saved(CHAT, "5", None, true).await.unwrap();3426
assert_eq!(3427
fake.calls().last().unwrap(),3428
&format!("save {CHAT} 5 5 true")3429
);3430
engine3431
.set_saved(CHANNEL, "7", Some("3"), false)3432
.await3433
.unwrap();3434
assert_eq!(3435
fake.calls().last().unwrap(),3436
&format!("save {CHANNEL} 3 7 false")3437
);3438
}3439
3440
#[tokio::test]3441
async fn pinning_announces_and_is_refused_in_channels() {3442
let fake = Arc::new(Fake::default());3443
let engine = channel_engine(&fake).await;3444
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];3445
engine.refresh_sidebar().await.unwrap();3446
let mut events = engine.subscribe();3447
engine.pin_message(CHAT, "5").await.unwrap();3448
assert_eq!(3449
events.try_recv().unwrap(),3450
CoreEvent::PinsChanged {3451
conversation_id: CHAT.to_owned()3452
}3453
);3454
engine3455
.unpin_message(CHAT, "5", Some("folder-1"))3456
.await3457
.unwrap();3458
assert_eq!(3459
fake.calls().last().unwrap(),3460
&format!("unpin {CHAT} 5 Some(\"folder-1\")")3461
);3462
assert!(matches!(3463
engine.pin_message(CHANNEL, "5").await,3464
Err(Error::Unsupported(_))3465
));3466
}3467
3468
#[tokio::test]3469
async fn pin_events_become_core_events() {3470
let fake = Arc::new(Fake::default());3471
let engine = chat_engine(&fake, small_pages()).await;3472
let mut events = engine.subscribe();3473
let mut event = read_event(Some(CHAT));3474
engine.handle_pin_event(&event);3475
assert!(events.try_recv().is_err());3476
event.kind = chatsvc::EventKind::PinsChanged;3477
engine.handle_pin_event(&event);3478
assert_eq!(3479
events.try_recv().unwrap(),3480
CoreEvent::PinsChanged {3481
conversation_id: CHAT.to_owned()3482
}3483
);3484
}3485
3486
#[tokio::test]3487
async fn message_links_resolve_chat_notes_and_channel() {3488
let fake = Arc::new(Fake::default());3489
let engine = channel_engine(&fake).await;3490
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];3491
engine.refresh_sidebar().await.unwrap();3492
assert_eq!(3493
engine.message_link(CHAT, "5").await.unwrap(),3494
teams_core::chat_message_link(CHAT, "5", None)3495
);3496
engine.fetch_newer(CHANNEL).await.unwrap();3497
let root = engine.open_conversation(CHANNEL).unwrap()[0].clone();3498
assert_eq!(3499
engine3500
.message_link(CHANNEL, &root.message_id)3501
.await3502
.unwrap(),3503
teams_core::channel_message_link(&teams_core::ChannelLinkInput {3504
tenant_id: "tenant-1".into(),3505
group_id: "team-1".into(),3506
channel_id: CHANNEL.into(),3507
team_name: "Squad".into(),3508
channel_name: "General".into(),3509
root_id: root.message_id.clone(),3510
message_id: root.message_id.clone(),3511
created_ms: root.created_at.timestamp_millis(),3512
})3513
);3514
}