Merge remote-tracking branch 'origin/main' into feat/channel-post-card
@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 59] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 64] = symbols![
12
12
"bot",
13
13
"done",
14
14
"table",
@@ -68,6 +68,11 @@ const SYMBOLS: [(&str, &[u8]); 59] = symbols![
68
68
"fluent_text_edit_style_filled",
69
69
"fluent_table_add",
70
70
"fluent_table_dismiss",
71
"fluent_important",
72
"fluent_important_filled",
73
"fluent_alert_urgent",
74
"fluent_alert_urgent_filled",
75
"fluent_chat",
71
76
];
72
77
73
78
pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 59] = symbols![11
const SYMBOLS: [(&str, &[u8]); 64] = symbols![12
"bot",12
"bot",13
"done",13
"done",14
"table",14
"table",@@ -68,6 +68,11 @@ const SYMBOLS: [(&str, &[u8]); 59] = symbols![68
"fluent_text_edit_style_filled",68
"fluent_text_edit_style_filled",69
"fluent_table_add",69
"fluent_table_add",70
"fluent_table_dismiss",70
"fluent_table_dismiss",71
"fluent_important",72
"fluent_important_filled",73
"fluent_alert_urgent",74
"fluent_alert_urgent_filled",75
"fluent_chat",71
];76
];72
77
73
pub struct AppAssets;78
pub struct AppAssets;@@ -285,6 +285,7 @@ mod tests {
285
285
links_json: "[]".to_owned(),
286
286
subject: None,
287
287
call_event_json: None,
288
importance: Default::default(),
288
289
}
289
290
}
290
291
@@ -285,6 +285,7 @@ mod tests {285
links_json: "[]".to_owned(),285
links_json: "[]".to_owned(),286
subject: None,286
subject: None,287
call_event_json: None,287
call_event_json: None,288
importance: Default::default(),288
}289
}289
}290
}290
291
@@ -575,7 +575,9 @@ mod tests {
575
575
mentions_me: false,
576
576
muted: false,
577
577
signals: Default::default(),
578
chat: Default::default(),
578
579
created_at: at(9, minute),
580
importance: Default::default(),
579
581
}
580
582
}
581
583
@@ -575,7 +575,9 @@ mod tests {575
mentions_me: false,575
mentions_me: false,576
muted: false,576
muted: false,577
signals: Default::default(),577
signals: Default::default(),578
chat: Default::default(),578
created_at: at(9, minute),579
created_at: at(9, minute),580
importance: Default::default(),579
}581
}580
}582
}581
583
@@ -9,7 +9,7 @@ use crate::notify::Preview;
9
9
10
10
const IMAGE_LABEL: &str = "Image";
11
11
12
fn preview_label(preview: &Preview) -> String {
12
pub(crate) fn preview_label(preview: &Preview) -> String {
13
13
match preview {
14
14
Preview::Text(text) => text.clone(),
15
15
Preview::Image => IMAGE_LABEL.to_owned(),
@@ -9,7 +9,7 @@ use crate::notify::Preview;9
9
10
const IMAGE_LABEL: &str = "Image";10
const IMAGE_LABEL: &str = "Image";11
11
12
fn preview_label(preview: &Preview) -> String {12
pub(crate) fn preview_label(preview: &Preview) -> String {13
match preview {13
match preview {14
Preview::Text(text) => text.clone(),14
Preview::Text(text) => text.clone(),15
Preview::Image => IMAGE_LABEL.to_owned(),15
Preview::Image => IMAGE_LABEL.to_owned(),@@ -6,6 +6,7 @@ use gpui_kit::*;
6
6
use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};
7
7
use super::preview_label;
8
8
use super::reactions::reacted_messages;
9
use crate::agent_api;
9
10
use crate::app_state::{AppEvent, AppState};
10
11
use crate::call::MissedCall;
11
12
use crate::demo;
@@ -22,6 +23,7 @@ pub struct ActivityCenter {
22
23
tracker: IncomingTracker,
23
24
cutoff: DateTime<Utc>,
24
25
_subscription: Subscription,
26
_proposal_observation: Option<Subscription>,
25
27
}
26
28
27
29
impl ActivityCenter {
@@ -40,6 +42,8 @@ impl ActivityCenter {
40
42
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
41
43
this.on_app_event(event, cx);
42
44
});
45
let proposal_observation =
46
agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
43
47
let mut center = ActivityCenter {
44
48
app,
45
49
main_window: window.window_handle(),
@@ -47,6 +51,7 @@ impl ActivityCenter {
47
51
tracker: IncomingTracker::new(cutoff),
48
52
cutoff,
49
53
_subscription: subscription,
54
_proposal_observation: proposal_observation,
50
55
};
51
56
center.flush(cx);
52
57
center
@@ -63,6 +68,7 @@ impl ActivityCenter {
63
68
}
64
69
65
70
pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
71
agent_api::mark_all_proposals_seen(cx);
66
72
if self.feed.mark_all_read() {
67
73
self.flush(cx);
68
74
}
@@ -97,6 +103,22 @@ impl ActivityCenter {
97
103
}
98
104
99
105
fn on_selection(&mut self, cx: &mut Context<Self>) {
106
let selected = self
107
.app
108
.read(cx)
109
.selection
110
.as_ref()
111
.map(|selection| selection.conversation_id().to_owned());
112
let Some(conversation_id) = selected else {
113
return;
114
};
115
agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
116
if self.feed.mark_conversation_read(&conversation_id) {
117
self.flush(cx);
118
}
119
}
120
121
fn on_proposals(&mut self, cx: &mut Context<Self>) {
100
122
let selected = self
101
123
.app
102
124
.read(cx)
@@ -104,10 +126,11 @@ impl ActivityCenter {
104
126
.as_ref()
105
127
.map(|selection| selection.conversation_id().to_owned());
106
128
if let Some(conversation_id) = selected
107
&& self.feed.mark_conversation_read(&conversation_id)
129
&& self.in_foreground(&conversation_id, cx)
108
130
{
109
self.flush(cx);
131
agent_api::mark_conversation_proposals_seen(&conversation_id, cx);
110
132
}
133
cx.notify();
111
134
}
112
135
113
136
fn on_sidebar(&mut self, cx: &mut Context<Self>) {
@@ -6,6 +6,7 @@ use gpui_kit::*;6
use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};6
use super::feed::{Actor, Entry, Feed, RETENTION_DAYS, ReactedMessage, start_time};7
use super::preview_label;7
use super::preview_label;8
use super::reactions::reacted_messages;8
use super::reactions::reacted_messages;9
use crate::agent_api;9
use crate::app_state::{AppEvent, AppState};10
use crate::app_state::{AppEvent, AppState};10
use crate::call::MissedCall;11
use crate::call::MissedCall;11
use crate::demo;12
use crate::demo;@@ -22,6 +23,7 @@ pub struct ActivityCenter {22
tracker: IncomingTracker,23
tracker: IncomingTracker,23
cutoff: DateTime<Utc>,24
cutoff: DateTime<Utc>,24
_subscription: Subscription,25
_subscription: Subscription,26
_proposal_observation: Option<Subscription>,25
}27
}26
28
27
impl ActivityCenter {29
impl ActivityCenter {@@ -40,6 +42,8 @@ impl ActivityCenter {40
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {42
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {41
this.on_app_event(event, cx);43
this.on_app_event(event, cx);42
});44
});45
let proposal_observation =46
agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));43
let mut center = ActivityCenter {47
let mut center = ActivityCenter {44
app,48
app,45
main_window: window.window_handle(),49
main_window: window.window_handle(),@@ -47,6 +51,7 @@ impl ActivityCenter {47
tracker: IncomingTracker::new(cutoff),51
tracker: IncomingTracker::new(cutoff),48
cutoff,52
cutoff,49
_subscription: subscription,53
_subscription: subscription,54
_proposal_observation: proposal_observation,50
};55
};51
center.flush(cx);56
center.flush(cx);52
center57
center@@ -63,6 +68,7 @@ impl ActivityCenter {63
}68
}64
69
65
pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {70
pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {71
agent_api::mark_all_proposals_seen(cx);66
if self.feed.mark_all_read() {72
if self.feed.mark_all_read() {67
self.flush(cx);73
self.flush(cx);68
}74
}@@ -97,6 +103,22 @@ impl ActivityCenter {97
}103
}98
104
99
fn on_selection(&mut self, cx: &mut Context<Self>) {105
fn on_selection(&mut self, cx: &mut Context<Self>) {106
let selected = self107
.app108
.read(cx)109
.selection110
.as_ref()111
.map(|selection| selection.conversation_id().to_owned());112
let Some(conversation_id) = selected else {113
return;114
};115
agent_api::mark_conversation_proposals_seen(&conversation_id, cx);116
if self.feed.mark_conversation_read(&conversation_id) {117
self.flush(cx);118
}119
}120
121
fn on_proposals(&mut self, cx: &mut Context<Self>) {100
let selected = self122
let selected = self101
.app123
.app102
.read(cx)124
.read(cx)@@ -104,10 +126,11 @@ impl ActivityCenter {104
.as_ref()126
.as_ref()105
.map(|selection| selection.conversation_id().to_owned());127
.map(|selection| selection.conversation_id().to_owned());106
if let Some(conversation_id) = selected128
if let Some(conversation_id) = selected107
&& self.feed.mark_conversation_read(&conversation_id)129
&& self.in_foreground(&conversation_id, cx)108
{130
{109
self.flush(cx);131
agent_api::mark_conversation_proposals_seen(&conversation_id, cx);110
}132
}133
cx.notify();111
}134
}112
135
113
fn on_sidebar(&mut self, cx: &mut Context<Self>) {136
fn on_sidebar(&mut self, cx: &mut Context<Self>) {@@ -1,8 +1,9 @@
1
1
pub mod bridge;
2
2
pub mod body;
3
pub mod pending;
3
4
pub mod source;
4
5
5
use std::collections::{BTreeSet, HashMap};
6
use std::collections::{BTreeSet, HashMap, HashSet};
6
7
use std::sync::Arc;
7
8
8
9
use chrono::{DateTime, Local};
@@ -17,6 +18,7 @@ use app_base::agent_api::{extras, image_scale};
17
18
18
19
use crate::backend::Engine;
19
20
use crate::runtime;
21
use pending::PendingProposal;
20
22
use source::AppSource;
21
23
22
24
#[derive(Debug, Clone, PartialEq)]
@@ -64,6 +66,8 @@ pub struct AgentApi {
64
66
token: String,
65
67
proposals: HashMap<String, ProposalEntry>,
66
68
reactions: HashMap<(String, String), ReactionProposal>,
69
reaction_excerpts: HashMap<String, String>,
70
seen_proposals: HashSet<String>,
67
71
server: Option<ServerHandle>,
68
72
status: ServerStatus,
69
73
generation: u64,
@@ -76,6 +80,7 @@ struct AgentApiHandle(Entity<AgentApi>);
76
80
impl Global for AgentApiHandle {}
77
81
78
82
const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";
83
const SEEN_PROPOSALS_KEY: &str = "activity_seen_proposals";
79
84
80
85
pub fn endpoint_url(port: u16) -> String {
81
86
format!("http://127.0.0.1:{port}/mcp")
@@ -128,6 +133,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
128
133
let hub = AgentHub::new(store.clone(), policy, ui);
129
134
let token = mcp::load_or_create_token(&store).unwrap_or_default();
130
135
let source = Arc::new(AppSource::new(store.clone()));
136
let seen_proposals = pending::decode_seen(store.meta(SEEN_PROPOSALS_KEY).ok().flatten());
131
137
let api = cx.new(|_| AgentApi {
132
138
hub,
133
139
source,
@@ -135,6 +141,8 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
135
141
token,
136
142
proposals: HashMap::new(),
137
143
reactions: HashMap::new(),
144
reaction_excerpts: HashMap::new(),
145
seen_proposals,
138
146
server: None,
139
147
status: ServerStatus::Off,
140
148
generation: 0,
@@ -280,6 +288,46 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {
280
288
.collect()
281
289
}
282
290
291
pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {
292
handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())
293
}
294
295
pub fn unseen_proposal_count(cx: &App) -> usize {
296
pending_proposals(cx)
297
.iter()
298
.filter(|pending| !pending.seen)
299
.count()
300
}
301
302
pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {
303
mark_proposals_seen(cx, |pending| pending.id == proposal_id);
304
}
305
306
pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {
307
mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);
308
}
309
310
pub fn mark_all_proposals_seen(cx: &mut App) {
311
mark_proposals_seen(cx, |_| true);
312
}
313
314
fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {
315
let Some(api) = handle(cx) else {
316
return;
317
};
318
let fresh: Vec<String> = api
319
.read(cx)
320
.pending_proposals()
321
.into_iter()
322
.filter(|pending| !pending.seen && matches(pending))
323
.map(|pending| pending.id)
324
.collect();
325
if fresh.is_empty() {
326
return;
327
}
328
api.update(cx, |api, cx| api.mark_seen(fresh, cx));
329
}
330
283
331
pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {
284
332
if let Some(api) = handle(cx) {
285
333
api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));
@@ -346,6 +394,30 @@ impl AgentApi {
346
394
}
347
395
}
348
396
397
pub fn pending_proposals(&self) -> Vec<PendingProposal> {
398
pending::collect(
399
&self.proposals,
400
&self.reactions,
401
&self.reaction_excerpts,
402
&self.seen_proposals,
403
)
404
}
405
406
fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {
407
self.seen_proposals.extend(proposal_ids);
408
let pending: HashSet<String> = self
409
.pending_proposals()
410
.into_iter()
411
.map(|pending| pending.id)
412
.collect();
413
self.seen_proposals.retain(|id| pending.contains(id));
414
let _ = self.store.set_meta(
415
SEEN_PROPOSALS_KEY,
416
&pending::encode_seen(&self.seen_proposals),
417
);
418
cx.notify();
419
}
420
349
421
pub fn reinstall_note(&self) -> Option<&str> {
350
422
self.reinstall_note.as_deref()
351
423
}
@@ -394,6 +466,15 @@ impl AgentApi {
394
466
pictures: Vec<ProposalPicture>,
395
467
cx: &mut Context<Self>,
396
468
) {
469
if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event
470
&& let Some(excerpt) = pending::reacted_excerpt(
471
&self.store,
472
&reaction.conversation_id,
473
&reaction.message_id,
474
)
475
{
476
self.reaction_excerpts.insert(reaction.id.clone(), excerpt);
477
}
397
478
bridge::apply(
398
479
&mut self.proposals,
399
480
&mut self.reactions,
@@ -401,6 +482,9 @@ impl AgentApi {
401
482
pictures,
402
483
&self.store,
403
484
);
485
let reactions = &self.reactions;
486
self.reaction_excerpts
487
.retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));
404
488
cx.notify();
405
489
}
406
490
@@ -1,8 +1,9 @@1
pub mod bridge;1
pub mod bridge;2
pub mod body;2
pub mod body;3
pub mod pending;3
pub mod source;4
pub mod source;4
5
5
use std::collections::{BTreeSet, HashMap};6
use std::collections::{BTreeSet, HashMap, HashSet};6
use std::sync::Arc;7
use std::sync::Arc;7
8
8
use chrono::{DateTime, Local};9
use chrono::{DateTime, Local};@@ -17,6 +18,7 @@ use app_base::agent_api::{extras, image_scale};17
18
18
use crate::backend::Engine;19
use crate::backend::Engine;19
use crate::runtime;20
use crate::runtime;21
use pending::PendingProposal;20
use source::AppSource;22
use source::AppSource;21
23
22
#[derive(Debug, Clone, PartialEq)]24
#[derive(Debug, Clone, PartialEq)]@@ -64,6 +66,8 @@ pub struct AgentApi {64
token: String,66
token: String,65
proposals: HashMap<String, ProposalEntry>,67
proposals: HashMap<String, ProposalEntry>,66
reactions: HashMap<(String, String), ReactionProposal>,68
reactions: HashMap<(String, String), ReactionProposal>,69
reaction_excerpts: HashMap<String, String>,70
seen_proposals: HashSet<String>,67
server: Option<ServerHandle>,71
server: Option<ServerHandle>,68
status: ServerStatus,72
status: ServerStatus,69
generation: u64,73
generation: u64,@@ -76,6 +80,7 @@ struct AgentApiHandle(Entity<AgentApi>);76
impl Global for AgentApiHandle {}80
impl Global for AgentApiHandle {}77
81
78
const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";82
const DEMO_PORT_ENV: &str = "RUSTY_TEAMS_MCP_PORT";83
const SEEN_PROPOSALS_KEY: &str = "activity_seen_proposals";79
84
80
pub fn endpoint_url(port: u16) -> String {85
pub fn endpoint_url(port: u16) -> String {81
format!("http://127.0.0.1:{port}/mcp")86
format!("http://127.0.0.1:{port}/mcp")@@ -128,6 +133,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {128
let hub = AgentHub::new(store.clone(), policy, ui);133
let hub = AgentHub::new(store.clone(), policy, ui);129
let token = mcp::load_or_create_token(&store).unwrap_or_default();134
let token = mcp::load_or_create_token(&store).unwrap_or_default();130
let source = Arc::new(AppSource::new(store.clone()));135
let source = Arc::new(AppSource::new(store.clone()));136
let seen_proposals = pending::decode_seen(store.meta(SEEN_PROPOSALS_KEY).ok().flatten());131
let api = cx.new(|_| AgentApi {137
let api = cx.new(|_| AgentApi {132
hub,138
hub,133
source,139
source,@@ -135,6 +141,8 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {135
token,141
token,136
proposals: HashMap::new(),142
proposals: HashMap::new(),137
reactions: HashMap::new(),143
reactions: HashMap::new(),144
reaction_excerpts: HashMap::new(),145
seen_proposals,138
server: None,146
server: None,139
status: ServerStatus::Off,147
status: ServerStatus::Off,140
generation: 0,148
generation: 0,@@ -280,6 +288,46 @@ pub fn pending_agents(cx: &App) -> HashMap<String, &'static str> {280
.collect()288
.collect()281
}289
}282
290
291
pub fn pending_proposals(cx: &App) -> Vec<PendingProposal> {292
handle(cx).map_or_else(Vec::new, |api| api.read(cx).pending_proposals())293
}294
295
pub fn unseen_proposal_count(cx: &App) -> usize {296
pending_proposals(cx)297
.iter()298
.filter(|pending| !pending.seen)299
.count()300
}301
302
pub fn mark_proposal_seen(proposal_id: &str, cx: &mut App) {303
mark_proposals_seen(cx, |pending| pending.id == proposal_id);304
}305
306
pub fn mark_conversation_proposals_seen(conversation_id: &str, cx: &mut App) {307
mark_proposals_seen(cx, |pending| pending.conversation_id == conversation_id);308
}309
310
pub fn mark_all_proposals_seen(cx: &mut App) {311
mark_proposals_seen(cx, |_| true);312
}313
314
fn mark_proposals_seen(cx: &mut App, matches: impl Fn(&PendingProposal) -> bool) {315
let Some(api) = handle(cx) else {316
return;317
};318
let fresh: Vec<String> = api319
.read(cx)320
.pending_proposals()321
.into_iter()322
.filter(|pending| !pending.seen && matches(pending))323
.map(|pending| pending.id)324
.collect();325
if fresh.is_empty() {326
return;327
}328
api.update(cx, |api, cx| api.mark_seen(fresh, cx));329
}330
283
pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {331
pub fn resolve_proposal(conversation_id: &str, outcome: Outcome, cx: &mut App) {284
if let Some(api) = handle(cx) {332
if let Some(api) = handle(cx) {285
api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));333
api.update(cx, |api, cx| api.resolve(conversation_id, outcome, cx));@@ -346,6 +394,30 @@ impl AgentApi {346
}394
}347
}395
}348
396
397
pub fn pending_proposals(&self) -> Vec<PendingProposal> {398
pending::collect(399
&self.proposals,400
&self.reactions,401
&self.reaction_excerpts,402
&self.seen_proposals,403
)404
}405
406
fn mark_seen(&mut self, proposal_ids: Vec<String>, cx: &mut Context<Self>) {407
self.seen_proposals.extend(proposal_ids);408
let pending: HashSet<String> = self409
.pending_proposals()410
.into_iter()411
.map(|pending| pending.id)412
.collect();413
self.seen_proposals.retain(|id| pending.contains(id));414
let _ = self.store.set_meta(415
SEEN_PROPOSALS_KEY,416
&pending::encode_seen(&self.seen_proposals),417
);418
cx.notify();419
}420
349
pub fn reinstall_note(&self) -> Option<&str> {421
pub fn reinstall_note(&self) -> Option<&str> {350
self.reinstall_note.as_deref()422
self.reinstall_note.as_deref()351
}423
}@@ -394,6 +466,15 @@ impl AgentApi {394
pictures: Vec<ProposalPicture>,466
pictures: Vec<ProposalPicture>,395
cx: &mut Context<Self>,467
cx: &mut Context<Self>,396
) {468
) {469
if let mcp::UiEvent::ReactionProposalChanged(reaction) = &event470
&& let Some(excerpt) = pending::reacted_excerpt(471
&self.store,472
&reaction.conversation_id,473
&reaction.message_id,474
)475
{476
self.reaction_excerpts.insert(reaction.id.clone(), excerpt);477
}397
bridge::apply(478
bridge::apply(398
&mut self.proposals,479
&mut self.proposals,399
&mut self.reactions,480
&mut self.reactions,@@ -401,6 +482,9 @@ impl AgentApi {401
pictures,482
pictures,402
&self.store,483
&self.store,403
);484
);485
let reactions = &self.reactions;486
self.reaction_excerpts487
.retain(|id, _| reactions.values().any(|reaction| &reaction.id == id));404
cx.notify();488
cx.notify();405
}489
}406
490
@@ -0,0 +1,247 @@
1
use std::collections::{HashMap, HashSet};
2
3
use chrono::{DateTime, Utc};
4
use mcp::ReactionProposal;
5
use store::{Sidebar, Store};
6
7
use super::{ProposalEntry, ProposalStatus, agent_label};
8
use crate::activity::preview_label;
9
use crate::app_state::chat_title;
10
use crate::notify::preview_of;
11
use crate::rows::reaction_glyph;
12
13
const EXCERPT_CHARACTERS: usize = 120;
14
15
#[derive(Debug, Clone, PartialEq)]
16
pub enum PendingKind {
17
Reply {
18
text: String,
19
},
20
Reaction {
21
glyph: String,
22
message_id: String,
23
excerpt: Option<String>,
24
},
25
}
26
27
#[derive(Debug, Clone, PartialEq)]
28
pub struct PendingProposal {
29
pub id: String,
30
pub conversation_id: String,
31
pub agent: &'static str,
32
pub kind: PendingKind,
33
pub created_at: DateTime<Utc>,
34
pub seen: bool,
35
}
36
37
impl PendingProposal {
38
pub fn title(&self) -> String {
39
let what = match self.kind {
40
PendingKind::Reply { .. } => "a reply",
41
PendingKind::Reaction { .. } => "a reaction",
42
};
43
format!("{} proposes {what}", self.agent)
44
}
45
46
pub fn headline(&self, conversation: Option<&str>) -> String {
47
match conversation {
48
Some(conversation) => format!("{} in {conversation}", self.title()),
49
None => self.title(),
50
}
51
}
52
53
pub fn detail(&self) -> String {
54
match &self.kind {
55
PendingKind::Reply { text } => single_line(text),
56
PendingKind::Reaction {
57
glyph,
58
excerpt: Some(excerpt),
59
..
60
} => format!("{glyph} to: {excerpt}"),
61
PendingKind::Reaction { glyph, .. } => glyph.clone(),
62
}
63
}
64
65
pub fn jump_message_id(&self) -> &str {
66
match &self.kind {
67
PendingKind::Reply { .. } => "",
68
PendingKind::Reaction { message_id, .. } => message_id,
69
}
70
}
71
}
72
73
fn single_line(text: &str) -> String {
74
text.split_whitespace().collect::<Vec<_>>().join(" ")
75
}
76
77
pub fn collect(
78
proposals: &HashMap<String, ProposalEntry>,
79
reactions: &HashMap<(String, String), ReactionProposal>,
80
excerpts: &HashMap<String, String>,
81
seen: &HashSet<String>,
82
) -> Vec<PendingProposal> {
83
let replies = proposals
84
.values()
85
.filter(|entry| !matches!(entry.status, ProposalStatus::Stale { .. }))
86
.map(|entry| PendingProposal {
87
id: entry.proposal.id.clone(),
88
conversation_id: entry.proposal.conversation_id.clone(),
89
agent: agent_label(entry.proposal.agent.as_deref()),
90
kind: PendingKind::Reply {
91
text: entry.proposal.text.clone(),
92
},
93
created_at: entry.proposal.created_at,
94
seen: seen.contains(&entry.proposal.id),
95
});
96
let reacts = reactions.values().map(|reaction| PendingProposal {
97
id: reaction.id.clone(),
98
conversation_id: reaction.conversation_id.clone(),
99
agent: agent_label(reaction.agent.as_deref()),
100
kind: PendingKind::Reaction {
101
glyph: reaction_glyph(&reaction.emoji),
102
message_id: reaction.message_id.clone(),
103
excerpt: excerpts.get(&reaction.id).cloned(),
104
},
105
created_at: reaction.created_at,
106
seen: seen.contains(&reaction.id),
107
});
108
let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();
109
pending.sort_by(|left, right| {
110
right
111
.created_at
112
.cmp(&left.created_at)
113
.then_with(|| left.id.cmp(&right.id))
114
});
115
pending
116
}
117
118
pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
119
if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
120
return Some(chat_title(chat));
121
}
122
sidebar.teams.iter().find_map(|team| {
123
team.channels
124
.iter()
125
.find(|channel| channel.id == conversation_id)
126
.map(|channel| format!("{} > {}", team.team.name, channel.name))
127
})
128
}
129
130
pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {
131
let records = store
132
.messages_by_id(conversation_id, &[message_id.to_owned()])
133
.ok()?;
134
let record = records.get(message_id)?;
135
let text = single_line(&preview_label(&preview_of(record)));
136
Some(text.chars().take(EXCERPT_CHARACTERS).collect())
137
}
138
139
pub fn decode_seen(saved: Option<String>) -> HashSet<String> {
140
saved
141
.unwrap_or_default()
142
.lines()
143
.filter(|line| !line.is_empty())
144
.map(str::to_owned)
145
.collect()
146
}
147
148
pub fn encode_seen(seen: &HashSet<String>) -> String {
149
let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();
150
ids.sort_unstable();
151
ids.join("\n")
152
}
153
154
#[cfg(test)]
155
mod tests {
156
use std::collections::{HashMap, HashSet};
157
use std::sync::Arc;
158
159
use chrono::{Local, TimeZone, Utc};
160
use mcp::{Proposal, ReactionProposal};
161
162
use super::*;
163
164
fn reply(
165
conversation_id: &str,
166
id: &str,
167
minute: u32,
168
status: ProposalStatus,
169
) -> ProposalEntry {
170
ProposalEntry {
171
proposal: Proposal {
172
id: id.into(),
173
conversation_id: conversation_id.into(),
174
reply_to_message_id: None,
175
text: "Looks\n good to me".into(),
176
mentions: Vec::new(),
177
images: Vec::new(),
178
agent: Some("claude".into()),
179
session_id: None,
180
created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
181
},
182
body: Arc::new(Vec::new()),
183
mention_labels: Vec::new(),
184
images: Vec::new(),
185
status,
186
}
187
}
188
189
fn reaction(id: &str, minute: u32) -> ReactionProposal {
190
ReactionProposal {
191
id: id.into(),
192
conversation_id: "chat-b".into(),
193
message_id: "m7".into(),
194
emoji: "like".into(),
195
agent: Some("copilot".into()),
196
session_id: None,
197
created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),
198
}
199
}
200
201
#[test]
202
fn collect_lists_pending_replies_and_reactions_newest_first() {
203
let proposals = HashMap::from([
204
(
205
"chat-a".to_owned(),
206
reply("chat-a", "p1", 5, ProposalStatus::Pending),
207
),
208
(
209
"chat-c".to_owned(),
210
reply(
211
"chat-c",
212
"p2",
213
9,
214
ProposalStatus::Stale {
215
answered_at: Local::now(),
216
},
217
),
218
),
219
]);
220
let reactions =
221
HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);
222
let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);
223
let seen = HashSet::from(["p1".to_owned()]);
224
let pending = collect(&proposals, &reactions, &excerpts, &seen);
225
let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();
226
assert_eq!(ids, ["r1", "p1"]);
227
assert!(!pending[0].seen);
228
assert!(pending[1].seen);
229
assert_eq!(pending[0].title(), "Copilot proposes a reaction");
230
assert_eq!(pending[0].jump_message_id(), "m7");
231
assert_eq!(pending[1].jump_message_id(), "");
232
assert_eq!(
233
pending[1].headline(Some("Release planning")),
234
"Claude proposes a reply in Release planning"
235
);
236
assert_eq!(pending[1].detail(), "Looks good to me");
237
assert!(pending[0].detail().ends_with(" to: Ship it?"));
238
}
239
240
#[test]
241
fn seen_ids_round_trip() {
242
let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);
243
assert_eq!(encode_seen(&seen), "a\nb");
244
assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);
245
assert!(decode_seen(None).is_empty());
246
}
247
}
@@ -0,0 +1,247 @@1
use std::collections::{HashMap, HashSet};2
3
use chrono::{DateTime, Utc};4
use mcp::ReactionProposal;5
use store::{Sidebar, Store};6
7
use super::{ProposalEntry, ProposalStatus, agent_label};8
use crate::activity::preview_label;9
use crate::app_state::chat_title;10
use crate::notify::preview_of;11
use crate::rows::reaction_glyph;12
13
const EXCERPT_CHARACTERS: usize = 120;14
15
#[derive(Debug, Clone, PartialEq)]16
pub enum PendingKind {17
Reply {18
text: String,19
},20
Reaction {21
glyph: String,22
message_id: String,23
excerpt: Option<String>,24
},25
}26
27
#[derive(Debug, Clone, PartialEq)]28
pub struct PendingProposal {29
pub id: String,30
pub conversation_id: String,31
pub agent: &'static str,32
pub kind: PendingKind,33
pub created_at: DateTime<Utc>,34
pub seen: bool,35
}36
37
impl PendingProposal {38
pub fn title(&self) -> String {39
let what = match self.kind {40
PendingKind::Reply { .. } => "a reply",41
PendingKind::Reaction { .. } => "a reaction",42
};43
format!("{} proposes {what}", self.agent)44
}45
46
pub fn headline(&self, conversation: Option<&str>) -> String {47
match conversation {48
Some(conversation) => format!("{} in {conversation}", self.title()),49
None => self.title(),50
}51
}52
53
pub fn detail(&self) -> String {54
match &self.kind {55
PendingKind::Reply { text } => single_line(text),56
PendingKind::Reaction {57
glyph,58
excerpt: Some(excerpt),59
..60
} => format!("{glyph} to: {excerpt}"),61
PendingKind::Reaction { glyph, .. } => glyph.clone(),62
}63
}64
65
pub fn jump_message_id(&self) -> &str {66
match &self.kind {67
PendingKind::Reply { .. } => "",68
PendingKind::Reaction { message_id, .. } => message_id,69
}70
}71
}72
73
fn single_line(text: &str) -> String {74
text.split_whitespace().collect::<Vec<_>>().join(" ")75
}76
77
pub fn collect(78
proposals: &HashMap<String, ProposalEntry>,79
reactions: &HashMap<(String, String), ReactionProposal>,80
excerpts: &HashMap<String, String>,81
seen: &HashSet<String>,82
) -> Vec<PendingProposal> {83
let replies = proposals84
.values()85
.filter(|entry| !matches!(entry.status, ProposalStatus::Stale { .. }))86
.map(|entry| PendingProposal {87
id: entry.proposal.id.clone(),88
conversation_id: entry.proposal.conversation_id.clone(),89
agent: agent_label(entry.proposal.agent.as_deref()),90
kind: PendingKind::Reply {91
text: entry.proposal.text.clone(),92
},93
created_at: entry.proposal.created_at,94
seen: seen.contains(&entry.proposal.id),95
});96
let reacts = reactions.values().map(|reaction| PendingProposal {97
id: reaction.id.clone(),98
conversation_id: reaction.conversation_id.clone(),99
agent: agent_label(reaction.agent.as_deref()),100
kind: PendingKind::Reaction {101
glyph: reaction_glyph(&reaction.emoji),102
message_id: reaction.message_id.clone(),103
excerpt: excerpts.get(&reaction.id).cloned(),104
},105
created_at: reaction.created_at,106
seen: seen.contains(&reaction.id),107
});108
let mut pending: Vec<PendingProposal> = replies.chain(reacts).collect();109
pending.sort_by(|left, right| {110
right111
.created_at112
.cmp(&left.created_at)113
.then_with(|| left.id.cmp(&right.id))114
});115
pending116
}117
118
pub fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {119
if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {120
return Some(chat_title(chat));121
}122
sidebar.teams.iter().find_map(|team| {123
team.channels124
.iter()125
.find(|channel| channel.id == conversation_id)126
.map(|channel| format!("{} > {}", team.team.name, channel.name))127
})128
}129
130
pub fn reacted_excerpt(store: &Store, conversation_id: &str, message_id: &str) -> Option<String> {131
let records = store132
.messages_by_id(conversation_id, &[message_id.to_owned()])133
.ok()?;134
let record = records.get(message_id)?;135
let text = single_line(&preview_label(&preview_of(record)));136
Some(text.chars().take(EXCERPT_CHARACTERS).collect())137
}138
139
pub fn decode_seen(saved: Option<String>) -> HashSet<String> {140
saved141
.unwrap_or_default()142
.lines()143
.filter(|line| !line.is_empty())144
.map(str::to_owned)145
.collect()146
}147
148
pub fn encode_seen(seen: &HashSet<String>) -> String {149
let mut ids: Vec<&str> = seen.iter().map(String::as_str).collect();150
ids.sort_unstable();151
ids.join("\n")152
}153
154
#[cfg(test)]155
mod tests {156
use std::collections::{HashMap, HashSet};157
use std::sync::Arc;158
159
use chrono::{Local, TimeZone, Utc};160
use mcp::{Proposal, ReactionProposal};161
162
use super::*;163
164
fn reply(165
conversation_id: &str,166
id: &str,167
minute: u32,168
status: ProposalStatus,169
) -> ProposalEntry {170
ProposalEntry {171
proposal: Proposal {172
id: id.into(),173
conversation_id: conversation_id.into(),174
reply_to_message_id: None,175
text: "Looks\n good to me".into(),176
mentions: Vec::new(),177
images: Vec::new(),178
agent: Some("claude".into()),179
session_id: None,180
created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),181
},182
body: Arc::new(Vec::new()),183
mention_labels: Vec::new(),184
images: Vec::new(),185
status,186
}187
}188
189
fn reaction(id: &str, minute: u32) -> ReactionProposal {190
ReactionProposal {191
id: id.into(),192
conversation_id: "chat-b".into(),193
message_id: "m7".into(),194
emoji: "like".into(),195
agent: Some("copilot".into()),196
session_id: None,197
created_at: Utc.with_ymd_and_hms(2026, 10, 18, 9, minute, 0).unwrap(),198
}199
}200
201
#[test]202
fn collect_lists_pending_replies_and_reactions_newest_first() {203
let proposals = HashMap::from([204
(205
"chat-a".to_owned(),206
reply("chat-a", "p1", 5, ProposalStatus::Pending),207
),208
(209
"chat-c".to_owned(),210
reply(211
"chat-c",212
"p2",213
9,214
ProposalStatus::Stale {215
answered_at: Local::now(),216
},217
),218
),219
]);220
let reactions =221
HashMap::from([(("chat-b".to_owned(), "m7".to_owned()), reaction("r1", 7))]);222
let excerpts = HashMap::from([("r1".to_owned(), "Ship it?".to_owned())]);223
let seen = HashSet::from(["p1".to_owned()]);224
let pending = collect(&proposals, &reactions, &excerpts, &seen);225
let ids: Vec<&str> = pending.iter().map(|item| item.id.as_str()).collect();226
assert_eq!(ids, ["r1", "p1"]);227
assert!(!pending[0].seen);228
assert!(pending[1].seen);229
assert_eq!(pending[0].title(), "Copilot proposes a reaction");230
assert_eq!(pending[0].jump_message_id(), "m7");231
assert_eq!(pending[1].jump_message_id(), "");232
assert_eq!(233
pending[1].headline(Some("Release planning")),234
"Claude proposes a reply in Release planning"235
);236
assert_eq!(pending[1].detail(), "Looks good to me");237
assert!(pending[0].detail().ends_with(" to: Ship it?"));238
}239
240
#[test]241
fn seen_ids_round_trip() {242
let seen = HashSet::from(["b".to_owned(), "a".to_owned()]);243
assert_eq!(encode_seen(&seen), "a\nb");244
assert_eq!(decode_seen(Some(encode_seen(&seen))), seen);245
assert!(decode_seen(None).is_empty());246
}247
}@@ -73,6 +73,7 @@ pub enum AppEvent {
73
73
MeetingChime,
74
74
CallTone(chatsvc::sounds::CallTone),
75
75
SoundSettings,
76
ChatSettings,
76
77
}
77
78
78
79
#[derive(Debug, Clone, Copy, Default)]
@@ -89,6 +90,7 @@ pub struct AppState {
89
90
pub favorite_ids: Vec<String>,
90
91
pub selection: Option<Selection>,
91
92
pub late_arrivals: LateArrivals,
93
pub acked_urgent: std::collections::HashSet<String>,
92
94
pub new_chat: bool,
93
95
pub new_chat_people: Vec<store::MemberRecord>,
94
96
pub connection: ConnectionState,
@@ -139,7 +141,11 @@ pub struct AppState {
139
141
pub call_count: u64,
140
142
pub call_share_sound: bool,
141
143
pub recording_policy: teams_core::RecordingPolicy,
144
pub allow_priority_messages: bool,
142
145
pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
146
pub chat_settings: teams_core::ChatSettingsDocument,
147
pub markdown_mode: bool,
148
pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
143
149
pub own_tenant: Option<String>,
144
150
pub call_share_motion: bool,
145
151
pub call_share_standout: bool,
@@ -231,6 +237,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
231
237
impl AppState {
232
238
pub fn new(store: Arc<Store>, mode: Mode) -> Self {
233
239
let sidebar = store.sidebar().unwrap_or_default();
240
let chat_settings = teams_core::stored_chat_settings(&store);
241
let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
234
242
let mut state = AppState {
235
243
store,
236
244
engine: None,
@@ -238,6 +246,7 @@ impl AppState {
238
246
favorite_ids: Vec::new(),
239
247
selection: None,
240
248
late_arrivals: LateArrivals::default(),
249
acked_urgent: Default::default(),
241
250
new_chat: false,
242
251
new_chat_people: Vec::new(),
243
252
connection: if mode.demo {
@@ -292,7 +301,11 @@ impl AppState {
292
301
call_count: 0,
293
302
call_share_sound: false,
294
303
recording_policy: teams_core::RecordingPolicy::default(),
304
allow_priority_messages: true,
295
305
account_sounds: None,
306
chat_settings,
307
markdown_mode,
308
demo_chat_desktop: HashMap::new(),
296
309
own_tenant: None,
297
310
call_share_motion: false,
298
311
call_share_standout: false,
@@ -534,6 +547,10 @@ impl AppState {
534
547
Some(engine) => data::unread_counts(engine, &self.sidebar.chats),
535
548
None => Default::default(),
536
549
};
550
self.directory.unread_importance = match &self.engine {
551
Some(engine) => data::unread_importance(engine, &self.sidebar.chats),
552
None => Default::default(),
553
};
537
554
}
538
555
539
556
pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {
@@ -993,7 +1010,9 @@ impl AppState {
993
1010
self.refresh_scheduled(cx);
994
1011
self.refresh_translation_settings(cx);
995
1012
self.refresh_recording_policy(cx);
1013
self.refresh_messaging_policy(cx);
996
1014
self.refresh_sound_settings(cx);
1015
self.refresh_chat_settings(cx);
997
1016
let waiting = self.directory.waiting_presence_ids();
998
1017
self.request_presence(waiting, cx);
999
1018
self.refresh_own_status(cx);
@@ -73,6 +73,7 @@ pub enum AppEvent {73
MeetingChime,73
MeetingChime,74
CallTone(chatsvc::sounds::CallTone),74
CallTone(chatsvc::sounds::CallTone),75
SoundSettings,75
SoundSettings,76
ChatSettings,76
}77
}77
78
78
#[derive(Debug, Clone, Copy, Default)]79
#[derive(Debug, Clone, Copy, Default)]@@ -89,6 +90,7 @@ pub struct AppState {89
pub favorite_ids: Vec<String>,90
pub favorite_ids: Vec<String>,90
pub selection: Option<Selection>,91
pub selection: Option<Selection>,91
pub late_arrivals: LateArrivals,92
pub late_arrivals: LateArrivals,93
pub acked_urgent: std::collections::HashSet<String>,92
pub new_chat: bool,94
pub new_chat: bool,93
pub new_chat_people: Vec<store::MemberRecord>,95
pub new_chat_people: Vec<store::MemberRecord>,94
pub connection: ConnectionState,96
pub connection: ConnectionState,@@ -139,7 +141,11 @@ pub struct AppState {139
pub call_count: u64,141
pub call_count: u64,140
pub call_share_sound: bool,142
pub call_share_sound: bool,141
pub recording_policy: teams_core::RecordingPolicy,143
pub recording_policy: teams_core::RecordingPolicy,144
pub allow_priority_messages: bool,142
pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,145
pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,146
pub chat_settings: teams_core::ChatSettingsDocument,147
pub markdown_mode: bool,148
pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,143
pub own_tenant: Option<String>,149
pub own_tenant: Option<String>,144
pub call_share_motion: bool,150
pub call_share_motion: bool,145
pub call_share_standout: bool,151
pub call_share_standout: bool,@@ -231,6 +237,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {231
impl AppState {237
impl AppState {232
pub fn new(store: Arc<Store>, mode: Mode) -> Self {238
pub fn new(store: Arc<Store>, mode: Mode) -> Self {233
let sidebar = store.sidebar().unwrap_or_default();239
let sidebar = store.sidebar().unwrap_or_default();240
let chat_settings = teams_core::stored_chat_settings(&store);241
let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);234
let mut state = AppState {242
let mut state = AppState {235
store,243
store,236
engine: None,244
engine: None,@@ -238,6 +246,7 @@ impl AppState {238
favorite_ids: Vec::new(),246
favorite_ids: Vec::new(),239
selection: None,247
selection: None,240
late_arrivals: LateArrivals::default(),248
late_arrivals: LateArrivals::default(),249
acked_urgent: Default::default(),241
new_chat: false,250
new_chat: false,242
new_chat_people: Vec::new(),251
new_chat_people: Vec::new(),243
connection: if mode.demo {252
connection: if mode.demo {@@ -292,7 +301,11 @@ impl AppState {292
call_count: 0,301
call_count: 0,293
call_share_sound: false,302
call_share_sound: false,294
recording_policy: teams_core::RecordingPolicy::default(),303
recording_policy: teams_core::RecordingPolicy::default(),304
allow_priority_messages: true,295
account_sounds: None,305
account_sounds: None,306
chat_settings,307
markdown_mode,308
demo_chat_desktop: HashMap::new(),296
own_tenant: None,309
own_tenant: None,297
call_share_motion: false,310
call_share_motion: false,298
call_share_standout: false,311
call_share_standout: false,@@ -534,6 +547,10 @@ impl AppState {534
Some(engine) => data::unread_counts(engine, &self.sidebar.chats),547
Some(engine) => data::unread_counts(engine, &self.sidebar.chats),535
None => Default::default(),548
None => Default::default(),536
};549
};550
self.directory.unread_importance = match &self.engine {551
Some(engine) => data::unread_importance(engine, &self.sidebar.chats),552
None => Default::default(),553
};537
}554
}538
555
539
pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {556
pub fn request_avatars(&mut self, user_ids: Vec<String>, cx: &mut Context<Self>) {@@ -993,7 +1010,9 @@ impl AppState {993
self.refresh_scheduled(cx);1010
self.refresh_scheduled(cx);994
self.refresh_translation_settings(cx);1011
self.refresh_translation_settings(cx);995
self.refresh_recording_policy(cx);1012
self.refresh_recording_policy(cx);1013
self.refresh_messaging_policy(cx);996
self.refresh_sound_settings(cx);1014
self.refresh_sound_settings(cx);1015
self.refresh_chat_settings(cx);997
let waiting = self.directory.waiting_presence_ids();1016
let waiting = self.directory.waiting_presence_ids();998
self.request_presence(waiting, cx);1017
self.request_presence(waiting, cx);999
self.refresh_own_status(cx);1018
self.refresh_own_status(cx);@@ -390,7 +390,7 @@ impl AppState {
390
390
self.start_new_chat(cx);
391
391
}
392
392
393
fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
393
pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
394
394
self.sidebar
395
395
.chats
396
396
.iter()
@@ -390,7 +390,7 @@ impl AppState {390
self.start_new_chat(cx);390
self.start_new_chat(cx);391
}391
}392
392
393
fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {393
pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {394
self.sidebar394
self.sidebar395
.chats395
.chats396
.iter()396
.iter()@@ -0,0 +1,162 @@
1
use gpui_kit::Context;
2
use store::Store;
3
use teams_core::{
4
ChatAccountSettings, ChatNotificationMode, ChatSettingChange, ChatSettingsDocument,
5
DesktopNotifications,
6
};
7
8
use crate::app_state::{AppEvent, AppState};
9
use crate::rows::Receipt;
10
use crate::runtime;
11
12
const META_MARKDOWN_MODE: &str = "compose.markdown_mode";
13
14
pub fn stored_markdown_mode(store: &Store) -> bool {
15
store.meta(META_MARKDOWN_MODE).ok().flatten().as_deref() == Some("true")
16
}
17
18
/// Teams shows no read state at all while the own read receipts setting is off.
19
pub fn shown_receipt(settings: &ChatAccountSettings, receipt: Receipt) -> Receipt {
20
if settings.read_receipts {
21
receipt
22
} else {
23
Receipt::Hidden
24
}
25
}
26
27
impl AppState {
28
pub fn account_chat_settings(&self) -> ChatAccountSettings {
29
self.chat_settings.settings()
30
}
31
32
pub fn refresh_chat_settings(&mut self, cx: &mut Context<Self>) {
33
let Some(engine) = self.engine.clone() else {
34
return;
35
};
36
let read = runtime::spawn(async move { engine.refresh_chat_settings().await });
37
cx.spawn(async move |this, cx| {
38
let document = match read.await {
39
Ok(Ok(document)) => document,
40
Ok(Err(error)) => {
41
log::warn!("chat settings not read: {error}");
42
return;
43
}
44
Err(_) => return,
45
};
46
this.update(cx, |state, cx| state.apply_chat_settings(document, cx))
47
.ok();
48
})
49
.detach();
50
}
51
52
pub fn save_chat_setting(&mut self, change: ChatSettingChange, cx: &mut Context<Self>) {
53
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
54
return;
55
};
56
let previous = self.chat_settings.clone();
57
let mut updated = previous.clone();
58
updated.apply(change);
59
self.apply_chat_settings(updated, cx);
60
let Some(engine) = engine_or_demo else {
61
return;
62
};
63
self.run_chat_action(
64
"Setting",
65
async move { engine.save_chat_setting(change).await.map(|_| ()) },
66
move |state, cx| state.apply_chat_settings(previous, cx),
67
|_, _| {},
68
cx,
69
);
70
}
71
72
fn apply_chat_settings(&mut self, document: ChatSettingsDocument, cx: &mut Context<Self>) {
73
if self.chat_settings == document {
74
return;
75
}
76
let _ = teams_core::store_chat_settings(&self.store, &document);
77
self.chat_settings = document;
78
cx.emit(AppEvent::ChatSettings);
79
cx.notify();
80
}
81
82
pub fn set_markdown_mode(&mut self, enabled: bool, cx: &mut Context<Self>) {
83
self.markdown_mode = enabled;
84
let _ = self
85
.store
86
.set_meta(META_MARKDOWN_MODE, if enabled { "true" } else { "false" });
87
cx.emit(AppEvent::ChatSettings);
88
cx.notify();
89
}
90
91
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {
92
match &self.engine {
93
Some(engine) => engine.chat_desktop_notifications(chat_id),
94
None => self
95
.demo_chat_desktop
96
.get(chat_id)
97
.copied()
98
.unwrap_or_default(),
99
}
100
}
101
102
pub fn set_chat_notifications(
103
&mut self,
104
chat_id: &str,
105
mode: ChatNotificationMode,
106
desktop: DesktopNotifications,
107
cx: &mut Context<Self>,
108
) {
109
let Some(previous_muted) = self.chat_record(chat_id).map(|chat| chat.muted) else {
110
return;
111
};
112
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
113
return;
114
};
115
let muted = mode == ChatNotificationMode::Mute;
116
let _ = self.store.set_chat_muted(chat_id, muted);
117
self.reload_sidebar(cx);
118
let Some(engine) = engine_or_demo else {
119
self.demo_chat_desktop.insert(chat_id.to_owned(), desktop);
120
return;
121
};
122
let owned_id = chat_id.to_owned();
123
let revert_id = owned_id.clone();
124
self.run_chat_action(
125
"Chat notifications",
126
async move {
127
engine
128
.set_chat_notifications(&owned_id, mode, desktop)
129
.await
130
},
131
move |state, cx| {
132
let _ = state.store.set_chat_muted(&revert_id, previous_muted);
133
state.reload_sidebar(cx);
134
},
135
|_, _| {},
136
cx,
137
);
138
}
139
}
140
141
#[cfg(test)]
142
mod tests {
143
use super::*;
144
145
#[test]
146
fn receipts_disappear_while_the_own_setting_is_off() {
147
let mut settings = ChatAccountSettings::default();
148
assert_eq!(shown_receipt(&settings, Receipt::Read), Receipt::Read);
149
assert_eq!(shown_receipt(&settings, Receipt::Sent), Receipt::Sent);
150
settings.read_receipts = false;
151
assert_eq!(shown_receipt(&settings, Receipt::Read), Receipt::Hidden);
152
assert_eq!(shown_receipt(&settings, Receipt::Sent), Receipt::Hidden);
153
}
154
155
#[test]
156
fn markdown_mode_is_a_local_setting_that_starts_off() {
157
let store = Store::open_in_memory().unwrap();
158
assert!(!stored_markdown_mode(&store));
159
store.set_meta(META_MARKDOWN_MODE, "true").unwrap();
160
assert!(stored_markdown_mode(&store));
161
}
162
}
@@ -0,0 +1,162 @@1
use gpui_kit::Context;2
use store::Store;3
use teams_core::{4
ChatAccountSettings, ChatNotificationMode, ChatSettingChange, ChatSettingsDocument,5
DesktopNotifications,6
};7
8
use crate::app_state::{AppEvent, AppState};9
use crate::rows::Receipt;10
use crate::runtime;11
12
const META_MARKDOWN_MODE: &str = "compose.markdown_mode";13
14
pub fn stored_markdown_mode(store: &Store) -> bool {15
store.meta(META_MARKDOWN_MODE).ok().flatten().as_deref() == Some("true")16
}17
18
/// Teams shows no read state at all while the own read receipts setting is off.19
pub fn shown_receipt(settings: &ChatAccountSettings, receipt: Receipt) -> Receipt {20
if settings.read_receipts {21
receipt22
} else {23
Receipt::Hidden24
}25
}26
27
impl AppState {28
pub fn account_chat_settings(&self) -> ChatAccountSettings {29
self.chat_settings.settings()30
}31
32
pub fn refresh_chat_settings(&mut self, cx: &mut Context<Self>) {33
let Some(engine) = self.engine.clone() else {34
return;35
};36
let read = runtime::spawn(async move { engine.refresh_chat_settings().await });37
cx.spawn(async move |this, cx| {38
let document = match read.await {39
Ok(Ok(document)) => document,40
Ok(Err(error)) => {41
log::warn!("chat settings not read: {error}");42
return;43
}44
Err(_) => return,45
};46
this.update(cx, |state, cx| state.apply_chat_settings(document, cx))47
.ok();48
})49
.detach();50
}51
52
pub fn save_chat_setting(&mut self, change: ChatSettingChange, cx: &mut Context<Self>) {53
let Some(engine_or_demo) = self.chat_action_engine(cx) else {54
return;55
};56
let previous = self.chat_settings.clone();57
let mut updated = previous.clone();58
updated.apply(change);59
self.apply_chat_settings(updated, cx);60
let Some(engine) = engine_or_demo else {61
return;62
};63
self.run_chat_action(64
"Setting",65
async move { engine.save_chat_setting(change).await.map(|_| ()) },66
move |state, cx| state.apply_chat_settings(previous, cx),67
|_, _| {},68
cx,69
);70
}71
72
fn apply_chat_settings(&mut self, document: ChatSettingsDocument, cx: &mut Context<Self>) {73
if self.chat_settings == document {74
return;75
}76
let _ = teams_core::store_chat_settings(&self.store, &document);77
self.chat_settings = document;78
cx.emit(AppEvent::ChatSettings);79
cx.notify();80
}81
82
pub fn set_markdown_mode(&mut self, enabled: bool, cx: &mut Context<Self>) {83
self.markdown_mode = enabled;84
let _ = self85
.store86
.set_meta(META_MARKDOWN_MODE, if enabled { "true" } else { "false" });87
cx.emit(AppEvent::ChatSettings);88
cx.notify();89
}90
91
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {92
match &self.engine {93
Some(engine) => engine.chat_desktop_notifications(chat_id),94
None => self95
.demo_chat_desktop96
.get(chat_id)97
.copied()98
.unwrap_or_default(),99
}100
}101
102
pub fn set_chat_notifications(103
&mut self,104
chat_id: &str,105
mode: ChatNotificationMode,106
desktop: DesktopNotifications,107
cx: &mut Context<Self>,108
) {109
let Some(previous_muted) = self.chat_record(chat_id).map(|chat| chat.muted) else {110
return;111
};112
let Some(engine_or_demo) = self.chat_action_engine(cx) else {113
return;114
};115
let muted = mode == ChatNotificationMode::Mute;116
let _ = self.store.set_chat_muted(chat_id, muted);117
self.reload_sidebar(cx);118
let Some(engine) = engine_or_demo else {119
self.demo_chat_desktop.insert(chat_id.to_owned(), desktop);120
return;121
};122
let owned_id = chat_id.to_owned();123
let revert_id = owned_id.clone();124
self.run_chat_action(125
"Chat notifications",126
async move {127
engine128
.set_chat_notifications(&owned_id, mode, desktop)129
.await130
},131
move |state, cx| {132
let _ = state.store.set_chat_muted(&revert_id, previous_muted);133
state.reload_sidebar(cx);134
},135
|_, _| {},136
cx,137
);138
}139
}140
141
#[cfg(test)]142
mod tests {143
use super::*;144
145
#[test]146
fn receipts_disappear_while_the_own_setting_is_off() {147
let mut settings = ChatAccountSettings::default();148
assert_eq!(shown_receipt(&settings, Receipt::Read), Receipt::Read);149
assert_eq!(shown_receipt(&settings, Receipt::Sent), Receipt::Sent);150
settings.read_receipts = false;151
assert_eq!(shown_receipt(&settings, Receipt::Read), Receipt::Hidden);152
assert_eq!(shown_receipt(&settings, Receipt::Sent), Receipt::Hidden);153
}154
155
#[test]156
fn markdown_mode_is_a_local_setting_that_starts_off() {157
let store = Store::open_in_memory().unwrap();158
assert!(!stored_markdown_mode(&store));159
store.set_meta(META_MARKDOWN_MODE, "true").unwrap();160
assert!(stored_markdown_mode(&store));161
}162
}@@ -4,7 +4,7 @@ use std::sync::Arc;
4
4
use std::time::{Duration, Instant};
5
5
6
6
use gpui_kit::{Image, ImageFormat};
7
use store::{ChatRecord, Store, is_bot_id};
7
use store::{ChatRecord, MessageImportance, Store, is_bot_id};
8
8
9
9
use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};
10
10
use tokio::sync::oneshot;
@@ -131,6 +131,7 @@ pub struct Directory {
131
131
pub section_settings: ChatSectionSettings,
132
132
pub pinned_channels: Vec<String>,
133
133
pub unread_counts: HashMap<String, u32>,
134
pub unread_importance: HashMap<String, MessageImportance>,
134
135
pub avatars: HashMap<String, AvatarState>,
135
136
pub presence: HashMap<String, (PresenceKind, Instant)>,
136
137
pub activity: HashMap<String, Activity>,
@@ -591,6 +592,26 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u
591
592
.collect()
592
593
}
593
594
595
pub fn unread_importance_of(directory: &Directory, chat: &ChatRecord) -> MessageImportance {
596
directory
597
.unread_importance
598
.get(&chat.id)
599
.copied()
600
.unwrap_or_default()
601
}
602
603
pub fn unread_importance(
604
engine: &Engine,
605
chats: &[ChatRecord],
606
) -> HashMap<String, MessageImportance> {
607
chats
608
.iter()
609
.filter(|chat| chat.unread)
610
.map(|chat| (chat.id.clone(), engine.unread_importance(&chat.id)))
611
.filter(|(_, importance)| importance.is_marked())
612
.collect()
613
}
614
594
615
pub fn presence_kind_of(availability: Availability) -> PresenceKind {
595
616
match availability {
596
617
Availability::Available => PresenceKind::Available,
@@ -4,7 +4,7 @@ use std::sync::Arc;4
use std::time::{Duration, Instant};4
use std::time::{Duration, Instant};5
5
6
use gpui_kit::{Image, ImageFormat};6
use gpui_kit::{Image, ImageFormat};7
use store::{ChatRecord, Store, is_bot_id};7
use store::{ChatRecord, MessageImportance, Store, is_bot_id};8
8
9
use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};9
use teams_core::{Activity, Availability, ChatSectionSettings, FolderChange, is_notes_chat};10
use tokio::sync::oneshot;10
use tokio::sync::oneshot;@@ -131,6 +131,7 @@ pub struct Directory {131
pub section_settings: ChatSectionSettings,131
pub section_settings: ChatSectionSettings,132
pub pinned_channels: Vec<String>,132
pub pinned_channels: Vec<String>,133
pub unread_counts: HashMap<String, u32>,133
pub unread_counts: HashMap<String, u32>,134
pub unread_importance: HashMap<String, MessageImportance>,134
pub avatars: HashMap<String, AvatarState>,135
pub avatars: HashMap<String, AvatarState>,135
pub presence: HashMap<String, (PresenceKind, Instant)>,136
pub presence: HashMap<String, (PresenceKind, Instant)>,136
pub activity: HashMap<String, Activity>,137
pub activity: HashMap<String, Activity>,@@ -591,6 +592,26 @@ pub fn unread_counts(engine: &Engine, chats: &[ChatRecord]) -> HashMap<String, u591
.collect()592
.collect()592
}593
}593
594
595
pub fn unread_importance_of(directory: &Directory, chat: &ChatRecord) -> MessageImportance {596
directory597
.unread_importance598
.get(&chat.id)599
.copied()600
.unwrap_or_default()601
}602
603
pub fn unread_importance(604
engine: &Engine,605
chats: &[ChatRecord],606
) -> HashMap<String, MessageImportance> {607
chats608
.iter()609
.filter(|chat| chat.unread)610
.map(|chat| (chat.id.clone(), engine.unread_importance(&chat.id)))611
.filter(|(_, importance)| importance.is_marked())612
.collect()613
}614
594
pub fn presence_kind_of(availability: Availability) -> PresenceKind {615
pub fn presence_kind_of(availability: Availability) -> PresenceKind {595
match availability {616
match availability {596
Availability::Available => PresenceKind::Available,617
Availability::Available => PresenceKind::Available,@@ -0,0 +1,263 @@
1
use gpui_kit::Context;
2
use store::MessageImportance;
3
use teams_core::NOTES_CHAT_ID;
4
5
use crate::app_state::AppState;
6
use crate::data::is_one_on_one;
7
use crate::runtime;
8
9
pub const DELIVERY_BUTTON_TITLE: &str = "Set delivery options";
10
pub const URGENT_MAX_MEMBERS: usize = 20;
11
pub const URGENT_TOO_MANY_MEMBERS: &str = "Unavailable in chats with more than 20 people";
12
const MEETING_KIND: &str = "meeting";
13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15
pub struct DeliveryOption {
16
pub importance: MessageImportance,
17
pub header: &'static str,
18
pub content: &'static str,
19
pub symbol: &'static str,
20
pub tag: &'static str,
21
}
22
23
pub const STANDARD: DeliveryOption = DeliveryOption {
24
importance: MessageImportance::Normal,
25
header: "Standard",
26
content: "Message will be sent as usual",
27
symbol: "fluent_chat",
28
tag: "standard-delivery-option",
29
};
30
31
pub const IMPORTANT: DeliveryOption = DeliveryOption {
32
importance: MessageImportance::High,
33
header: "Important",
34
content: "Message will be marked as important",
35
symbol: "fluent_important",
36
tag: "important-delivery-option",
37
};
38
39
pub const URGENT: DeliveryOption = DeliveryOption {
40
importance: MessageImportance::Urgent,
41
header: "Urgent",
42
content: "Recipient(s) notified every 2 min for 20 min",
43
symbol: "fluent_alert_urgent",
44
tag: "urgent-delivery-option",
45
};
46
47
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48
pub enum UrgentAvailability {
49
Hidden,
50
Disabled,
51
Available,
52
}
53
54
#[derive(Debug, Clone, Copy, Default)]
55
pub struct DeliveryContext<'a> {
56
pub conversation_id: &'a str,
57
pub chat_kind: &'a str,
58
pub member_count: usize,
59
pub channel: bool,
60
pub one_on_one_bot: bool,
61
pub editing: bool,
62
pub policy_allows_urgent: bool,
63
}
64
65
/// Teams hides Urgent while editing, in notes, bot 1:1 chats, meeting chats, channels and when the messaging policy denies priority messages; more than 20 people disable it.
66
pub fn urgent_availability(context: &DeliveryContext) -> UrgentAvailability {
67
let hidden = context.editing
68
|| !context.policy_allows_urgent
69
|| context.conversation_id == NOTES_CHAT_ID
70
|| context.one_on_one_bot
71
|| context.channel
72
|| context.chat_kind.eq_ignore_ascii_case(MEETING_KIND);
73
if hidden {
74
UrgentAvailability::Hidden
75
} else if context.member_count > URGENT_MAX_MEMBERS {
76
UrgentAvailability::Disabled
77
} else {
78
UrgentAvailability::Available
79
}
80
}
81
82
impl AppState {
83
pub fn urgent_availability(&self, conversation_id: &str, editing: bool) -> UrgentAvailability {
84
let chat = self
85
.sidebar
86
.chats
87
.iter()
88
.find(|chat| chat.id == conversation_id);
89
let one_on_one_bot = chat.is_some_and(|chat| {
90
is_one_on_one(chat)
91
&& self
92
.bot_apps
93
.get(&chat.id)
94
.is_some_and(|apps| apps.iter().any(|app| !app.bot_ids.is_empty()))
95
});
96
urgent_availability(&DeliveryContext {
97
conversation_id,
98
chat_kind: chat.map_or("", |chat| chat.kind.as_str()),
99
member_count: chat.map_or(0, |chat| chat.members.len()),
100
channel: chat.is_none() && !conversation_id.is_empty(),
101
one_on_one_bot,
102
editing,
103
policy_allows_urgent: self.allow_priority_messages,
104
})
105
}
106
107
pub fn refresh_messaging_policy(&mut self, cx: &mut Context<Self>) {
108
let Some(engine) = self.engine.clone() else {
109
return;
110
};
111
let read = runtime::spawn(async move { engine.allow_priority_messages().await.ok() });
112
cx.spawn(async move |this, cx| {
113
let Some(allowed) = read.await.ok().flatten() else {
114
return;
115
};
116
this.update(cx, |state, cx| {
117
state.allow_priority_messages = allowed;
118
cx.notify();
119
})
120
.ok();
121
})
122
.detach();
123
}
124
}
125
126
pub fn delivery_options(urgent: UrgentAvailability) -> Vec<(DeliveryOption, bool)> {
127
let mut options = vec![(STANDARD, true), (IMPORTANT, true)];
128
match urgent {
129
UrgentAvailability::Hidden => {}
130
UrgentAvailability::Disabled => options.push((URGENT, false)),
131
UrgentAvailability::Available => options.push((URGENT, true)),
132
}
133
options
134
}
135
136
/// The importance that can still be sent once the chat or the policy changed.
137
pub fn allowed_importance(
138
importance: MessageImportance,
139
urgent: UrgentAvailability,
140
) -> MessageImportance {
141
if importance == MessageImportance::Urgent && urgent != UrgentAvailability::Available {
142
MessageImportance::Normal
143
} else {
144
importance
145
}
146
}
147
148
pub fn urgent_banner(member_count: usize) -> &'static str {
149
if member_count > 2 {
150
"Notify recipients every 2 minutes for 20 minutes"
151
} else {
152
"Notify recipient every 2 minutes for 20 minutes"
153
}
154
}
155
156
#[cfg(test)]
157
mod tests {
158
use super::*;
159
160
fn group(member_count: usize) -> DeliveryContext<'static> {
161
DeliveryContext {
162
conversation_id: "19:group@thread.v2",
163
chat_kind: "group",
164
member_count,
165
policy_allows_urgent: true,
166
..Default::default()
167
}
168
}
169
170
#[test]
171
fn urgent_is_offered_in_ordinary_chats() {
172
assert_eq!(
173
urgent_availability(&group(5)),
174
UrgentAvailability::Available
175
);
176
let options: Vec<_> = delivery_options(UrgentAvailability::Available)
177
.into_iter()
178
.map(|(option, enabled)| (option.header, enabled))
179
.collect();
180
assert_eq!(
181
options,
182
[("Standard", true), ("Important", true), ("Urgent", true)]
183
);
184
}
185
186
#[test]
187
fn urgent_is_hidden_where_teams_hides_it() {
188
let hidden = [
189
DeliveryContext {
190
conversation_id: NOTES_CHAT_ID,
191
..group(1)
192
},
193
DeliveryContext {
194
chat_kind: "meeting",
195
..group(4)
196
},
197
DeliveryContext {
198
one_on_one_bot: true,
199
..group(1)
200
},
201
DeliveryContext {
202
channel: true,
203
..group(4)
204
},
205
DeliveryContext {
206
editing: true,
207
..group(4)
208
},
209
DeliveryContext {
210
policy_allows_urgent: false,
211
..group(4)
212
},
213
];
214
for context in hidden {
215
assert_eq!(
216
urgent_availability(&context),
217
UrgentAvailability::Hidden,
218
"{context:?}"
219
);
220
}
221
assert_eq!(delivery_options(UrgentAvailability::Hidden).len(), 2);
222
}
223
224
#[test]
225
fn more_than_twenty_people_disable_urgent() {
226
assert_eq!(
227
urgent_availability(&group(20)),
228
UrgentAvailability::Available
229
);
230
assert_eq!(
231
urgent_availability(&group(21)),
232
UrgentAvailability::Disabled
233
);
234
assert_eq!(
235
delivery_options(UrgentAvailability::Disabled)[2],
236
(URGENT, false)
237
);
238
}
239
240
#[test]
241
fn a_chosen_urgent_falls_back_to_standard_where_it_is_not_allowed() {
242
assert_eq!(
243
allowed_importance(MessageImportance::Urgent, UrgentAvailability::Disabled),
244
MessageImportance::Normal
245
);
246
assert_eq!(
247
allowed_importance(MessageImportance::High, UrgentAvailability::Hidden),
248
MessageImportance::High
249
);
250
}
251
252
#[test]
253
fn the_banner_uses_the_plural_for_more_than_two_members() {
254
assert_eq!(
255
urgent_banner(2),
256
"Notify recipient every 2 minutes for 20 minutes"
257
);
258
assert_eq!(
259
urgent_banner(3),
260
"Notify recipients every 2 minutes for 20 minutes"
261
);
262
}
263
}
@@ -0,0 +1,263 @@1
use gpui_kit::Context;2
use store::MessageImportance;3
use teams_core::NOTES_CHAT_ID;4
5
use crate::app_state::AppState;6
use crate::data::is_one_on_one;7
use crate::runtime;8
9
pub const DELIVERY_BUTTON_TITLE: &str = "Set delivery options";10
pub const URGENT_MAX_MEMBERS: usize = 20;11
pub const URGENT_TOO_MANY_MEMBERS: &str = "Unavailable in chats with more than 20 people";12
const MEETING_KIND: &str = "meeting";13
14
#[derive(Debug, Clone, Copy, PartialEq, Eq)]15
pub struct DeliveryOption {16
pub importance: MessageImportance,17
pub header: &'static str,18
pub content: &'static str,19
pub symbol: &'static str,20
pub tag: &'static str,21
}22
23
pub const STANDARD: DeliveryOption = DeliveryOption {24
importance: MessageImportance::Normal,25
header: "Standard",26
content: "Message will be sent as usual",27
symbol: "fluent_chat",28
tag: "standard-delivery-option",29
};30
31
pub const IMPORTANT: DeliveryOption = DeliveryOption {32
importance: MessageImportance::High,33
header: "Important",34
content: "Message will be marked as important",35
symbol: "fluent_important",36
tag: "important-delivery-option",37
};38
39
pub const URGENT: DeliveryOption = DeliveryOption {40
importance: MessageImportance::Urgent,41
header: "Urgent",42
content: "Recipient(s) notified every 2 min for 20 min",43
symbol: "fluent_alert_urgent",44
tag: "urgent-delivery-option",45
};46
47
#[derive(Debug, Clone, Copy, PartialEq, Eq)]48
pub enum UrgentAvailability {49
Hidden,50
Disabled,51
Available,52
}53
54
#[derive(Debug, Clone, Copy, Default)]55
pub struct DeliveryContext<'a> {56
pub conversation_id: &'a str,57
pub chat_kind: &'a str,58
pub member_count: usize,59
pub channel: bool,60
pub one_on_one_bot: bool,61
pub editing: bool,62
pub policy_allows_urgent: bool,63
}64
65
/// Teams hides Urgent while editing, in notes, bot 1:1 chats, meeting chats, channels and when the messaging policy denies priority messages; more than 20 people disable it.66
pub fn urgent_availability(context: &DeliveryContext) -> UrgentAvailability {67
let hidden = context.editing68
|| !context.policy_allows_urgent69
|| context.conversation_id == NOTES_CHAT_ID70
|| context.one_on_one_bot71
|| context.channel72
|| context.chat_kind.eq_ignore_ascii_case(MEETING_KIND);73
if hidden {74
UrgentAvailability::Hidden75
} else if context.member_count > URGENT_MAX_MEMBERS {76
UrgentAvailability::Disabled77
} else {78
UrgentAvailability::Available79
}80
}81
82
impl AppState {83
pub fn urgent_availability(&self, conversation_id: &str, editing: bool) -> UrgentAvailability {84
let chat = self85
.sidebar86
.chats87
.iter()88
.find(|chat| chat.id == conversation_id);89
let one_on_one_bot = chat.is_some_and(|chat| {90
is_one_on_one(chat)91
&& self92
.bot_apps93
.get(&chat.id)94
.is_some_and(|apps| apps.iter().any(|app| !app.bot_ids.is_empty()))95
});96
urgent_availability(&DeliveryContext {97
conversation_id,98
chat_kind: chat.map_or("", |chat| chat.kind.as_str()),99
member_count: chat.map_or(0, |chat| chat.members.len()),100
channel: chat.is_none() && !conversation_id.is_empty(),101
one_on_one_bot,102
editing,103
policy_allows_urgent: self.allow_priority_messages,104
})105
}106
107
pub fn refresh_messaging_policy(&mut self, cx: &mut Context<Self>) {108
let Some(engine) = self.engine.clone() else {109
return;110
};111
let read = runtime::spawn(async move { engine.allow_priority_messages().await.ok() });112
cx.spawn(async move |this, cx| {113
let Some(allowed) = read.await.ok().flatten() else {114
return;115
};116
this.update(cx, |state, cx| {117
state.allow_priority_messages = allowed;118
cx.notify();119
})120
.ok();121
})122
.detach();123
}124
}125
126
pub fn delivery_options(urgent: UrgentAvailability) -> Vec<(DeliveryOption, bool)> {127
let mut options = vec![(STANDARD, true), (IMPORTANT, true)];128
match urgent {129
UrgentAvailability::Hidden => {}130
UrgentAvailability::Disabled => options.push((URGENT, false)),131
UrgentAvailability::Available => options.push((URGENT, true)),132
}133
options134
}135
136
/// The importance that can still be sent once the chat or the policy changed.137
pub fn allowed_importance(138
importance: MessageImportance,139
urgent: UrgentAvailability,140
) -> MessageImportance {141
if importance == MessageImportance::Urgent && urgent != UrgentAvailability::Available {142
MessageImportance::Normal143
} else {144
importance145
}146
}147
148
pub fn urgent_banner(member_count: usize) -> &'static str {149
if member_count > 2 {150
"Notify recipients every 2 minutes for 20 minutes"151
} else {152
"Notify recipient every 2 minutes for 20 minutes"153
}154
}155
156
#[cfg(test)]157
mod tests {158
use super::*;159
160
fn group(member_count: usize) -> DeliveryContext<'static> {161
DeliveryContext {162
conversation_id: "19:group@thread.v2",163
chat_kind: "group",164
member_count,165
policy_allows_urgent: true,166
..Default::default()167
}168
}169
170
#[test]171
fn urgent_is_offered_in_ordinary_chats() {172
assert_eq!(173
urgent_availability(&group(5)),174
UrgentAvailability::Available175
);176
let options: Vec<_> = delivery_options(UrgentAvailability::Available)177
.into_iter()178
.map(|(option, enabled)| (option.header, enabled))179
.collect();180
assert_eq!(181
options,182
[("Standard", true), ("Important", true), ("Urgent", true)]183
);184
}185
186
#[test]187
fn urgent_is_hidden_where_teams_hides_it() {188
let hidden = [189
DeliveryContext {190
conversation_id: NOTES_CHAT_ID,191
..group(1)192
},193
DeliveryContext {194
chat_kind: "meeting",195
..group(4)196
},197
DeliveryContext {198
one_on_one_bot: true,199
..group(1)200
},201
DeliveryContext {202
channel: true,203
..group(4)204
},205
DeliveryContext {206
editing: true,207
..group(4)208
},209
DeliveryContext {210
policy_allows_urgent: false,211
..group(4)212
},213
];214
for context in hidden {215
assert_eq!(216
urgent_availability(&context),217
UrgentAvailability::Hidden,218
"{context:?}"219
);220
}221
assert_eq!(delivery_options(UrgentAvailability::Hidden).len(), 2);222
}223
224
#[test]225
fn more_than_twenty_people_disable_urgent() {226
assert_eq!(227
urgent_availability(&group(20)),228
UrgentAvailability::Available229
);230
assert_eq!(231
urgent_availability(&group(21)),232
UrgentAvailability::Disabled233
);234
assert_eq!(235
delivery_options(UrgentAvailability::Disabled)[2],236
(URGENT, false)237
);238
}239
240
#[test]241
fn a_chosen_urgent_falls_back_to_standard_where_it_is_not_allowed() {242
assert_eq!(243
allowed_importance(MessageImportance::Urgent, UrgentAvailability::Disabled),244
MessageImportance::Normal245
);246
assert_eq!(247
allowed_importance(MessageImportance::High, UrgentAvailability::Hidden),248
MessageImportance::High249
);250
}251
252
#[test]253
fn the_banner_uses_the_plural_for_more_than_two_members() {254
assert_eq!(255
urgent_banner(2),256
"Notify recipient every 2 minutes for 20 minutes"257
);258
assert_eq!(259
urgent_banner(3),260
"Notify recipients every 2 minutes for 20 minutes"261
);262
}263
}@@ -7,8 +7,8 @@ use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7
7
use gpui_kit::{App, Entity};
8
8
use store::{
9
9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,
11
TeamLayoutRecord, TeamRecord,
10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,
11
Store, TeamLayoutRecord, TeamRecord,
12
12
};
13
13
use teams_core::{
14
14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,
@@ -974,6 +974,12 @@ pub fn seed_directory(state: &mut AppState) {
974
974
directory
975
975
.unread_counts
976
976
.insert("demo-chat-allhands".to_owned(), 120);
977
directory
978
.unread_importance
979
.insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
980
directory
981
.unread_importance
982
.insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
977
983
directory.set_avatar(MARA_ID, photo(&MARA));
978
984
directory.set_avatar(PRIYA_ID, photo(&PRIYA));
979
985
directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
@@ -1106,6 +1112,7 @@ fn message(
1106
1112
mentions_json: "[]".to_owned(),
1107
1113
subject: None,
1108
1114
call_event_json: None,
1115
importance: Default::default(),
1109
1116
}
1110
1117
}
1111
1118
@@ -1209,6 +1216,11 @@ fn call_messages() -> Vec<MessageRecord> {
1209
1216
]
1210
1217
}
1211
1218
1219
fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1220
record.importance = importance;
1221
record
1222
}
1223
1212
1224
fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1213
1225
record.subject = Some(subject.to_owned());
1214
1226
record
@@ -1539,6 +1551,12 @@ fn priority_messages() -> Vec<MessageRecord> {
1539
1551
false,
1540
1552
),
1541
1553
]
1554
.into_iter()
1555
.map(|record| match record.message_id.as_str() {
1556
"p2" => with_importance(record, MessageImportance::High),
1557
_ => record,
1558
})
1559
.collect()
1542
1560
}
1543
1561
1544
1562
fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
@@ -1881,6 +1899,10 @@ fn unread_messages() -> Vec<MessageRecord> {
1881
1899
.map(|(id, sender, time, html)| {
1882
1900
message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1883
1901
})
1902
.map(|record| match record.message_id.as_str() {
1903
"u5" => with_importance(record, MessageImportance::Urgent),
1904
_ => record,
1905
})
1884
1906
.collect()
1885
1907
}
1886
1908
@@ -2307,6 +2329,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;
2307
2329
mod tests {
2308
2330
use super::*;
2309
2331
2332
#[test]
2333
fn the_demo_has_one_important_and_one_urgent_message() {
2334
let store = Store::open_in_memory().unwrap();
2335
seed(&store);
2336
let importance = |chat: &str, message_id: &str| {
2337
store
2338
.messages(chat, None, 50)
2339
.unwrap()
2340
.into_iter()
2341
.find(|record| record.message_id == message_id)
2342
.map(|record| record.importance)
2343
};
2344
assert_eq!(
2345
importance(PRIORITY_CHAT, "p2"),
2346
Some(MessageImportance::High)
2347
);
2348
assert_eq!(
2349
importance(UNREAD_CHAT, "u5"),
2350
Some(MessageImportance::Urgent)
2351
);
2352
}
2353
2310
2354
#[test]
2311
2355
fn png_has_signature_and_ends_with_iend() {
2312
2356
let png = encode_png(&MARA);
@@ -7,8 +7,8 @@ use chrono::{DateTime, Duration, Local, TimeZone, Utc};7
use gpui_kit::{App, Entity};7
use gpui_kit::{App, Entity};8
use store::{8
use store::{9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,9
ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store,10
ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,11
TeamLayoutRecord, TeamRecord,11
Store, TeamLayoutRecord, TeamRecord,12
};12
};13
use teams_core::{13
use teams_core::{14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,14
Activity, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language,@@ -974,6 +974,12 @@ pub fn seed_directory(state: &mut AppState) {974
directory974
directory975
.unread_counts975
.unread_counts976
.insert("demo-chat-allhands".to_owned(), 120);976
.insert("demo-chat-allhands".to_owned(), 120);977
directory978
.unread_importance979
.insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);980
directory981
.unread_importance982
.insert("demo-chat-customer-1".to_owned(), MessageImportance::High);977
directory.set_avatar(MARA_ID, photo(&MARA));983
directory.set_avatar(MARA_ID, photo(&MARA));978
directory.set_avatar(PRIYA_ID, photo(&PRIYA));984
directory.set_avatar(PRIYA_ID, photo(&PRIYA));979
directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));985
directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));@@ -1106,6 +1112,7 @@ fn message(1106
mentions_json: "[]".to_owned(),1112
mentions_json: "[]".to_owned(),1107
subject: None,1113
subject: None,1108
call_event_json: None,1114
call_event_json: None,1115
importance: Default::default(),1109
}1116
}1110
}1117
}1111
1118
@@ -1209,6 +1216,11 @@ fn call_messages() -> Vec<MessageRecord> {1209
]1216
]1210
}1217
}1211
1218
1219
fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {1220
record.importance = importance;1221
record1222
}1223
1212
fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {1224
fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {1213
record.subject = Some(subject.to_owned());1225
record.subject = Some(subject.to_owned());1214
record1226
record@@ -1539,6 +1551,12 @@ fn priority_messages() -> Vec<MessageRecord> {1539
false,1551
false,1540
),1552
),1541
]1553
]1554
.into_iter()1555
.map(|record| match record.message_id.as_str() {1556
"p2" => with_importance(record, MessageImportance::High),1557
_ => record,1558
})1559
.collect()1542
}1560
}1543
1561
1544
fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {1562
fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {@@ -1881,6 +1899,10 @@ fn unread_messages() -> Vec<MessageRecord> {1881
.map(|(id, sender, time, html)| {1899
.map(|(id, sender, time, html)| {1882
message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)1900
message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)1883
})1901
})1902
.map(|record| match record.message_id.as_str() {1903
"u5" => with_importance(record, MessageImportance::Urgent),1904
_ => record,1905
})1884
.collect()1906
.collect()1885
}1907
}1886
1908
@@ -2307,6 +2329,28 @@ fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8;2307
mod tests {2329
mod tests {2308
use super::*;2330
use super::*;2309
2331
2332
#[test]2333
fn the_demo_has_one_important_and_one_urgent_message() {2334
let store = Store::open_in_memory().unwrap();2335
seed(&store);2336
let importance = |chat: &str, message_id: &str| {2337
store2338
.messages(chat, None, 50)2339
.unwrap()2340
.into_iter()2341
.find(|record| record.message_id == message_id)2342
.map(|record| record.importance)2343
};2344
assert_eq!(2345
importance(PRIORITY_CHAT, "p2"),2346
Some(MessageImportance::High)2347
);2348
assert_eq!(2349
importance(UNREAD_CHAT, "u5"),2350
Some(MessageImportance::Urgent)2351
);2352
}2353
2310
#[test]2354
#[test]2311
fn png_has_signature_and_ends_with_iend() {2355
fn png_has_signature_and_ends_with_iend() {2312
let png = encode_png(&MARA);2356
let png = encode_png(&MARA);@@ -118,6 +118,7 @@ mod tests {
118
118
mentions_json: "[]".into(),
119
119
subject: None,
120
120
call_event_json: None,
121
importance: Default::default(),
121
122
}
122
123
}
123
124
@@ -118,6 +118,7 @@ mod tests {118
mentions_json: "[]".into(),118
mentions_json: "[]".into(),119
subject: None,119
subject: None,120
call_event_json: None,120
call_event_json: None,121
importance: Default::default(),121
}122
}122
}123
}123
124
@@ -0,0 +1,41 @@
1
use store::MessageImportance;
2
3
/// Teams strings "Important!" / "Urgent!", shown in capitals (`text-transform: uppercase`).
4
pub const IMPORTANT_LABEL: &str = "IMPORTANT!";
5
pub const URGENT_LABEL: &str = "URGENT!";
6
pub const URGENT_TOAST_SUFFIX: &str = "sent an urgent message";
7
8
pub fn importance_label(importance: MessageImportance) -> Option<&'static str> {
9
match importance {
10
MessageImportance::Normal => None,
11
MessageImportance::High => Some(IMPORTANT_LABEL),
12
MessageImportance::Urgent => Some(URGENT_LABEL),
13
}
14
}
15
16
pub fn urgent_toast_title(sender: &str) -> String {
17
format!("{sender} {URGENT_TOAST_SUFFIX}")
18
}
19
20
#[cfg(test)]
21
mod tests {
22
use super::*;
23
24
#[test]
25
fn labels_match_the_teams_strings_in_capitals() {
26
assert_eq!(importance_label(MessageImportance::Normal), None);
27
assert_eq!(
28
importance_label(MessageImportance::High),
29
Some("IMPORTANT!")
30
);
31
assert_eq!(importance_label(MessageImportance::Urgent), Some("URGENT!"));
32
}
33
34
#[test]
35
fn the_urgent_toast_title_names_the_sender() {
36
assert_eq!(
37
urgent_toast_title("Lea Schneider"),
38
"Lea Schneider sent an urgent message"
39
);
40
}
41
}
@@ -0,0 +1,41 @@1
use store::MessageImportance;2
3
/// Teams strings "Important!" / "Urgent!", shown in capitals (`text-transform: uppercase`).4
pub const IMPORTANT_LABEL: &str = "IMPORTANT!";5
pub const URGENT_LABEL: &str = "URGENT!";6
pub const URGENT_TOAST_SUFFIX: &str = "sent an urgent message";7
8
pub fn importance_label(importance: MessageImportance) -> Option<&'static str> {9
match importance {10
MessageImportance::Normal => None,11
MessageImportance::High => Some(IMPORTANT_LABEL),12
MessageImportance::Urgent => Some(URGENT_LABEL),13
}14
}15
16
pub fn urgent_toast_title(sender: &str) -> String {17
format!("{sender} {URGENT_TOAST_SUFFIX}")18
}19
20
#[cfg(test)]21
mod tests {22
use super::*;23
24
#[test]25
fn labels_match_the_teams_strings_in_capitals() {26
assert_eq!(importance_label(MessageImportance::Normal), None);27
assert_eq!(28
importance_label(MessageImportance::High),29
Some("IMPORTANT!")30
);31
assert_eq!(importance_label(MessageImportance::Urgent), Some("URGENT!"));32
}33
34
#[test]35
fn the_urgent_toast_title_names_the_sender() {36
assert_eq!(37
urgent_toast_title("Lea Schneider"),38
"Lea Schneider sent an urgent message"39
);40
}41
}@@ -14,15 +14,18 @@ pub mod chat_actions;
14
14
pub mod chat_filter;
15
15
pub mod find_in_chat;
16
16
pub mod chat_members;
17
pub mod chat_settings_actions;
17
18
pub mod connection_banner;
18
19
pub mod data;
19
20
pub mod default_reactions;
21
pub mod delivery_options;
20
22
pub mod demo;
21
23
pub mod demo_meetings;
22
24
pub mod demo_profiles;
23
25
pub mod emoji;
24
26
pub mod gifs;
25
27
pub mod image_view_gallery;
28
pub mod importance;
26
29
pub mod local_previews;
27
30
pub mod message_actions;
28
31
pub mod notice;
@@ -47,6 +50,7 @@ pub mod stored_outgoing;
47
50
pub mod task_dialog;
48
51
pub mod translation_actions;
49
52
pub mod typing;
53
pub mod urgent_ack;
50
54
51
55
pub use app_ui_kit::render;
52
56
pub use app_base::{
@@ -14,15 +14,18 @@ pub mod chat_actions;14
pub mod chat_filter;14
pub mod chat_filter;15
pub mod find_in_chat;15
pub mod find_in_chat;16
pub mod chat_members;16
pub mod chat_members;17
pub mod chat_settings_actions;17
pub mod connection_banner;18
pub mod connection_banner;18
pub mod data;19
pub mod data;19
pub mod default_reactions;20
pub mod default_reactions;21
pub mod delivery_options;20
pub mod demo;22
pub mod demo;21
pub mod demo_meetings;23
pub mod demo_meetings;22
pub mod demo_profiles;24
pub mod demo_profiles;23
pub mod emoji;25
pub mod emoji;24
pub mod gifs;26
pub mod gifs;25
pub mod image_view_gallery;27
pub mod image_view_gallery;28
pub mod importance;26
pub mod local_previews;29
pub mod local_previews;27
pub mod message_actions;30
pub mod message_actions;28
pub mod notice;31
pub mod notice;@@ -47,6 +50,7 @@ pub mod stored_outgoing;47
pub mod task_dialog;50
pub mod task_dialog;48
pub mod translation_actions;51
pub mod translation_actions;49
pub mod typing;52
pub mod typing;53
pub mod urgent_ack;50
54
51
pub use app_ui_kit::render;55
pub use app_ui_kit::render;52
pub use app_base::{56
pub use app_base::{@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
3
3
use chrono::{DateTime, Utc};
4
4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5
5
6
use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
6
use super::rules::{ChannelSignals, ChatKind, ChatSignals, Incoming, Preview};
7
7
use crate::app_state::chat_title;
8
8
9
9
const RECENT_WINDOW: usize = 20;
@@ -160,6 +160,7 @@ pub fn build_incoming(
160
160
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),
161
161
_ => ChannelSignals::default(),
162
162
};
163
let chat = chat_signals(store, sidebar, &record.conversation_id, my_user_id);
163
164
Some(Incoming {
164
165
conversation_id: record.conversation_id.clone(),
165
166
message_id: record.message_id.clone(),
@@ -171,10 +172,33 @@ pub fn build_incoming(
171
172
mentions_me: mentions_me(record, my_user_id),
172
173
muted: is_muted_chat(sidebar, &record.conversation_id),
173
174
signals,
175
chat,
174
176
created_at: record.created_at,
177
importance: record.importance,
175
178
})
176
179
}
177
180
181
fn chat_signals(
182
store: &Store,
183
sidebar: &Sidebar,
184
conversation_id: &str,
185
my_user_id: Option<&str>,
186
) -> ChatSignals {
187
let meeting = sidebar
188
.chats
189
.iter()
190
.any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));
191
let participated = meeting
192
&& store
193
.messages(conversation_id, None, RECENT_WINDOW)
194
.is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));
195
ChatSignals {
196
meeting,
197
participated,
198
..ChatSignals::default()
199
}
200
}
201
178
202
fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
179
203
sidebar
180
204
.chats
@@ -373,6 +397,7 @@ mod tests {
373
397
reactions_json: "[]".into(),
374
398
mentions_json: "[]".into(),
375
399
call_event_json: None,
400
importance: Default::default(),
376
401
}
377
402
}
378
403
@@ -388,6 +413,27 @@ mod tests {
388
413
assert!(!build(&sidebar()).muted);
389
414
}
390
415
416
#[test]
417
fn meeting_chats_know_whether_i_took_part() {
418
let mut with_meeting = sidebar();
419
with_meeting.chats[1].kind = "meeting".into();
420
let store = Store::open_in_memory().unwrap();
421
let message = record("group", "u1", Utc::now(), "hi");
422
let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
423
assert!(first.chat.meeting);
424
assert!(!first.chat.participated);
425
let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");
426
store.upsert_messages(&[own]).unwrap();
427
let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
428
assert!(later.chat.participated);
429
assert!(
430
!build_incoming(&message, &store, &sidebar(), Some("me"))
431
.unwrap()
432
.chat
433
.meeting
434
);
435
}
436
391
437
#[test]
392
438
fn history_before_start_is_ignored() {
393
439
let start = Utc::now();
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet, VecDeque};3
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};4
use store::{ChannelNotifications, MessageRecord, Sidebar, Store};5
5
6
use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};6
use super::rules::{ChannelSignals, ChatKind, ChatSignals, Incoming, Preview};7
use crate::app_state::chat_title;7
use crate::app_state::chat_title;8
8
9
const RECENT_WINDOW: usize = 20;9
const RECENT_WINDOW: usize = 20;@@ -160,6 +160,7 @@ pub fn build_incoming(160
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),160
ChatKind::Channel { .. } => channel_signals(record, store, sidebar, my_user_id),161
_ => ChannelSignals::default(),161
_ => ChannelSignals::default(),162
};162
};163
let chat = chat_signals(store, sidebar, &record.conversation_id, my_user_id);163
Some(Incoming {164
Some(Incoming {164
conversation_id: record.conversation_id.clone(),165
conversation_id: record.conversation_id.clone(),165
message_id: record.message_id.clone(),166
message_id: record.message_id.clone(),@@ -171,10 +172,33 @@ pub fn build_incoming(171
mentions_me: mentions_me(record, my_user_id),172
mentions_me: mentions_me(record, my_user_id),172
muted: is_muted_chat(sidebar, &record.conversation_id),173
muted: is_muted_chat(sidebar, &record.conversation_id),173
signals,174
signals,175
chat,174
created_at: record.created_at,176
created_at: record.created_at,177
importance: record.importance,175
})178
})176
}179
}177
180
181
fn chat_signals(182
store: &Store,183
sidebar: &Sidebar,184
conversation_id: &str,185
my_user_id: Option<&str>,186
) -> ChatSignals {187
let meeting = sidebar188
.chats189
.iter()190
.any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));191
let participated = meeting192
&& store193
.messages(conversation_id, None, RECENT_WINDOW)194
.is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));195
ChatSignals {196
meeting,197
participated,198
..ChatSignals::default()199
}200
}201
178
fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {202
fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {179
sidebar203
sidebar180
.chats204
.chats@@ -373,6 +397,7 @@ mod tests {373
reactions_json: "[]".into(),397
reactions_json: "[]".into(),374
mentions_json: "[]".into(),398
mentions_json: "[]".into(),375
call_event_json: None,399
call_event_json: None,400
importance: Default::default(),376
}401
}377
}402
}378
403
@@ -388,6 +413,27 @@ mod tests {388
assert!(!build(&sidebar()).muted);413
assert!(!build(&sidebar()).muted);389
}414
}390
415
416
#[test]417
fn meeting_chats_know_whether_i_took_part() {418
let mut with_meeting = sidebar();419
with_meeting.chats[1].kind = "meeting".into();420
let store = Store::open_in_memory().unwrap();421
let message = record("group", "u1", Utc::now(), "hi");422
let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();423
assert!(first.chat.meeting);424
assert!(!first.chat.participated);425
let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");426
store.upsert_messages(&[own]).unwrap();427
let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();428
assert!(later.chat.participated);429
assert!(430
!build_incoming(&message, &store, &sidebar(), Some("me"))431
.unwrap()432
.chat433
.meeting434
);435
}436
391
#[test]437
#[test]392
fn history_before_start_is_ignored() {438
fn history_before_start_is_ignored() {393
let start = Utc::now();439
let start = Utc::now();@@ -200,6 +200,7 @@ mod tests {
200
200
dismissed: false,
201
201
fade: super::super::stack::Fade::shown(std::time::Instant::now()),
202
202
agent: None,
203
urgent: false,
203
204
};
204
205
assert_eq!(toast_height(&model("Hi"), 1), 112.);
205
206
assert_eq!(toast_height(&model("Hi"), 2), 130.);
@@ -207,12 +208,12 @@ mod tests {
207
208
assert_eq!(toast_height(&model("Hi"), 0), 112.);
208
209
let mut agent = model("Hi");
209
210
agent.agent = Some(super::super::stack::AgentToast {
210
run_id: 1,
211
session_id: String::new(),
211
kind: super::super::stack::AgentToastKind::Proposal {
212
proposal_id: "p".into(),
213
},
212
214
header: String::new(),
213
215
title: String::new(),
214
216
body: "Hi".into(),
215
failed: false,
216
217
});
217
218
assert_eq!(toast_height(&agent, 1), 134.);
218
219
assert_eq!(toast_height(&agent, 2), 152.);
@@ -200,6 +200,7 @@ mod tests {200
dismissed: false,200
dismissed: false,201
fade: super::super::stack::Fade::shown(std::time::Instant::now()),201
fade: super::super::stack::Fade::shown(std::time::Instant::now()),202
agent: None,202
agent: None,203
urgent: false,203
};204
};204
assert_eq!(toast_height(&model("Hi"), 1), 112.);205
assert_eq!(toast_height(&model("Hi"), 1), 112.);205
assert_eq!(toast_height(&model("Hi"), 2), 130.);206
assert_eq!(toast_height(&model("Hi"), 2), 130.);@@ -207,12 +208,12 @@ mod tests {207
assert_eq!(toast_height(&model("Hi"), 0), 112.);208
assert_eq!(toast_height(&model("Hi"), 0), 112.);208
let mut agent = model("Hi");209
let mut agent = model("Hi");209
agent.agent = Some(super::super::stack::AgentToast {210
agent.agent = Some(super::super::stack::AgentToast {210
run_id: 1,211
kind: super::super::stack::AgentToastKind::Proposal {211
session_id: String::new(),212
proposal_id: "p".into(),213
},212
header: String::new(),214
header: String::new(),213
title: String::new(),215
title: String::new(),214
body: "Hi".into(),216
body: "Hi".into(),215
failed: false,216
});217
});217
assert_eq!(toast_height(&agent, 1), 134.);218
assert_eq!(toast_height(&agent, 1), 134.);218
assert_eq!(toast_height(&agent, 2), 152.);219
assert_eq!(toast_height(&agent, 2), 152.);@@ -5,6 +5,7 @@ pub mod settings;
5
5
pub mod stack;
6
6
pub mod taskbar;
7
7
pub mod text;
8
pub mod urgent_repeat;
8
9
9
10
pub use app_base::notify::{badge, platform, sound_cache, sounds};
10
11
pub use chatsvc::sound_settings;
@@ -5,6 +5,7 @@ pub mod settings;5
pub mod stack;5
pub mod stack;6
pub mod taskbar;6
pub mod taskbar;7
pub mod text;7
pub mod text;8
pub mod urgent_repeat;8
9
9
pub use app_base::notify::{badge, platform, sound_cache, sounds};10
pub use app_base::notify::{badge, platform, sound_cache, sounds};10
pub use chatsvc::sound_settings;11
pub use chatsvc::sound_settings;@@ -3,7 +3,10 @@ use std::time::{Duration, Instant};
3
3
4
4
use calling::Progress;
5
5
use chrono::{DateTime, Utc};
6
use store::{ChannelNotificationLevel, ChannelNotifications};
6
use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};
7
use teams_core::{
8
DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
9
};
7
10
8
11
use super::sound_settings::SoundSettings;
9
12
use super::sounds::Ringtone;
@@ -69,8 +72,7 @@ impl Corner {
69
72
70
73
#[derive(Debug, Clone, PartialEq, Eq)]
71
74
pub struct Settings {
72
pub mentions_only: bool,
73
pub preview: bool,
75
pub account: NotificationAccountSettings,
74
76
pub corner: Corner,
75
77
pub flash: bool,
76
78
pub close_to_tray: bool,
@@ -82,8 +84,7 @@ pub struct Settings {
82
84
impl Default for Settings {
83
85
fn default() -> Self {
84
86
Settings {
85
mentions_only: false,
86
preview: true,
87
account: NotificationAccountSettings::default(),
87
88
corner: Corner::BottomRight,
88
89
flash: true,
89
90
close_to_tray: true,
@@ -116,6 +117,13 @@ pub struct ChannelSignals {
116
117
pub notifications: ChannelNotifications,
117
118
}
118
119
120
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121
pub struct ChatSignals {
122
pub meeting: bool,
123
pub participated: bool,
124
pub desktop: DesktopNotifications,
125
}
126
119
127
#[derive(Debug, Clone, PartialEq, Eq)]
120
128
pub struct Incoming {
121
129
pub conversation_id: String,
@@ -128,13 +136,19 @@ pub struct Incoming {
128
136
pub mentions_me: bool,
129
137
pub muted: bool,
130
138
pub signals: ChannelSignals,
139
pub chat: ChatSignals,
131
140
pub created_at: DateTime<Utc>,
141
pub importance: MessageImportance,
132
142
}
133
143
134
144
impl Incoming {
135
145
pub fn is_direct(&self) -> bool {
136
146
self.kind == ChatKind::Direct
137
147
}
148
149
pub fn is_urgent(&self) -> bool {
150
self.importance == MessageImportance::Urgent
151
}
138
152
}
139
153
140
154
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -169,6 +183,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {
169
183
pub struct Decision {
170
184
pub toast: bool,
171
185
pub sound: bool,
186
pub urgent_sound: bool,
172
187
}
173
188
174
189
pub fn alerts(incoming: &Incoming) -> bool {
@@ -201,20 +216,76 @@ fn channel_toasts(incoming: &Incoming) -> bool {
201
216
|| signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
202
217
}
203
218
219
fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {
220
if matches!(incoming.kind, ChatKind::Channel { .. }) {
221
return if incoming.mentions_me {
222
account.personal_mentions.shows_banner()
223
} else {
224
account.preset != NotificationPreset::MentionsAndReplies
225
|| incoming.signals.in_my_thread
226
};
227
}
228
let chat = incoming.chat;
229
if chat.desktop == DesktopNotifications::Off {
230
return false;
231
}
232
if incoming.mentions_me {
233
return account.personal_mentions.shows_banner();
234
}
235
let meeting_muted = chat.meeting
236
&& match account.meeting_chats {
237
MeetingChatNotifications::Mute => true,
238
MeetingChatNotifications::MuteUntilJoin => !chat.participated,
239
MeetingChatNotifications::Unmute => false,
240
};
241
!meeting_muted
242
&& (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())
243
}
244
245
pub fn shows_preview(settings: &Settings) -> bool {
246
settings.account.show_preview
247
}
248
204
249
const SILENT: Decision = Decision {
205
250
toast: false,
206
251
sound: false,
252
urgent_sound: false,
207
253
};
208
254
255
/// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").
209
256
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {
257
let urgent = incoming.is_urgent();
210
258
let suppressed = !alerts(incoming)
211
259
|| !channel_toasts(incoming)
212
260
|| environment.chat_in_foreground
213
261
|| environment.system_quiet
214
|| environment.own_do_not_disturb
262
|| (environment.own_do_not_disturb && !urgent)
215
263
|| settings.do_not_disturb
216
264
|| (settings.mute_in_calls && environment.in_call)
217
|| (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());
265
|| (!urgent && !account_toasts(&settings.account, incoming));
266
if suppressed {
267
return SILENT;
268
}
269
let busy_allows = settings.sounds.sound_when_busy || !environment.busy();
270
let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;
271
Decision {
272
toast: true,
273
sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),
274
urgent_sound,
275
}
276
}
277
278
pub fn decide_proposal(
279
settings: &Settings,
280
desktop: DesktopNotifications,
281
environment: Environment,
282
) -> Decision {
283
let suppressed = desktop == DesktopNotifications::Off
284
|| environment.chat_in_foreground
285
|| environment.system_quiet
286
|| environment.own_do_not_disturb
287
|| settings.do_not_disturb
288
|| (settings.mute_in_calls && environment.in_call);
218
289
if suppressed {
219
290
return SILENT;
220
291
}
@@ -222,6 +293,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
222
293
toast: true,
223
294
sound: settings.sounds.notification_sound
224
295
&& (settings.sounds.sound_when_busy || !environment.busy()),
296
urgent_sound: false,
225
297
}
226
298
}
227
299
@@ -267,6 +339,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)
267
339
#[cfg(test)]
268
340
mod tests {
269
341
use calling::{CallState, EndReason};
342
use teams_core::ActivityAlert;
270
343
271
344
use super::*;
272
345
@@ -282,7 +355,9 @@ mod tests {
282
355
mentions_me: false,
283
356
muted: false,
284
357
signals: ChannelSignals::default(),
358
chat: ChatSignals::default(),
285
359
created_at: Utc::now(),
360
importance: Default::default(),
286
361
}
287
362
}
288
363
@@ -304,11 +379,58 @@ mod tests {
304
379
decision,
305
380
Decision {
306
381
toast: true,
307
sound: true
382
sound: true,
383
urgent_sound: false,
308
384
}
309
385
);
310
386
}
311
387
388
#[test]
389
fn proposals_toast_like_messages_but_ignore_chat_mute() {
390
let settings = Settings::default();
391
let shown = decide_proposal(
392
&settings,
393
DesktopNotifications::default(),
394
Environment::default(),
395
);
396
assert!(shown.toast && shown.sound);
397
for environment in [
398
Environment {
399
chat_in_foreground: true,
400
..Default::default()
401
},
402
Environment {
403
own_do_not_disturb: true,
404
..Default::default()
405
},
406
Environment {
407
system_quiet: true,
408
..Default::default()
409
},
410
] {
411
assert_eq!(
412
decide_proposal(&settings, DesktopNotifications::default(), environment),
413
SILENT
414
);
415
}
416
assert_eq!(
417
decide_proposal(&settings, DesktopNotifications::Off, Environment::default()),
418
SILENT
419
);
420
let quiet = Settings {
421
do_not_disturb: true,
422
..Default::default()
423
};
424
assert_eq!(
425
decide_proposal(
426
&quiet,
427
DesktopNotifications::default(),
428
Environment::default()
429
),
430
SILENT
431
);
432
}
433
312
434
#[test]
313
435
fn foreground_chat_is_silent() {
314
436
let environment = Environment {
@@ -339,6 +461,54 @@ mod tests {
339
461
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
340
462
}
341
463
464
fn urgent() -> Incoming {
465
Incoming {
466
importance: MessageImportance::Urgent,
467
..group()
468
}
469
}
470
471
#[test]
472
fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {
473
let dnd = Environment {
474
own_do_not_disturb: true,
475
..Default::default()
476
};
477
assert_eq!(
478
decide(&Settings::default(), &urgent(), dnd),
479
Decision {
480
toast: true,
481
sound: true,
482
urgent_sound: true,
483
}
484
);
485
let mut chat_off = urgent();
486
chat_off.chat.desktop = DesktopNotifications::Off;
487
assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);
488
let foreground = Environment {
489
chat_in_foreground: true,
490
..Default::default()
491
};
492
assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);
493
}
494
495
#[test]
496
fn urgent_sound_follows_its_own_setting() {
497
let mut settings = Settings::default();
498
settings.sounds.urgent_sound = false;
499
let decision = decide(&settings, &urgent(), Environment::default());
500
assert!(decision.toast && !decision.sound && !decision.urgent_sound);
501
settings.sounds.urgent_sound = true;
502
settings.sounds.notification_sound = false;
503
let decision = decide(&settings, &urgent(), Environment::default());
504
assert!(decision.sound && decision.urgent_sound);
505
let important = Incoming {
506
importance: MessageImportance::High,
507
..group()
508
};
509
assert!(!decide(&settings, &important, Environment::default()).sound);
510
}
511
342
512
#[test]
343
513
fn in_call_follows_server_presence_or_a_live_native_call() {
344
514
let model = |state| {
@@ -431,7 +601,8 @@ mod tests {
431
601
decide(&quiet_when_busy, &group(), environment),
432
602
Decision {
433
603
toast: true,
434
sound: false
604
sound: false,
605
urgent_sound: false,
435
606
}
436
607
);
437
608
}
@@ -489,24 +660,84 @@ mod tests {
489
660
assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
490
661
}
491
662
663
fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {
664
let mut settings = Settings::default();
665
change(&mut settings.account);
666
settings
667
}
668
669
fn toasts(settings: &Settings, incoming: &Incoming) -> bool {
670
decide(settings, incoming, Environment::default()).toast
671
}
672
673
fn mention(mut incoming: Incoming) -> Incoming {
674
incoming.mentions_me = true;
675
incoming
676
}
677
492
678
#[test]
493
fn mentions_only_keeps_direct_and_mentions() {
494
let settings = Settings {
495
mentions_only: true,
496
..Default::default()
497
};
498
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
499
assert!(
500
decide(
501
&settings,
502
&incoming(ChatKind::Direct),
503
Environment::default()
504
)
505
.toast
506
);
507
let mut mention = group();
508
mention.mentions_me = true;
509
assert!(decide(&settings, &mention, Environment::default()).toast);
679
fn chat_message_notifications_off_keeps_personal_mentions() {
680
let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
681
assert!(!toasts(&settings, &group()));
682
assert!(!toasts(&settings, &incoming(ChatKind::Direct)));
683
assert!(toasts(&settings, &mention(group())));
684
}
685
686
#[test]
687
fn personal_mentions_only_in_activity_give_no_banner() {
688
let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);
689
assert!(!toasts(&settings, &mention(group())));
690
assert!(!toasts(&settings, &mention(channel())));
691
assert!(toasts(&settings, &group()));
692
}
693
694
#[test]
695
fn mentions_and_replies_preset_drops_plain_channel_posts() {
696
let settings =
697
with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);
698
let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
699
assert!(!toasts(&settings, &post));
700
post.signals.in_my_thread = true;
701
assert!(toasts(&settings, &post));
702
assert!(toasts(&settings, &mention(channel())));
703
assert!(toasts(&settings, &group()));
704
}
705
706
fn meeting_chat(participated: bool) -> Incoming {
707
let mut message = group();
708
message.chat.meeting = true;
709
message.chat.participated = participated;
710
message
711
}
712
713
#[test]
714
fn meeting_chats_stay_quiet_until_i_take_part() {
715
let settings = Settings::default();
716
assert!(!toasts(&settings, &meeting_chat(false)));
717
assert!(toasts(&settings, &meeting_chat(true)));
718
assert!(toasts(&settings, &mention(meeting_chat(false))));
719
}
720
721
#[test]
722
fn meeting_chat_mute_and_unmute() {
723
let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);
724
assert!(!toasts(&muted, &meeting_chat(true)));
725
assert!(toasts(&muted, &mention(meeting_chat(true))));
726
let unmuted =
727
with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);
728
assert!(toasts(&unmuted, &meeting_chat(false)));
729
}
730
731
#[test]
732
fn per_chat_desktop_preference_overrides_the_account() {
733
let mut silenced = group();
734
silenced.chat.desktop = DesktopNotifications::Off;
735
assert!(!toasts(&Settings::default(), &silenced));
736
assert!(!toasts(&Settings::default(), &mention(silenced)));
737
let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
738
let mut selected = group();
739
selected.chat.desktop = DesktopNotifications::On;
740
assert!(toasts(&settings, &selected));
510
741
}
511
742
512
743
fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
@@ -627,7 +858,8 @@ mod tests {
627
858
decision,
628
859
Decision {
629
860
toast: true,
630
sound: false
861
sound: false,
862
urgent_sound: false,
631
863
}
632
864
);
633
865
}
@@ -3,7 +3,10 @@ use std::time::{Duration, Instant};3
3
4
use calling::Progress;4
use calling::Progress;5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use store::{ChannelNotificationLevel, ChannelNotifications};6
use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};7
use teams_core::{8
DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,9
};7
10
8
use super::sound_settings::SoundSettings;11
use super::sound_settings::SoundSettings;9
use super::sounds::Ringtone;12
use super::sounds::Ringtone;@@ -69,8 +72,7 @@ impl Corner {69
72
70
#[derive(Debug, Clone, PartialEq, Eq)]73
#[derive(Debug, Clone, PartialEq, Eq)]71
pub struct Settings {74
pub struct Settings {72
pub mentions_only: bool,75
pub account: NotificationAccountSettings,73
pub preview: bool,74
pub corner: Corner,76
pub corner: Corner,75
pub flash: bool,77
pub flash: bool,76
pub close_to_tray: bool,78
pub close_to_tray: bool,@@ -82,8 +84,7 @@ pub struct Settings {82
impl Default for Settings {84
impl Default for Settings {83
fn default() -> Self {85
fn default() -> Self {84
Settings {86
Settings {85
mentions_only: false,87
account: NotificationAccountSettings::default(),86
preview: true,87
corner: Corner::BottomRight,88
corner: Corner::BottomRight,88
flash: true,89
flash: true,89
close_to_tray: true,90
close_to_tray: true,@@ -116,6 +117,13 @@ pub struct ChannelSignals {116
pub notifications: ChannelNotifications,117
pub notifications: ChannelNotifications,117
}118
}118
119
120
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]121
pub struct ChatSignals {122
pub meeting: bool,123
pub participated: bool,124
pub desktop: DesktopNotifications,125
}126
119
#[derive(Debug, Clone, PartialEq, Eq)]127
#[derive(Debug, Clone, PartialEq, Eq)]120
pub struct Incoming {128
pub struct Incoming {121
pub conversation_id: String,129
pub conversation_id: String,@@ -128,13 +136,19 @@ pub struct Incoming {128
pub mentions_me: bool,136
pub mentions_me: bool,129
pub muted: bool,137
pub muted: bool,130
pub signals: ChannelSignals,138
pub signals: ChannelSignals,139
pub chat: ChatSignals,131
pub created_at: DateTime<Utc>,140
pub created_at: DateTime<Utc>,141
pub importance: MessageImportance,132
}142
}133
143
134
impl Incoming {144
impl Incoming {135
pub fn is_direct(&self) -> bool {145
pub fn is_direct(&self) -> bool {136
self.kind == ChatKind::Direct146
self.kind == ChatKind::Direct137
}147
}148
149
pub fn is_urgent(&self) -> bool {150
self.importance == MessageImportance::Urgent151
}138
}152
}139
153
140
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]154
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -169,6 +183,7 @@ pub fn should_ringback(native_call: Option<&CallModel>) -> bool {169
pub struct Decision {183
pub struct Decision {170
pub toast: bool,184
pub toast: bool,171
pub sound: bool,185
pub sound: bool,186
pub urgent_sound: bool,172
}187
}173
188
174
pub fn alerts(incoming: &Incoming) -> bool {189
pub fn alerts(incoming: &Incoming) -> bool {@@ -201,20 +216,76 @@ fn channel_toasts(incoming: &Incoming) -> bool {201
|| signals.notifications.level == ChannelNotificationLevel::BannerAndFeed216
|| signals.notifications.level == ChannelNotificationLevel::BannerAndFeed202
}217
}203
218
219
fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {220
if matches!(incoming.kind, ChatKind::Channel { .. }) {221
return if incoming.mentions_me {222
account.personal_mentions.shows_banner()223
} else {224
account.preset != NotificationPreset::MentionsAndReplies225
|| incoming.signals.in_my_thread226
};227
}228
let chat = incoming.chat;229
if chat.desktop == DesktopNotifications::Off {230
return false;231
}232
if incoming.mentions_me {233
return account.personal_mentions.shows_banner();234
}235
let meeting_muted = chat.meeting236
&& match account.meeting_chats {237
MeetingChatNotifications::Mute => true,238
MeetingChatNotifications::MuteUntilJoin => !chat.participated,239
MeetingChatNotifications::Unmute => false,240
};241
!meeting_muted242
&& (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())243
}244
245
pub fn shows_preview(settings: &Settings) -> bool {246
settings.account.show_preview247
}248
204
const SILENT: Decision = Decision {249
const SILENT: Decision = Decision {205
toast: false,250
toast: false,206
sound: false,251
sound: false,252
urgent_sound: false,207
};253
};208
254
255
/// Teams lets urgent messages through Do not disturb ("You'll only get notifications for urgent messages and from your priority contacts").209
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {256
pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment) -> Decision {257
let urgent = incoming.is_urgent();210
let suppressed = !alerts(incoming)258
let suppressed = !alerts(incoming)211
|| !channel_toasts(incoming)259
|| !channel_toasts(incoming)212
|| environment.chat_in_foreground260
|| environment.chat_in_foreground213
|| environment.system_quiet261
|| environment.system_quiet214
|| environment.own_do_not_disturb262
|| (environment.own_do_not_disturb && !urgent)215
|| settings.do_not_disturb263
|| settings.do_not_disturb216
|| (settings.mute_in_calls && environment.in_call)264
|| (settings.mute_in_calls && environment.in_call)217
|| (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());265
|| (!urgent && !account_toasts(&settings.account, incoming));266
if suppressed {267
return SILENT;268
}269
let busy_allows = settings.sounds.sound_when_busy || !environment.busy();270
let urgent_sound = urgent && settings.sounds.urgent_sound && busy_allows;271
Decision {272
toast: true,273
sound: urgent_sound || (!urgent && settings.sounds.notification_sound && busy_allows),274
urgent_sound,275
}276
}277
278
pub fn decide_proposal(279
settings: &Settings,280
desktop: DesktopNotifications,281
environment: Environment,282
) -> Decision {283
let suppressed = desktop == DesktopNotifications::Off284
|| environment.chat_in_foreground285
|| environment.system_quiet286
|| environment.own_do_not_disturb287
|| settings.do_not_disturb288
|| (settings.mute_in_calls && environment.in_call);218
if suppressed {289
if suppressed {219
return SILENT;290
return SILENT;220
}291
}@@ -222,6 +293,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment222
toast: true,293
toast: true,223
sound: settings.sounds.notification_sound294
sound: settings.sounds.notification_sound224
&& (settings.sounds.sound_when_busy || !environment.busy()),295
&& (settings.sounds.sound_when_busy || !environment.busy()),296
urgent_sound: false,225
}297
}226
}298
}227
299
@@ -267,6 +339,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)267
#[cfg(test)]339
#[cfg(test)]268
mod tests {340
mod tests {269
use calling::{CallState, EndReason};341
use calling::{CallState, EndReason};342
use teams_core::ActivityAlert;270
343
271
use super::*;344
use super::*;272
345
@@ -282,7 +355,9 @@ mod tests {282
mentions_me: false,355
mentions_me: false,283
muted: false,356
muted: false,284
signals: ChannelSignals::default(),357
signals: ChannelSignals::default(),358
chat: ChatSignals::default(),285
created_at: Utc::now(),359
created_at: Utc::now(),360
importance: Default::default(),286
}361
}287
}362
}288
363
@@ -304,11 +379,58 @@ mod tests {304
decision,379
decision,305
Decision {380
Decision {306
toast: true,381
toast: true,307
sound: true382
sound: true,383
urgent_sound: false,308
}384
}309
);385
);310
}386
}311
387
388
#[test]389
fn proposals_toast_like_messages_but_ignore_chat_mute() {390
let settings = Settings::default();391
let shown = decide_proposal(392
&settings,393
DesktopNotifications::default(),394
Environment::default(),395
);396
assert!(shown.toast && shown.sound);397
for environment in [398
Environment {399
chat_in_foreground: true,400
..Default::default()401
},402
Environment {403
own_do_not_disturb: true,404
..Default::default()405
},406
Environment {407
system_quiet: true,408
..Default::default()409
},410
] {411
assert_eq!(412
decide_proposal(&settings, DesktopNotifications::default(), environment),413
SILENT414
);415
}416
assert_eq!(417
decide_proposal(&settings, DesktopNotifications::Off, Environment::default()),418
SILENT419
);420
let quiet = Settings {421
do_not_disturb: true,422
..Default::default()423
};424
assert_eq!(425
decide_proposal(426
&quiet,427
DesktopNotifications::default(),428
Environment::default()429
),430
SILENT431
);432
}433
312
#[test]434
#[test]313
fn foreground_chat_is_silent() {435
fn foreground_chat_is_silent() {314
let environment = Environment {436
let environment = Environment {@@ -339,6 +461,54 @@ mod tests {339
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);461
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);340
}462
}341
463
464
fn urgent() -> Incoming {465
Incoming {466
importance: MessageImportance::Urgent,467
..group()468
}469
}470
471
#[test]472
fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {473
let dnd = Environment {474
own_do_not_disturb: true,475
..Default::default()476
};477
assert_eq!(478
decide(&Settings::default(), &urgent(), dnd),479
Decision {480
toast: true,481
sound: true,482
urgent_sound: true,483
}484
);485
let mut chat_off = urgent();486
chat_off.chat.desktop = DesktopNotifications::Off;487
assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);488
let foreground = Environment {489
chat_in_foreground: true,490
..Default::default()491
};492
assert_eq!(decide(&Settings::default(), &urgent(), foreground), SILENT);493
}494
495
#[test]496
fn urgent_sound_follows_its_own_setting() {497
let mut settings = Settings::default();498
settings.sounds.urgent_sound = false;499
let decision = decide(&settings, &urgent(), Environment::default());500
assert!(decision.toast && !decision.sound && !decision.urgent_sound);501
settings.sounds.urgent_sound = true;502
settings.sounds.notification_sound = false;503
let decision = decide(&settings, &urgent(), Environment::default());504
assert!(decision.sound && decision.urgent_sound);505
let important = Incoming {506
importance: MessageImportance::High,507
..group()508
};509
assert!(!decide(&settings, &important, Environment::default()).sound);510
}511
342
#[test]512
#[test]343
fn in_call_follows_server_presence_or_a_live_native_call() {513
fn in_call_follows_server_presence_or_a_live_native_call() {344
let model = |state| {514
let model = |state| {@@ -431,7 +601,8 @@ mod tests {431
decide(&quiet_when_busy, &group(), environment),601
decide(&quiet_when_busy, &group(), environment),432
Decision {602
Decision {433
toast: true,603
toast: true,434
sound: false604
sound: false,605
urgent_sound: false,435
}606
}436
);607
);437
}608
}@@ -489,24 +660,84 @@ mod tests {489
assert!(decide(&Settings::default(), &muted, Environment::default()).toast);660
assert!(decide(&Settings::default(), &muted, Environment::default()).toast);490
}661
}491
662
663
fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {664
let mut settings = Settings::default();665
change(&mut settings.account);666
settings667
}668
669
fn toasts(settings: &Settings, incoming: &Incoming) -> bool {670
decide(settings, incoming, Environment::default()).toast671
}672
673
fn mention(mut incoming: Incoming) -> Incoming {674
incoming.mentions_me = true;675
incoming676
}677
492
#[test]678
#[test]493
fn mentions_only_keeps_direct_and_mentions() {679
fn chat_message_notifications_off_keeps_personal_mentions() {494
let settings = Settings {680
let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);495
mentions_only: true,681
assert!(!toasts(&settings, &group()));496
..Default::default()682
assert!(!toasts(&settings, &incoming(ChatKind::Direct)));497
};683
assert!(toasts(&settings, &mention(group())));498
assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);684
}499
assert!(685
500
decide(686
#[test]501
&settings,687
fn personal_mentions_only_in_activity_give_no_banner() {502
&incoming(ChatKind::Direct),688
let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);503
Environment::default()689
assert!(!toasts(&settings, &mention(group())));504
)690
assert!(!toasts(&settings, &mention(channel())));505
.toast691
assert!(toasts(&settings, &group()));506
);692
}507
let mut mention = group();693
508
mention.mentions_me = true;694
#[test]509
assert!(decide(&settings, &mention, Environment::default()).toast);695
fn mentions_and_replies_preset_drops_plain_channel_posts() {696
let settings =697
with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);698
let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);699
assert!(!toasts(&settings, &post));700
post.signals.in_my_thread = true;701
assert!(toasts(&settings, &post));702
assert!(toasts(&settings, &mention(channel())));703
assert!(toasts(&settings, &group()));704
}705
706
fn meeting_chat(participated: bool) -> Incoming {707
let mut message = group();708
message.chat.meeting = true;709
message.chat.participated = participated;710
message711
}712
713
#[test]714
fn meeting_chats_stay_quiet_until_i_take_part() {715
let settings = Settings::default();716
assert!(!toasts(&settings, &meeting_chat(false)));717
assert!(toasts(&settings, &meeting_chat(true)));718
assert!(toasts(&settings, &mention(meeting_chat(false))));719
}720
721
#[test]722
fn meeting_chat_mute_and_unmute() {723
let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);724
assert!(!toasts(&muted, &meeting_chat(true)));725
assert!(toasts(&muted, &mention(meeting_chat(true))));726
let unmuted =727
with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);728
assert!(toasts(&unmuted, &meeting_chat(false)));729
}730
731
#[test]732
fn per_chat_desktop_preference_overrides_the_account() {733
let mut silenced = group();734
silenced.chat.desktop = DesktopNotifications::Off;735
assert!(!toasts(&Settings::default(), &silenced));736
assert!(!toasts(&Settings::default(), &mention(silenced)));737
let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);738
let mut selected = group();739
selected.chat.desktop = DesktopNotifications::On;740
assert!(toasts(&settings, &selected));510
}741
}511
742
512
fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {743
fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {@@ -627,7 +858,8 @@ mod tests {627
decision,858
decision,628
Decision {859
Decision {629
toast: true,860
toast: true,630
sound: false861
sound: false,862
urgent_sound: false,631
}863
}632
);864
);633
}865
}@@ -1,7 +1,7 @@
1
1
use store::Store;
2
2
3
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
4
3
use super::rules::{Corner, Settings};
4
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
5
5
6
6
const META_KEY: &str = "notifications.settings";
7
7
const RINGTONE_PREFIX: &str = "ringtone.";
@@ -29,18 +29,37 @@ fn serialize(settings: &Settings) -> String {
29
29
});
30
30
[
31
31
("sound".to_owned(), sounds.notification_sound.to_string()),
32
("sound_type".to_owned(), sounds.notification_sound_type.name().to_owned()),
32
(
33
"sound_type".to_owned(),
34
sounds.notification_sound_type.name().to_owned(),
35
),
33
36
("urgent_sound".to_owned(), sounds.urgent_sound.to_string()),
34
("urgent_sound_type".to_owned(), sounds.urgent_sound_type.name().to_owned()),
35
("call_sound".to_owned(), sounds.call_and_meeting_sound.to_string()),
36
("sound_when_busy".to_owned(), sounds.sound_when_busy.to_string()),
37
("mentions_only".to_owned(), settings.mentions_only.to_string()),
38
("preview".to_owned(), settings.preview.to_string()),
37
(
38
"urgent_sound_type".to_owned(),
39
sounds.urgent_sound_type.name().to_owned(),
40
),
41
(
42
"call_sound".to_owned(),
43
sounds.call_and_meeting_sound.to_string(),
44
),
45
(
46
"sound_when_busy".to_owned(),
47
sounds.sound_when_busy.to_string(),
48
),
39
49
("corner".to_owned(), settings.corner.key().to_owned()),
40
50
("taskbar_flash".to_owned(), settings.flash.to_string()),
41
("close_to_tray".to_owned(), settings.close_to_tray.to_string()),
42
("do_not_disturb".to_owned(), settings.do_not_disturb.to_string()),
43
("mute_in_calls".to_owned(), settings.mute_in_calls.to_string()),
51
(
52
"close_to_tray".to_owned(),
53
settings.close_to_tray.to_string(),
54
),
55
(
56
"do_not_disturb".to_owned(),
57
settings.do_not_disturb.to_string(),
58
),
59
(
60
"mute_in_calls".to_owned(),
61
settings.mute_in_calls.to_string(),
62
),
44
63
]
45
64
.into_iter()
46
65
.chain(ringtones)
@@ -64,8 +83,6 @@ fn parse(text: &str) -> Settings {
64
83
"urgent_sound_type" => set_alert_sound(&mut sounds.urgent_sound_type, value),
65
84
"call_sound" => sounds.call_and_meeting_sound = flag,
66
85
"sound_when_busy" => sounds.sound_when_busy = flag,
67
"mentions_only" => settings.mentions_only = flag,
68
"preview" => settings.preview = flag,
69
86
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),
70
87
"taskbar_flash" => settings.flash = flag,
71
88
"close_to_tray" => settings.close_to_tray = flag,
@@ -100,8 +117,7 @@ mod tests {
100
117
#[test]
101
118
fn round_trips_every_field() {
102
119
let settings = Settings {
103
mentions_only: true,
104
preview: false,
120
account: Default::default(),
105
121
corner: Corner::TopLeft,
106
122
flash: false,
107
123
close_to_tray: false,
@@ -133,6 +149,10 @@ mod tests {
133
149
#[test]
134
150
fn the_old_synthesized_ringtone_key_is_ignored() {
135
151
assert_eq!(parse("ringtone=chime"), Settings::default());
152
assert_eq!(
153
parse("mentions_only=true\npreview=false"),
154
Settings::default()
155
);
136
156
}
137
157
138
158
#[test]
@@ -1,7 +1,7 @@1
use store::Store;1
use store::Store;2
2
3
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};4
use super::rules::{Corner, Settings};3
use super::rules::{Corner, Settings};4
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};5
5
6
const META_KEY: &str = "notifications.settings";6
const META_KEY: &str = "notifications.settings";7
const RINGTONE_PREFIX: &str = "ringtone.";7
const RINGTONE_PREFIX: &str = "ringtone.";@@ -29,18 +29,37 @@ fn serialize(settings: &Settings) -> String {29
});29
});30
[30
[31
("sound".to_owned(), sounds.notification_sound.to_string()),31
("sound".to_owned(), sounds.notification_sound.to_string()),32
("sound_type".to_owned(), sounds.notification_sound_type.name().to_owned()),32
(33
"sound_type".to_owned(),34
sounds.notification_sound_type.name().to_owned(),35
),33
("urgent_sound".to_owned(), sounds.urgent_sound.to_string()),36
("urgent_sound".to_owned(), sounds.urgent_sound.to_string()),34
("urgent_sound_type".to_owned(), sounds.urgent_sound_type.name().to_owned()),37
(35
("call_sound".to_owned(), sounds.call_and_meeting_sound.to_string()),38
"urgent_sound_type".to_owned(),36
("sound_when_busy".to_owned(), sounds.sound_when_busy.to_string()),39
sounds.urgent_sound_type.name().to_owned(),37
("mentions_only".to_owned(), settings.mentions_only.to_string()),40
),38
("preview".to_owned(), settings.preview.to_string()),41
(42
"call_sound".to_owned(),43
sounds.call_and_meeting_sound.to_string(),44
),45
(46
"sound_when_busy".to_owned(),47
sounds.sound_when_busy.to_string(),48
),39
("corner".to_owned(), settings.corner.key().to_owned()),49
("corner".to_owned(), settings.corner.key().to_owned()),40
("taskbar_flash".to_owned(), settings.flash.to_string()),50
("taskbar_flash".to_owned(), settings.flash.to_string()),41
("close_to_tray".to_owned(), settings.close_to_tray.to_string()),51
(42
("do_not_disturb".to_owned(), settings.do_not_disturb.to_string()),52
"close_to_tray".to_owned(),43
("mute_in_calls".to_owned(), settings.mute_in_calls.to_string()),53
settings.close_to_tray.to_string(),54
),55
(56
"do_not_disturb".to_owned(),57
settings.do_not_disturb.to_string(),58
),59
(60
"mute_in_calls".to_owned(),61
settings.mute_in_calls.to_string(),62
),44
]63
]45
.into_iter()64
.into_iter()46
.chain(ringtones)65
.chain(ringtones)@@ -64,8 +83,6 @@ fn parse(text: &str) -> Settings {64
"urgent_sound_type" => set_alert_sound(&mut sounds.urgent_sound_type, value),83
"urgent_sound_type" => set_alert_sound(&mut sounds.urgent_sound_type, value),65
"call_sound" => sounds.call_and_meeting_sound = flag,84
"call_sound" => sounds.call_and_meeting_sound = flag,66
"sound_when_busy" => sounds.sound_when_busy = flag,85
"sound_when_busy" => sounds.sound_when_busy = flag,67
"mentions_only" => settings.mentions_only = flag,68
"preview" => settings.preview = flag,69
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),86
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),70
"taskbar_flash" => settings.flash = flag,87
"taskbar_flash" => settings.flash = flag,71
"close_to_tray" => settings.close_to_tray = flag,88
"close_to_tray" => settings.close_to_tray = flag,@@ -100,8 +117,7 @@ mod tests {100
#[test]117
#[test]101
fn round_trips_every_field() {118
fn round_trips_every_field() {102
let settings = Settings {119
let settings = Settings {103
mentions_only: true,120
account: Default::default(),104
preview: false,105
corner: Corner::TopLeft,121
corner: Corner::TopLeft,106
flash: false,122
flash: false,107
close_to_tray: false,123
close_to_tray: false,@@ -133,6 +149,10 @@ mod tests {133
#[test]149
#[test]134
fn the_old_synthesized_ringtone_key_is_ignored() {150
fn the_old_synthesized_ringtone_key_is_ignored() {135
assert_eq!(parse("ringtone=chime"), Settings::default());151
assert_eq!(parse("ringtone=chime"), Settings::default());152
assert_eq!(153
parse("mentions_only=true\npreview=false"),154
Settings::default()155
);136
}156
}137
157
138
#[test]158
#[test]@@ -140,14 +140,37 @@ pub enum ReplyState {
140
140
Failed,
141
141
}
142
142
143
#[derive(Debug, Clone, PartialEq, Eq)]
144
pub enum AgentToastKind {
145
Run {
146
run_id: u64,
147
session_id: String,
148
failed: bool,
149
},
150
Proposal {
151
proposal_id: String,
152
},
153
}
154
143
155
#[derive(Debug, Clone, PartialEq, Eq)]
144
156
pub struct AgentToast {
145
pub run_id: u64,
146
pub session_id: String,
157
pub kind: AgentToastKind,
147
158
pub header: String,
148
159
pub title: String,
149
160
pub body: String,
150
pub failed: bool,
161
}
162
163
impl AgentToast {
164
pub fn failed(&self) -> bool {
165
matches!(self.kind, AgentToastKind::Run { failed: true, .. })
166
}
167
168
pub fn proposal_id(&self) -> Option<&str> {
169
match &self.kind {
170
AgentToastKind::Proposal { proposal_id } => Some(proposal_id),
171
AgentToastKind::Run { .. } => None,
172
}
173
}
151
174
}
152
175
153
176
#[derive(Debug, Clone)]
@@ -171,6 +194,7 @@ pub struct ToastModel {
171
194
pub dismissed: bool,
172
195
pub fade: Fade,
173
196
pub agent: Option<AgentToast>,
197
pub urgent: bool,
174
198
}
175
199
176
200
impl ToastModel {
@@ -218,6 +242,7 @@ impl ToastStack {
218
242
existing.sender_id = incoming.sender_id.clone();
219
243
existing.sender_name = incoming.sender_name.clone();
220
244
existing.preview = incoming.preview.clone();
245
existing.urgent = incoming.is_urgent();
221
246
let mention = existing.mentions_me;
222
247
existing.timer.restart(now, mention);
223
248
return PushOutcome {
@@ -248,6 +273,7 @@ impl ToastStack {
248
273
dismissed: false,
249
274
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
250
275
agent: None,
276
urgent: incoming.is_urgent(),
251
277
});
252
278
PushOutcome {
253
279
id: self.next_id,
@@ -285,6 +311,7 @@ impl ToastStack {
285
311
dismissed: false,
286
312
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
287
313
agent: Some(agent),
314
urgent: false,
288
315
});
289
316
self.next_id
290
317
}
@@ -422,7 +449,9 @@ mod tests {
422
449
mentions_me: mention,
423
450
muted: false,
424
451
signals: Default::default(),
452
chat: Default::default(),
425
453
created_at: chrono::Utc::now(),
454
importance: Default::default(),
426
455
}
427
456
}
428
457
@@ -618,12 +647,14 @@ mod tests {
618
647
619
648
fn agent_toast() -> AgentToast {
620
649
AgentToast {
621
run_id: 7,
622
session_id: "s".into(),
650
kind: AgentToastKind::Run {
651
run_id: 7,
652
session_id: "s".into(),
653
failed: false,
654
},
623
655
header: "Answer this - Claude - 1:02".into(),
624
656
title: "Claude finished: Answer this for Mara".into(),
625
657
body: "Done".into(),
626
failed: false,
627
658
}
628
659
}
629
660
@@ -140,14 +140,37 @@ pub enum ReplyState {140
Failed,140
Failed,141
}141
}142
142
143
#[derive(Debug, Clone, PartialEq, Eq)]144
pub enum AgentToastKind {145
Run {146
run_id: u64,147
session_id: String,148
failed: bool,149
},150
Proposal {151
proposal_id: String,152
},153
}154
143
#[derive(Debug, Clone, PartialEq, Eq)]155
#[derive(Debug, Clone, PartialEq, Eq)]144
pub struct AgentToast {156
pub struct AgentToast {145
pub run_id: u64,157
pub kind: AgentToastKind,146
pub session_id: String,147
pub header: String,158
pub header: String,148
pub title: String,159
pub title: String,149
pub body: String,160
pub body: String,150
pub failed: bool,161
}162
163
impl AgentToast {164
pub fn failed(&self) -> bool {165
matches!(self.kind, AgentToastKind::Run { failed: true, .. })166
}167
168
pub fn proposal_id(&self) -> Option<&str> {169
match &self.kind {170
AgentToastKind::Proposal { proposal_id } => Some(proposal_id),171
AgentToastKind::Run { .. } => None,172
}173
}151
}174
}152
175
153
#[derive(Debug, Clone)]176
#[derive(Debug, Clone)]@@ -171,6 +194,7 @@ pub struct ToastModel {171
pub dismissed: bool,194
pub dismissed: bool,172
pub fade: Fade,195
pub fade: Fade,173
pub agent: Option<AgentToast>,196
pub agent: Option<AgentToast>,197
pub urgent: bool,174
}198
}175
199
176
impl ToastModel {200
impl ToastModel {@@ -218,6 +242,7 @@ impl ToastStack {218
existing.sender_id = incoming.sender_id.clone();242
existing.sender_id = incoming.sender_id.clone();219
existing.sender_name = incoming.sender_name.clone();243
existing.sender_name = incoming.sender_name.clone();220
existing.preview = incoming.preview.clone();244
existing.preview = incoming.preview.clone();245
existing.urgent = incoming.is_urgent();221
let mention = existing.mentions_me;246
let mention = existing.mentions_me;222
existing.timer.restart(now, mention);247
existing.timer.restart(now, mention);223
return PushOutcome {248
return PushOutcome {@@ -248,6 +273,7 @@ impl ToastStack {248
dismissed: false,273
dismissed: false,249
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),274
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),250
agent: None,275
agent: None,276
urgent: incoming.is_urgent(),251
});277
});252
PushOutcome {278
PushOutcome {253
id: self.next_id,279
id: self.next_id,@@ -285,6 +311,7 @@ impl ToastStack {285
dismissed: false,311
dismissed: false,286
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),312
fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),287
agent: Some(agent),313
agent: Some(agent),314
urgent: false,288
});315
});289
self.next_id316
self.next_id290
}317
}@@ -422,7 +449,9 @@ mod tests {422
mentions_me: mention,449
mentions_me: mention,423
muted: false,450
muted: false,424
signals: Default::default(),451
signals: Default::default(),452
chat: Default::default(),425
created_at: chrono::Utc::now(),453
created_at: chrono::Utc::now(),454
importance: Default::default(),426
}455
}427
}456
}428
457
@@ -618,12 +647,14 @@ mod tests {618
647
619
fn agent_toast() -> AgentToast {648
fn agent_toast() -> AgentToast {620
AgentToast {649
AgentToast {621
run_id: 7,650
kind: AgentToastKind::Run {622
session_id: "s".into(),651
run_id: 7,652
session_id: "s".into(),653
failed: false,654
},623
header: "Answer this - Claude - 1:02".into(),655
header: "Answer this - Claude - 1:02".into(),624
title: "Claude finished: Answer this for Mara".into(),656
title: "Claude finished: Answer this for Mara".into(),625
body: "Done".into(),657
body: "Done".into(),626
failed: false,627
}658
}628
}659
}629
660
@@ -1,6 +1,7 @@
1
1
use super::rules::{ChatKind, Preview};
2
2
use super::stack::ToastModel;
3
3
use crate::format;
4
use crate::importance::urgent_toast_title;
4
5
5
6
const PREVIEW_OFF: &str = "New message";
6
7
const IMAGE_LABEL: &str = "Image";
@@ -26,14 +27,12 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
26
27
} else {
27
28
model.sender_name.as_str()
28
29
};
29
let (title, subtitle) = match &model.kind {
30
ChatKind::Direct => (sender.to_owned(), "Direct".to_owned()),
31
ChatKind::Group { member_count } => (
32
model.chat_title.clone(),
33
format!("Group, {member_count} people"),
34
),
35
ChatKind::Channel { team, channel } => (sender.to_owned(), format!("{team} > {channel}")),
30
let title = match &model.kind {
31
_ if model.urgent => urgent_toast_title(sender),
32
ChatKind::Group { .. } => model.chat_title.clone(),
33
ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),
36
34
};
35
let subtitle = subtitle_of(&model.kind);
37
36
let body = match (&model.preview, preview_on) {
38
37
(_, false) => PREVIEW_OFF.to_owned(),
39
38
(Preview::Text(text), true) => text.clone(),
@@ -53,6 +52,14 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {
53
52
}
54
53
}
55
54
55
fn subtitle_of(kind: &ChatKind) -> String {
56
match kind {
57
ChatKind::Direct => "Direct".to_owned(),
58
ChatKind::Group { member_count } => format!("Group, {member_count} people"),
59
ChatKind::Channel { team, channel } => format!("{team} > {channel}"),
60
}
61
}
62
56
63
/// Byte range of the first word after each `@`, for highlighting mentions.
57
64
pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {
58
65
let mut ranges = Vec::new();
@@ -99,6 +106,7 @@ mod tests {
99
106
dismissed: false,
100
107
fade: Fade::shown(Instant::now()),
101
108
agent: None,
109
urgent: false,
102
110
}
103
111
}
104
112
@@ -113,6 +121,19 @@ mod tests {
113
121
assert_eq!(text.preview, "Hello");
114
122
}
115
123
124
#[test]
125
fn urgent_names_the_sender_like_teams() {
126
let mut urgent = model(
127
ChatKind::Group { member_count: 5 },
128
Preview::Text("Server down".into()),
129
);
130
urgent.urgent = true;
131
let text = describe(&urgent, true);
132
assert_eq!(text.title, "Priya Nair sent an urgent message");
133
assert_eq!(text.subtitle, "Group, 5 people");
134
assert_eq!(text.preview, "Priya: Server down");
135
}
136
116
137
#[test]
117
138
fn group_shows_chat_title_and_prefixes_sender() {
118
139
let text = describe(
@@ -1,6 +1,7 @@1
use super::rules::{ChatKind, Preview};1
use super::rules::{ChatKind, Preview};2
use super::stack::ToastModel;2
use super::stack::ToastModel;3
use crate::format;3
use crate::format;4
use crate::importance::urgent_toast_title;4
5
5
const PREVIEW_OFF: &str = "New message";6
const PREVIEW_OFF: &str = "New message";6
const IMAGE_LABEL: &str = "Image";7
const IMAGE_LABEL: &str = "Image";@@ -26,14 +27,12 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {26
} else {27
} else {27
model.sender_name.as_str()28
model.sender_name.as_str()28
};29
};29
let (title, subtitle) = match &model.kind {30
let title = match &model.kind {30
ChatKind::Direct => (sender.to_owned(), "Direct".to_owned()),31
_ if model.urgent => urgent_toast_title(sender),31
ChatKind::Group { member_count } => (32
ChatKind::Group { .. } => model.chat_title.clone(),32
model.chat_title.clone(),33
ChatKind::Direct | ChatKind::Channel { .. } => sender.to_owned(),33
format!("Group, {member_count} people"),34
),35
ChatKind::Channel { team, channel } => (sender.to_owned(), format!("{team} > {channel}")),36
};34
};35
let subtitle = subtitle_of(&model.kind);37
let body = match (&model.preview, preview_on) {36
let body = match (&model.preview, preview_on) {38
(_, false) => PREVIEW_OFF.to_owned(),37
(_, false) => PREVIEW_OFF.to_owned(),39
(Preview::Text(text), true) => text.clone(),38
(Preview::Text(text), true) => text.clone(),@@ -53,6 +52,14 @@ pub fn describe(model: &ToastModel, preview_on: bool) -> ToastText {53
}52
}54
}53
}55
54
55
fn subtitle_of(kind: &ChatKind) -> String {56
match kind {57
ChatKind::Direct => "Direct".to_owned(),58
ChatKind::Group { member_count } => format!("Group, {member_count} people"),59
ChatKind::Channel { team, channel } => format!("{team} > {channel}"),60
}61
}62
56
/// Byte range of the first word after each `@`, for highlighting mentions.63
/// Byte range of the first word after each `@`, for highlighting mentions.57
pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {64
pub fn mention_ranges(text: &str) -> Vec<std::ops::Range<usize>> {58
let mut ranges = Vec::new();65
let mut ranges = Vec::new();@@ -99,6 +106,7 @@ mod tests {99
dismissed: false,106
dismissed: false,100
fade: Fade::shown(Instant::now()),107
fade: Fade::shown(Instant::now()),101
agent: None,108
agent: None,109
urgent: false,102
}110
}103
}111
}104
112
@@ -113,6 +121,19 @@ mod tests {113
assert_eq!(text.preview, "Hello");121
assert_eq!(text.preview, "Hello");114
}122
}115
123
124
#[test]125
fn urgent_names_the_sender_like_teams() {126
let mut urgent = model(127
ChatKind::Group { member_count: 5 },128
Preview::Text("Server down".into()),129
);130
urgent.urgent = true;131
let text = describe(&urgent, true);132
assert_eq!(text.title, "Priya Nair sent an urgent message");133
assert_eq!(text.subtitle, "Group, 5 people");134
assert_eq!(text.preview, "Priya: Server down");135
}136
116
#[test]137
#[test]117
fn group_shows_chat_title_and_prefixes_sender() {138
fn group_shows_chat_title_and_prefixes_sender() {118
let text = describe(139
let text = describe(@@ -0,0 +1,180 @@
1
use chrono::{DateTime, Duration, Utc};
2
3
use super::rules::Incoming;
4
5
pub const REPEAT_INTERVAL_MINUTES: i64 = 2;
6
pub const REPEAT_WINDOW_MINUTES: i64 = 20;
7
const REPEAT_COUNT: i64 = REPEAT_WINDOW_MINUTES / REPEAT_INTERVAL_MINUTES;
8
9
struct Pending {
10
incoming: Incoming,
11
repeats_sent: i64,
12
}
13
14
/// Teams notifies again every 2 minutes for 20 minutes until an urgent message is read.
15
#[derive(Default)]
16
pub struct UrgentRepeats {
17
pending: Vec<Pending>,
18
}
19
20
impl UrgentRepeats {
21
pub fn track(&mut self, incoming: &Incoming, now: DateTime<Utc>) {
22
let already_tracked = self.pending.iter().any(|pending| {
23
pending.incoming.conversation_id == incoming.conversation_id
24
&& pending.incoming.message_id == incoming.message_id
25
});
26
if !incoming.is_urgent() || already_tracked || expired(incoming.created_at, now) {
27
return;
28
}
29
self.pending.push(Pending {
30
incoming: incoming.clone(),
31
repeats_sent: 0,
32
});
33
}
34
35
pub fn stop_conversation(&mut self, conversation_id: &str) {
36
self.pending
37
.retain(|pending| pending.incoming.conversation_id != conversation_id);
38
}
39
40
pub fn stop_read(&mut self, read_until: impl Fn(&str) -> Option<DateTime<Utc>>) {
41
self.pending.retain(|pending| {
42
read_until(&pending.incoming.conversation_id)
43
.is_none_or(|read_at| read_at < pending.incoming.created_at)
44
});
45
}
46
47
pub fn due(&mut self, now: DateTime<Utc>) -> Vec<Incoming> {
48
let mut repeats = Vec::new();
49
self.pending.retain_mut(|pending| {
50
if expired(pending.incoming.created_at, now) {
51
return false;
52
}
53
let slot = elapsed_slots(pending.incoming.created_at, now).min(REPEAT_COUNT);
54
if slot > pending.repeats_sent {
55
pending.repeats_sent = slot;
56
repeats.push(pending.incoming.clone());
57
}
58
pending.repeats_sent < REPEAT_COUNT
59
});
60
repeats
61
}
62
63
pub fn is_empty(&self) -> bool {
64
self.pending.is_empty()
65
}
66
}
67
68
fn elapsed_slots(created_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 {
69
let elapsed = now - created_at;
70
if elapsed < Duration::zero() {
71
return 0;
72
}
73
elapsed.num_seconds() / (REPEAT_INTERVAL_MINUTES * 60)
74
}
75
76
fn expired(created_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {
77
now - created_at >= Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES)
78
}
79
80
#[cfg(test)]
81
mod tests {
82
use chrono::TimeZone;
83
use store::MessageImportance;
84
85
use super::*;
86
use crate::notify::rules::{ChatKind, Preview};
87
88
fn sent_at() -> DateTime<Utc> {
89
Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap()
90
}
91
92
fn minutes(count: i64) -> DateTime<Utc> {
93
sent_at() + Duration::minutes(count)
94
}
95
96
fn incoming(importance: MessageImportance) -> Incoming {
97
Incoming {
98
conversation_id: "chat".into(),
99
message_id: "m1".into(),
100
kind: ChatKind::Direct,
101
chat_title: "Lea".into(),
102
sender_id: Some("lea".into()),
103
sender_name: "Lea".into(),
104
preview: Preview::Text("Server down".into()),
105
mentions_me: false,
106
muted: false,
107
signals: Default::default(),
108
chat: Default::default(),
109
created_at: sent_at(),
110
importance,
111
}
112
}
113
114
fn tracked() -> UrgentRepeats {
115
let mut repeats = UrgentRepeats::default();
116
repeats.track(&incoming(MessageImportance::Urgent), sent_at());
117
repeats
118
}
119
120
#[test]
121
fn repeats_every_two_minutes_for_twenty_minutes() {
122
let mut repeats = tracked();
123
let mut pings = Vec::new();
124
for second in (0..=25 * 60).step_by(10) {
125
let now = sent_at() + Duration::seconds(second);
126
if !repeats.due(now).is_empty() {
127
pings.push(second / 60);
128
}
129
}
130
assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
131
assert!(repeats.is_empty());
132
}
133
134
#[test]
135
fn only_urgent_messages_repeat() {
136
let mut repeats = UrgentRepeats::default();
137
repeats.track(&incoming(MessageImportance::High), sent_at());
138
repeats.track(&incoming(MessageImportance::Normal), sent_at());
139
assert!(repeats.is_empty());
140
}
141
142
#[test]
143
fn tracking_twice_keeps_one_schedule() {
144
let mut repeats = tracked();
145
repeats.track(&incoming(MessageImportance::Urgent), minutes(1));
146
assert_eq!(repeats.due(minutes(2)).len(), 1);
147
}
148
149
#[test]
150
fn a_missed_tick_pings_once_not_in_a_burst() {
151
let mut repeats = tracked();
152
assert_eq!(repeats.due(minutes(9)).len(), 1);
153
assert!(repeats.due(minutes(9)).is_empty());
154
assert_eq!(repeats.due(minutes(10)).len(), 1);
155
}
156
157
#[test]
158
fn opening_the_chat_stops_the_repeats() {
159
let mut repeats = tracked();
160
repeats.stop_conversation("chat");
161
assert!(repeats.due(minutes(2)).is_empty());
162
assert!(repeats.is_empty());
163
}
164
165
#[test]
166
fn reading_on_another_device_stops_the_repeats() {
167
let mut repeats = tracked();
168
repeats.stop_read(|_| Some(minutes(-1)));
169
assert!(!repeats.is_empty());
170
repeats.stop_read(|_| Some(sent_at()));
171
assert!(repeats.is_empty());
172
}
173
174
#[test]
175
fn a_message_older_than_the_window_is_not_tracked() {
176
let mut repeats = UrgentRepeats::default();
177
repeats.track(&incoming(MessageImportance::Urgent), minutes(30));
178
assert!(repeats.is_empty());
179
}
180
}
@@ -0,0 +1,180 @@1
use chrono::{DateTime, Duration, Utc};2
3
use super::rules::Incoming;4
5
pub const REPEAT_INTERVAL_MINUTES: i64 = 2;6
pub const REPEAT_WINDOW_MINUTES: i64 = 20;7
const REPEAT_COUNT: i64 = REPEAT_WINDOW_MINUTES / REPEAT_INTERVAL_MINUTES;8
9
struct Pending {10
incoming: Incoming,11
repeats_sent: i64,12
}13
14
/// Teams notifies again every 2 minutes for 20 minutes until an urgent message is read.15
#[derive(Default)]16
pub struct UrgentRepeats {17
pending: Vec<Pending>,18
}19
20
impl UrgentRepeats {21
pub fn track(&mut self, incoming: &Incoming, now: DateTime<Utc>) {22
let already_tracked = self.pending.iter().any(|pending| {23
pending.incoming.conversation_id == incoming.conversation_id24
&& pending.incoming.message_id == incoming.message_id25
});26
if !incoming.is_urgent() || already_tracked || expired(incoming.created_at, now) {27
return;28
}29
self.pending.push(Pending {30
incoming: incoming.clone(),31
repeats_sent: 0,32
});33
}34
35
pub fn stop_conversation(&mut self, conversation_id: &str) {36
self.pending37
.retain(|pending| pending.incoming.conversation_id != conversation_id);38
}39
40
pub fn stop_read(&mut self, read_until: impl Fn(&str) -> Option<DateTime<Utc>>) {41
self.pending.retain(|pending| {42
read_until(&pending.incoming.conversation_id)43
.is_none_or(|read_at| read_at < pending.incoming.created_at)44
});45
}46
47
pub fn due(&mut self, now: DateTime<Utc>) -> Vec<Incoming> {48
let mut repeats = Vec::new();49
self.pending.retain_mut(|pending| {50
if expired(pending.incoming.created_at, now) {51
return false;52
}53
let slot = elapsed_slots(pending.incoming.created_at, now).min(REPEAT_COUNT);54
if slot > pending.repeats_sent {55
pending.repeats_sent = slot;56
repeats.push(pending.incoming.clone());57
}58
pending.repeats_sent < REPEAT_COUNT59
});60
repeats61
}62
63
pub fn is_empty(&self) -> bool {64
self.pending.is_empty()65
}66
}67
68
fn elapsed_slots(created_at: DateTime<Utc>, now: DateTime<Utc>) -> i64 {69
let elapsed = now - created_at;70
if elapsed < Duration::zero() {71
return 0;72
}73
elapsed.num_seconds() / (REPEAT_INTERVAL_MINUTES * 60)74
}75
76
fn expired(created_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {77
now - created_at >= Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES)78
}79
80
#[cfg(test)]81
mod tests {82
use chrono::TimeZone;83
use store::MessageImportance;84
85
use super::*;86
use crate::notify::rules::{ChatKind, Preview};87
88
fn sent_at() -> DateTime<Utc> {89
Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap()90
}91
92
fn minutes(count: i64) -> DateTime<Utc> {93
sent_at() + Duration::minutes(count)94
}95
96
fn incoming(importance: MessageImportance) -> Incoming {97
Incoming {98
conversation_id: "chat".into(),99
message_id: "m1".into(),100
kind: ChatKind::Direct,101
chat_title: "Lea".into(),102
sender_id: Some("lea".into()),103
sender_name: "Lea".into(),104
preview: Preview::Text("Server down".into()),105
mentions_me: false,106
muted: false,107
signals: Default::default(),108
chat: Default::default(),109
created_at: sent_at(),110
importance,111
}112
}113
114
fn tracked() -> UrgentRepeats {115
let mut repeats = UrgentRepeats::default();116
repeats.track(&incoming(MessageImportance::Urgent), sent_at());117
repeats118
}119
120
#[test]121
fn repeats_every_two_minutes_for_twenty_minutes() {122
let mut repeats = tracked();123
let mut pings = Vec::new();124
for second in (0..=25 * 60).step_by(10) {125
let now = sent_at() + Duration::seconds(second);126
if !repeats.due(now).is_empty() {127
pings.push(second / 60);128
}129
}130
assert_eq!(pings, [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);131
assert!(repeats.is_empty());132
}133
134
#[test]135
fn only_urgent_messages_repeat() {136
let mut repeats = UrgentRepeats::default();137
repeats.track(&incoming(MessageImportance::High), sent_at());138
repeats.track(&incoming(MessageImportance::Normal), sent_at());139
assert!(repeats.is_empty());140
}141
142
#[test]143
fn tracking_twice_keeps_one_schedule() {144
let mut repeats = tracked();145
repeats.track(&incoming(MessageImportance::Urgent), minutes(1));146
assert_eq!(repeats.due(minutes(2)).len(), 1);147
}148
149
#[test]150
fn a_missed_tick_pings_once_not_in_a_burst() {151
let mut repeats = tracked();152
assert_eq!(repeats.due(minutes(9)).len(), 1);153
assert!(repeats.due(minutes(9)).is_empty());154
assert_eq!(repeats.due(minutes(10)).len(), 1);155
}156
157
#[test]158
fn opening_the_chat_stops_the_repeats() {159
let mut repeats = tracked();160
repeats.stop_conversation("chat");161
assert!(repeats.due(minutes(2)).is_empty());162
assert!(repeats.is_empty());163
}164
165
#[test]166
fn reading_on_another_device_stops_the_repeats() {167
let mut repeats = tracked();168
repeats.stop_read(|_| Some(minutes(-1)));169
assert!(!repeats.is_empty());170
repeats.stop_read(|_| Some(sent_at()));171
assert!(repeats.is_empty());172
}173
174
#[test]175
fn a_message_older_than_the_window_is_not_tracked() {176
let mut repeats = UrgentRepeats::default();177
repeats.track(&incoming(MessageImportance::Urgent), minutes(30));178
assert!(repeats.is_empty());179
}180
}@@ -8,6 +8,8 @@ use teams_core::{
8
8
OBJECT_MARK, UploadedFile,
9
9
};
10
10
11
use store::MessageImportance;
12
11
13
use crate::remote_image::RemoteImage;
12
14
13
15
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -57,6 +59,7 @@ pub struct Outgoing {
57
59
pub images: Vec<OutgoingImage>,
58
60
pub files: Vec<OutgoingFile>,
59
61
pub link_preview: Option<LinkPreview>,
62
pub importance: MessageImportance,
60
63
}
61
64
62
65
impl Outgoing {
@@ -95,6 +98,7 @@ impl Outgoing {
95
98
96
99
pub fn extras(&self) -> MessageExtras {
97
100
MessageExtras {
101
importance: self.importance.stored(),
98
102
kept: Vec::new(),
99
103
images: self
100
104
.images
@@ -8,6 +8,8 @@ use teams_core::{8
OBJECT_MARK, UploadedFile,8
OBJECT_MARK, UploadedFile,9
};9
};10
10
11
use store::MessageImportance;12
11
use crate::remote_image::RemoteImage;13
use crate::remote_image::RemoteImage;12
14
13
#[derive(Debug, Clone, PartialEq, Eq)]15
#[derive(Debug, Clone, PartialEq, Eq)]@@ -57,6 +59,7 @@ pub struct Outgoing {57
pub images: Vec<OutgoingImage>,59
pub images: Vec<OutgoingImage>,58
pub files: Vec<OutgoingFile>,60
pub files: Vec<OutgoingFile>,59
pub link_preview: Option<LinkPreview>,61
pub link_preview: Option<LinkPreview>,62
pub importance: MessageImportance,60
}63
}61
64
62
impl Outgoing {65
impl Outgoing {@@ -95,6 +98,7 @@ impl Outgoing {95
98
96
pub fn extras(&self) -> MessageExtras {99
pub fn extras(&self) -> MessageExtras {97
MessageExtras {100
MessageExtras {101
importance: self.importance.stored(),98
kept: Vec::new(),102
kept: Vec::new(),99
images: self103
images: self100
.images104
.images@@ -79,6 +79,7 @@ pub fn pending_row(
79
79
})
80
80
.collect(),
81
81
subject: outgoing.subject.clone(),
82
importance: outgoing.importance,
82
83
new_marker: false,
83
84
reply_root: None,
84
85
delivery,
@@ -112,6 +113,7 @@ mod tests {
112
113
images: Vec::new(),
113
114
files: Vec::new(),
114
115
link_preview: None,
116
importance: Default::default(),
115
117
};
116
118
let row = pending_row(
117
119
"key".to_owned(),
@@ -79,6 +79,7 @@ pub fn pending_row(79
})79
})80
.collect(),80
.collect(),81
subject: outgoing.subject.clone(),81
subject: outgoing.subject.clone(),82
importance: outgoing.importance,82
new_marker: false,83
new_marker: false,83
reply_root: None,84
reply_root: None,84
delivery,85
delivery,@@ -112,6 +113,7 @@ mod tests {112
images: Vec::new(),113
images: Vec::new(),113
files: Vec::new(),114
files: Vec::new(),114
link_preview: None,115
link_preview: None,116
importance: Default::default(),115
};117
};116
let row = pending_row(118
let row = pending_row(117
"key".to_owned(),119
"key".to_owned(),@@ -4,7 +4,7 @@ use std::sync::Arc;
4
4
5
5
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6
6
use gpui_kit::Image;
7
use store::MessageRecord;
7
use store::{MessageImportance, MessageRecord};
8
8
use teams_core::roster_event::{RosterEvent, roster_event};
9
9
use teams_core::{
10
10
JumboEmoji, jumbo_emoji,
@@ -140,6 +140,7 @@ pub struct MessageRow {
140
140
pub meeting_link: Option<String>,
141
141
pub adaptive_cards: Vec<AdaptiveCard>,
142
142
pub subject: Option<String>,
143
pub importance: MessageImportance,
143
144
pub new_marker: bool,
144
145
pub reply_root: Option<String>,
145
146
pub delivery: Delivery,
@@ -711,6 +712,7 @@ fn event_row(
711
712
meeting_link: None,
712
713
adaptive_cards: Vec::new(),
713
714
subject: None,
715
importance: MessageImportance::Normal,
714
716
new_marker: false,
715
717
reply_root: None,
716
718
delivery: Delivery::Delivered,
@@ -845,6 +847,11 @@ fn message_row_with(
845
847
_ => adaptive_cards(record),
846
848
},
847
849
subject: record.subject.clone(),
850
importance: if record.deleted {
851
MessageImportance::Normal
852
} else {
853
record.importance
854
},
848
855
new_marker: false,
849
856
reply_root: record.reply_to_id.clone(),
850
857
delivery: Delivery::Delivered,
@@ -1177,6 +1184,7 @@ mod tests {
1177
1184
mentions_json: "[]".into(),
1178
1185
subject: None,
1179
1186
call_event_json: None,
1187
importance: Default::default(),
1180
1188
}
1181
1189
}
1182
1190
@@ -4,7 +4,7 @@ use std::sync::Arc;4
4
5
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};5
use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};6
use gpui_kit::Image;6
use gpui_kit::Image;7
use store::MessageRecord;7
use store::{MessageImportance, MessageRecord};8
use teams_core::roster_event::{RosterEvent, roster_event};8
use teams_core::roster_event::{RosterEvent, roster_event};9
use teams_core::{9
use teams_core::{10
JumboEmoji, jumbo_emoji,10
JumboEmoji, jumbo_emoji,@@ -140,6 +140,7 @@ pub struct MessageRow {140
pub meeting_link: Option<String>,140
pub meeting_link: Option<String>,141
pub adaptive_cards: Vec<AdaptiveCard>,141
pub adaptive_cards: Vec<AdaptiveCard>,142
pub subject: Option<String>,142
pub subject: Option<String>,143
pub importance: MessageImportance,143
pub new_marker: bool,144
pub new_marker: bool,144
pub reply_root: Option<String>,145
pub reply_root: Option<String>,145
pub delivery: Delivery,146
pub delivery: Delivery,@@ -711,6 +712,7 @@ fn event_row(711
meeting_link: None,712
meeting_link: None,712
adaptive_cards: Vec::new(),713
adaptive_cards: Vec::new(),713
subject: None,714
subject: None,715
importance: MessageImportance::Normal,714
new_marker: false,716
new_marker: false,715
reply_root: None,717
reply_root: None,716
delivery: Delivery::Delivered,718
delivery: Delivery::Delivered,@@ -845,6 +847,11 @@ fn message_row_with(845
_ => adaptive_cards(record),847
_ => adaptive_cards(record),846
},848
},847
subject: record.subject.clone(),849
subject: record.subject.clone(),850
importance: if record.deleted {851
MessageImportance::Normal852
} else {853
record.importance854
},848
new_marker: false,855
new_marker: false,849
reply_root: record.reply_to_id.clone(),856
reply_root: record.reply_to_id.clone(),850
delivery: Delivery::Delivered,857
delivery: Delivery::Delivered,@@ -1177,6 +1184,7 @@ mod tests {1177
mentions_json: "[]".into(),1184
mentions_json: "[]".into(),1178
subject: None,1185
subject: None,1179
call_event_json: None,1186
call_event_json: None,1187
importance: Default::default(),1180
}1188
}1181
}1189
}1182
1190
@@ -35,6 +35,7 @@ pub fn scheduled_outgoing(html: &str) -> Outgoing {
35
35
images: Vec::new(),
36
36
files: Vec::new(),
37
37
link_preview: None,
38
importance: Default::default(),
38
39
}
39
40
}
40
41
@@ -35,6 +35,7 @@ pub fn scheduled_outgoing(html: &str) -> Outgoing {35
images: Vec::new(),35
images: Vec::new(),36
files: Vec::new(),36
files: Vec::new(),37
link_preview: None,37
link_preview: None,38
importance: Default::default(),38
}39
}39
}40
}40
41
@@ -2,13 +2,13 @@ use std::collections::{HashMap, HashSet};
2
2
3
3
use app_ui_kit::widgets::Unread;
4
4
use chrono::{DateTime, FixedOffset, Utc};
5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};
5
use store::{ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id};
6
6
use teams_core::{ChatSection, is_event_preview};
7
7
8
8
use crate::app_state::chat_title;
9
9
use crate::data::{
10
10
Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,
11
unread_count,
11
unread_count, unread_importance_of,
12
12
};
13
13
use crate::format;
14
14
use crate::typing::{TypingState, preview_label};
@@ -59,6 +59,7 @@ pub struct ChatItem {
59
59
pub time_label: String,
60
60
pub preview: Preview,
61
61
pub unread: Unread,
62
pub importance: MessageImportance,
62
63
pub muted: bool,
63
64
pub is_group: bool,
64
65
pub member_count: usize,
@@ -205,6 +206,11 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<
205
206
.unwrap_or_default(),
206
207
preview,
207
208
unread,
209
importance: if chat.unread {
210
unread_importance_of(input.directory, chat)
211
} else {
212
MessageImportance::Normal
213
},
208
214
muted: chat.muted,
209
215
is_group: chat.kind == GROUP_KIND,
210
216
member_count: chat.members.len(),
@@ -1226,6 +1232,28 @@ mod tests {
1226
1232
assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);
1227
1233
}
1228
1234
1235
#[test]
1236
fn the_importance_marker_shows_only_while_the_chat_is_unread() {
1237
let chats = vec![chat("a", "group", true), chat("b", "group", false)];
1238
let mut directory = Directory::default();
1239
directory
1240
.unread_importance
1241
.insert("a".into(), MessageImportance::Urgent);
1242
directory
1243
.unread_importance
1244
.insert("b".into(), MessageImportance::High);
1245
let collapsed = HashSet::new();
1246
let context = input(&chats, &directory, &collapsed);
1247
assert_eq!(
1248
chat_item(&chats[0], &context, None).importance,
1249
MessageImportance::Urgent
1250
);
1251
assert_eq!(
1252
chat_item(&chats[1], &context, None).importance,
1253
MessageImportance::Normal
1254
);
1255
}
1256
1229
1257
#[test]
1230
1258
fn unread_is_a_count_when_known_else_a_dot() {
1231
1259
let chats = vec![
@@ -2,13 +2,13 @@ use std::collections::{HashMap, HashSet};2
2
3
use app_ui_kit::widgets::Unread;3
use app_ui_kit::widgets::Unread;4
use chrono::{DateTime, FixedOffset, Utc};4
use chrono::{DateTime, FixedOffset, Utc};5
use store::{ChannelRecord, ChatRecord, Sidebar, SidebarTeam, is_bot_id};5
use store::{ChannelRecord, ChatRecord, MessageImportance, Sidebar, SidebarTeam, is_bot_id};6
use teams_core::{ChatSection, is_event_preview};6
use teams_core::{ChatSection, is_event_preview};7
7
8
use crate::app_state::chat_title;8
use crate::app_state::chat_title;9
use crate::data::{9
use crate::data::{10
Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,10
Directory, FolderKind, Person, face_members, is_one_on_one, one_on_one_bot, others,11
unread_count,11
unread_count, unread_importance_of,12
};12
};13
use crate::format;13
use crate::format;14
use crate::typing::{TypingState, preview_label};14
use crate::typing::{TypingState, preview_label};@@ -59,6 +59,7 @@ pub struct ChatItem {59
pub time_label: String,59
pub time_label: String,60
pub preview: Preview,60
pub preview: Preview,61
pub unread: Unread,61
pub unread: Unread,62
pub importance: MessageImportance,62
pub muted: bool,63
pub muted: bool,63
pub is_group: bool,64
pub is_group: bool,64
pub member_count: usize,65
pub member_count: usize,@@ -205,6 +206,11 @@ pub fn chat_item(chat: &ChatRecord, input: &SectionInput<'_>, folder_id: Option<205
.unwrap_or_default(),206
.unwrap_or_default(),206
preview,207
preview,207
unread,208
unread,209
importance: if chat.unread {210
unread_importance_of(input.directory, chat)211
} else {212
MessageImportance::Normal213
},208
muted: chat.muted,214
muted: chat.muted,209
is_group: chat.kind == GROUP_KIND,215
is_group: chat.kind == GROUP_KIND,210
member_count: chat.members.len(),216
member_count: chat.members.len(),@@ -1226,6 +1232,28 @@ mod tests {1226
assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);1232
assert_eq!(sections[0].name, FAVORITES_FALLBACK_NAME);1227
}1233
}1228
1234
1235
#[test]1236
fn the_importance_marker_shows_only_while_the_chat_is_unread() {1237
let chats = vec![chat("a", "group", true), chat("b", "group", false)];1238
let mut directory = Directory::default();1239
directory1240
.unread_importance1241
.insert("a".into(), MessageImportance::Urgent);1242
directory1243
.unread_importance1244
.insert("b".into(), MessageImportance::High);1245
let collapsed = HashSet::new();1246
let context = input(&chats, &directory, &collapsed);1247
assert_eq!(1248
chat_item(&chats[0], &context, None).importance,1249
MessageImportance::Urgent1250
);1251
assert_eq!(1252
chat_item(&chats[1], &context, None).importance,1253
MessageImportance::Normal1254
);1255
}1256
1229
#[test]1257
#[test]1230
fn unread_is_a_count_when_known_else_a_dot() {1258
fn unread_is_a_count_when_known_else_a_dot() {1231
let chats = vec![1259
let chats = vec![@@ -2,7 +2,7 @@ use std::sync::Arc;
2
2
3
3
use gpui_kit::{Image, ImageFormat};
4
4
use serde::{Deserialize, Serialize};
5
use store::AttachmentImage;
5
use store::{AttachmentImage, MessageImportance};
6
6
use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};
7
7
8
8
use crate::remote_image::{RemoteImage, RemoteKind};
@@ -55,6 +55,8 @@ struct Payload {
55
55
files: Vec<OutgoingFile>,
56
56
objects: Vec<StoredObject>,
57
57
preview: Option<StoredPreview>,
58
#[serde(default)]
59
importance: Option<String>,
58
60
}
59
61
60
62
pub struct StoredOutgoing {
@@ -106,6 +108,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {
106
108
image_width: preview.image_width,
107
109
image_height: preview.image_height,
108
110
}),
111
importance: outgoing.importance.stored().map(str::to_owned),
109
112
})
110
113
.ok()?;
111
114
Some(StoredOutgoing { payload, images })
@@ -141,6 +144,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
141
144
files,
142
145
objects,
143
146
preview,
147
importance,
144
148
} = serde_json::from_str(payload).ok()?;
145
149
let mut inline = images.iter();
146
150
let images = objects
@@ -167,6 +171,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {
167
171
image_width: preview.image_width,
168
172
image_height: preview.image_height,
169
173
}),
174
importance: MessageImportance::from_stored(importance.as_deref()),
170
175
})
171
176
}
172
177
@@ -223,6 +228,7 @@ mod tests {
223
228
image_width: None,
224
229
image_height: None,
225
230
}),
231
importance: Default::default(),
226
232
}
227
233
}
228
234
@@ -243,6 +249,24 @@ mod tests {
243
249
assert_eq!(restored.edit, None);
244
250
}
245
251
252
#[test]
253
fn the_importance_survives_the_outbox_and_old_payloads_stay_standard() {
254
let original = Outgoing {
255
importance: MessageImportance::Urgent,
256
..outgoing()
257
};
258
let stored = encode(&original).unwrap();
259
let decoded = decode(&stored.payload, &stored.images).unwrap();
260
assert_eq!(decoded.importance, MessageImportance::Urgent);
261
assert_eq!(decoded.extras().importance, Some("urgent"));
262
let plain = encode(&outgoing()).unwrap();
263
assert!(!plain.payload.contains("importance\":\""));
264
assert_eq!(
265
decode(&plain.payload, &plain.images).unwrap().importance,
266
MessageImportance::Normal
267
);
268
}
269
246
270
#[test]
247
271
fn an_unreadable_payload_decodes_to_nothing() {
248
272
assert!(decode("not json", &[]).is_none());
@@ -2,7 +2,7 @@ use std::sync::Arc;2
2
3
use gpui_kit::{Image, ImageFormat};3
use gpui_kit::{Image, ImageFormat};4
use serde::{Deserialize, Serialize};4
use serde::{Deserialize, Serialize};5
use store::AttachmentImage;5
use store::{AttachmentImage, MessageImportance};6
use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};6
use teams_core::{Draft, DraftLine, LinkPreview, MentionInput};7
7
8
use crate::remote_image::{RemoteImage, RemoteKind};8
use crate::remote_image::{RemoteImage, RemoteKind};@@ -55,6 +55,8 @@ struct Payload {55
files: Vec<OutgoingFile>,55
files: Vec<OutgoingFile>,56
objects: Vec<StoredObject>,56
objects: Vec<StoredObject>,57
preview: Option<StoredPreview>,57
preview: Option<StoredPreview>,58
#[serde(default)]59
importance: Option<String>,58
}60
}59
61
60
pub struct StoredOutgoing {62
pub struct StoredOutgoing {@@ -106,6 +108,7 @@ pub fn encode(outgoing: &Outgoing) -> Option<StoredOutgoing> {106
image_width: preview.image_width,108
image_width: preview.image_width,107
image_height: preview.image_height,109
image_height: preview.image_height,108
}),110
}),111
importance: outgoing.importance.stored().map(str::to_owned),109
})112
})110
.ok()?;113
.ok()?;111
Some(StoredOutgoing { payload, images })114
Some(StoredOutgoing { payload, images })@@ -141,6 +144,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {141
files,144
files,142
objects,145
objects,143
preview,146
preview,147
importance,144
} = serde_json::from_str(payload).ok()?;148
} = serde_json::from_str(payload).ok()?;145
let mut inline = images.iter();149
let mut inline = images.iter();146
let images = objects150
let images = objects@@ -167,6 +171,7 @@ pub fn decode(payload: &str, images: &[AttachmentImage]) -> Option<Outgoing> {167
image_width: preview.image_width,171
image_width: preview.image_width,168
image_height: preview.image_height,172
image_height: preview.image_height,169
}),173
}),174
importance: MessageImportance::from_stored(importance.as_deref()),170
})175
})171
}176
}172
177
@@ -223,6 +228,7 @@ mod tests {223
image_width: None,228
image_width: None,224
image_height: None,229
image_height: None,225
}),230
}),231
importance: Default::default(),226
}232
}227
}233
}228
234
@@ -243,6 +249,24 @@ mod tests {243
assert_eq!(restored.edit, None);249
assert_eq!(restored.edit, None);244
}250
}245
251
252
#[test]253
fn the_importance_survives_the_outbox_and_old_payloads_stay_standard() {254
let original = Outgoing {255
importance: MessageImportance::Urgent,256
..outgoing()257
};258
let stored = encode(&original).unwrap();259
let decoded = decode(&stored.payload, &stored.images).unwrap();260
assert_eq!(decoded.importance, MessageImportance::Urgent);261
assert_eq!(decoded.extras().importance, Some("urgent"));262
let plain = encode(&outgoing()).unwrap();263
assert!(!plain.payload.contains("importance\":\""));264
assert_eq!(265
decode(&plain.payload, &plain.images).unwrap().importance,266
MessageImportance::Normal267
);268
}269
246
#[test]270
#[test]247
fn an_unreadable_payload_decodes_to_nothing() {271
fn an_unreadable_payload_decodes_to_nothing() {248
assert!(decode("not json", &[]).is_none());272
assert!(decode("not json", &[]).is_none());@@ -0,0 +1,100 @@
1
use std::collections::HashSet;
2
3
use chrono::{DateTime, Duration, Utc};
4
use gpui_kit::Context;
5
use store::{MessageImportance, MessageRecord};
6
7
use crate::app_state::AppState;
8
use crate::notify::urgent_repeat::{REPEAT_INTERVAL_MINUTES, REPEAT_WINDOW_MINUTES};
9
use crate::runtime;
10
11
const RECENT_MESSAGES: usize = 30;
12
13
/// Teams acknowledges an urgent message from someone else once it is shown; after the repeat window there is nothing left to stop.
14
pub fn urgent_to_ack(
15
records: &[MessageRecord],
16
my_user_id: &str,
17
now: DateTime<Utc>,
18
acked: &HashSet<String>,
19
) -> Vec<String> {
20
let oldest = now - Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES);
21
records
22
.iter()
23
.filter(|record| {
24
record.importance == MessageImportance::Urgent
25
&& !record.deleted
26
&& record.created_at >= oldest
27
&& record
28
.sender_id
29
.as_deref()
30
.is_some_and(|sender| sender != my_user_id)
31
&& !acked.contains(&record.message_id)
32
})
33
.map(|record| record.message_id.clone())
34
.collect()
35
}
36
37
impl AppState {
38
pub fn ack_urgent_messages(&mut self, chat_id: &str, _cx: &mut Context<Self>) {
39
if self.mode.demo || self.mode.read_only {
40
return;
41
}
42
let (Some(engine), Some(me)) = (self.engine.clone(), self.directory.me.as_ref()) else {
43
return;
44
};
45
let Ok(records) = self.store.messages(chat_id, None, RECENT_MESSAGES) else {
46
return;
47
};
48
let message_ids = urgent_to_ack(&records, &me.user_id, Utc::now(), &self.acked_urgent);
49
if message_ids.is_empty() {
50
return;
51
}
52
self.acked_urgent.extend(message_ids.iter().cloned());
53
let chat_id = chat_id.to_owned();
54
drop(runtime::spawn(async move {
55
for message_id in message_ids {
56
let _ = engine.ack_urgent_message(&chat_id, &message_id).await;
57
}
58
}));
59
}
60
}
61
62
#[cfg(test)]
63
mod tests {
64
use chrono::TimeZone;
65
66
use super::*;
67
68
fn now() -> DateTime<Utc> {
69
Utc.with_ymd_and_hms(2026, 10, 17, 9, 30, 0).unwrap()
70
}
71
72
fn record(
73
id: &str,
74
sender: &str,
75
minutes_ago: i64,
76
importance: MessageImportance,
77
) -> MessageRecord {
78
MessageRecord {
79
conversation_id: "chat".into(),
80
message_id: id.into(),
81
sender_id: Some(sender.into()),
82
created_at: now() - Duration::minutes(minutes_ago),
83
importance,
84
..Default::default()
85
}
86
}
87
88
#[test]
89
fn acks_recent_urgent_messages_from_others_once() {
90
let records = [
91
record("urgent", "lea", 3, MessageImportance::Urgent),
92
record("own", "me", 3, MessageImportance::Urgent),
93
record("important", "lea", 3, MessageImportance::High),
94
record("old", "lea", 40, MessageImportance::Urgent),
95
record("done", "lea", 1, MessageImportance::Urgent),
96
];
97
let acked = HashSet::from(["done".to_owned()]);
98
assert_eq!(urgent_to_ack(&records, "me", now(), &acked), ["urgent"]);
99
}
100
}
@@ -0,0 +1,100 @@1
use std::collections::HashSet;2
3
use chrono::{DateTime, Duration, Utc};4
use gpui_kit::Context;5
use store::{MessageImportance, MessageRecord};6
7
use crate::app_state::AppState;8
use crate::notify::urgent_repeat::{REPEAT_INTERVAL_MINUTES, REPEAT_WINDOW_MINUTES};9
use crate::runtime;10
11
const RECENT_MESSAGES: usize = 30;12
13
/// Teams acknowledges an urgent message from someone else once it is shown; after the repeat window there is nothing left to stop.14
pub fn urgent_to_ack(15
records: &[MessageRecord],16
my_user_id: &str,17
now: DateTime<Utc>,18
acked: &HashSet<String>,19
) -> Vec<String> {20
let oldest = now - Duration::minutes(REPEAT_WINDOW_MINUTES + REPEAT_INTERVAL_MINUTES);21
records22
.iter()23
.filter(|record| {24
record.importance == MessageImportance::Urgent25
&& !record.deleted26
&& record.created_at >= oldest27
&& record28
.sender_id29
.as_deref()30
.is_some_and(|sender| sender != my_user_id)31
&& !acked.contains(&record.message_id)32
})33
.map(|record| record.message_id.clone())34
.collect()35
}36
37
impl AppState {38
pub fn ack_urgent_messages(&mut self, chat_id: &str, _cx: &mut Context<Self>) {39
if self.mode.demo || self.mode.read_only {40
return;41
}42
let (Some(engine), Some(me)) = (self.engine.clone(), self.directory.me.as_ref()) else {43
return;44
};45
let Ok(records) = self.store.messages(chat_id, None, RECENT_MESSAGES) else {46
return;47
};48
let message_ids = urgent_to_ack(&records, &me.user_id, Utc::now(), &self.acked_urgent);49
if message_ids.is_empty() {50
return;51
}52
self.acked_urgent.extend(message_ids.iter().cloned());53
let chat_id = chat_id.to_owned();54
drop(runtime::spawn(async move {55
for message_id in message_ids {56
let _ = engine.ack_urgent_message(&chat_id, &message_id).await;57
}58
}));59
}60
}61
62
#[cfg(test)]63
mod tests {64
use chrono::TimeZone;65
66
use super::*;67
68
fn now() -> DateTime<Utc> {69
Utc.with_ymd_and_hms(2026, 10, 17, 9, 30, 0).unwrap()70
}71
72
fn record(73
id: &str,74
sender: &str,75
minutes_ago: i64,76
importance: MessageImportance,77
) -> MessageRecord {78
MessageRecord {79
conversation_id: "chat".into(),80
message_id: id.into(),81
sender_id: Some(sender.into()),82
created_at: now() - Duration::minutes(minutes_ago),83
importance,84
..Default::default()85
}86
}87
88
#[test]89
fn acks_recent_urgent_messages_from_others_once() {90
let records = [91
record("urgent", "lea", 3, MessageImportance::Urgent),92
record("own", "me", 3, MessageImportance::Urgent),93
record("important", "lea", 3, MessageImportance::High),94
record("old", "lea", 40, MessageImportance::Urgent),95
record("done", "lea", 1, MessageImportance::Urgent),96
];97
let acked = HashSet::from(["done".to_owned()]);98
assert_eq!(urgent_to_ack(&records, "me", now(), &acked), ["urgent"]);99
}100
}@@ -2,9 +2,13 @@ pub mod card_chart;
2
2
pub mod channel_tabs;
3
3
pub mod draft_style;
4
4
pub mod layout;
5
pub mod long_press;
5
6
pub mod reaction_proposal_pill;
6
7
pub mod render;
7
8
pub mod scroll_edge;
8
9
pub mod settings_controls;
9
10
pub mod spinner;
10
11
pub mod widgets;
12
13
#[cfg(test)]
14
mod touch_scroll;
@@ -2,9 +2,13 @@ pub mod card_chart;2
pub mod channel_tabs;2
pub mod channel_tabs;3
pub mod draft_style;3
pub mod draft_style;4
pub mod layout;4
pub mod layout;5
pub mod long_press;5
pub mod reaction_proposal_pill;6
pub mod reaction_proposal_pill;6
pub mod render;7
pub mod render;7
pub mod scroll_edge;8
pub mod scroll_edge;8
pub mod settings_controls;9
pub mod settings_controls;9
pub mod spinner;10
pub mod spinner;10
pub mod widgets;11
pub mod widgets;12
13
#[cfg(test)]14
mod touch_scroll;@@ -0,0 +1,40 @@
1
use gpui_kit::*;
2
3
pub fn long_press_right_click() -> impl IntoElement {
4
canvas(
5
|_, _, _| {},
6
|_, _, window, _| {
7
window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {
8
if phase != DispatchPhase::Bubble
9
|| event.phase != TouchPhase::Started
10
|| window.default_prevented()
11
{
12
return;
13
}
14
window.prevent_default();
15
let position = event.start_position;
16
window.defer(cx, move |window, cx| {
17
window.dispatch_event(
18
PlatformInput::MouseDown(MouseDownEvent {
19
button: MouseButton::Right,
20
position,
21
modifiers: Modifiers::default(),
22
click_count: 1,
23
first_mouse: false,
24
}),
25
cx,
26
);
27
window.dispatch_event(
28
PlatformInput::MouseUp(MouseUpEvent {
29
button: MouseButton::Right,
30
position,
31
modifiers: Modifiers::default(),
32
click_count: 1,
33
}),
34
cx,
35
);
36
});
37
});
38
},
39
)
40
}
@@ -0,0 +1,40 @@1
use gpui_kit::*;2
3
pub fn long_press_right_click() -> impl IntoElement {4
canvas(5
|_, _, _| {},6
|_, _, window, _| {7
window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {8
if phase != DispatchPhase::Bubble9
|| event.phase != TouchPhase::Started10
|| window.default_prevented()11
{12
return;13
}14
window.prevent_default();15
let position = event.start_position;16
window.defer(cx, move |window, cx| {17
window.dispatch_event(18
PlatformInput::MouseDown(MouseDownEvent {19
button: MouseButton::Right,20
position,21
modifiers: Modifiers::default(),22
click_count: 1,23
first_mouse: false,24
}),25
cx,26
);27
window.dispatch_event(28
PlatformInput::MouseUp(MouseUpEvent {29
button: MouseButton::Right,30
position,31
modifiers: Modifiers::default(),32
click_count: 1,33
}),34
cx,35
);36
});37
});38
},39
)40
}@@ -132,6 +132,7 @@ pub fn dropdown(id: &'static str, label: String, entries: Vec<MenuEntry>) -> imp
132
132
)
133
133
})
134
134
})
135
.listbox()
135
136
}
136
137
137
138
pub fn link_dropdown(
@@ -132,6 +132,7 @@ pub fn dropdown(id: &'static str, label: String, entries: Vec<MenuEntry>) -> imp132
)132
)133
})133
})134
})134
})135
.listbox()135
}136
}136
137
137
pub fn link_dropdown(138
pub fn link_dropdown(@@ -0,0 +1,223 @@
1
use std::cell::Cell;
2
use std::rc::Rc;
3
use std::time::Duration;
4
5
use crate::long_press::long_press_right_click;
6
use gpui_kit::{
7
Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,
8
ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,
9
TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,
10
px,
11
};
12
13
const ROW_HEIGHT: f32 = 40.;
14
const ROW_COUNT: usize = 60;
15
16
#[derive(Clone, Default)]
17
struct Clicks {
18
left: Rc<Cell<usize>>,
19
right: Rc<Cell<usize>>,
20
}
21
22
struct ScrollContainer {
23
scroll_handle: ScrollHandle,
24
clicks: Clicks,
25
}
26
27
impl Render for ScrollContainer {
28
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
29
let clicks = self.clicks.clone();
30
div().size_full().child(long_press_right_click()).child(
31
div()
32
.id("scroll-container")
33
.size_full()
34
.overflow_y_scroll()
35
.track_scroll(&self.scroll_handle)
36
.children((0..ROW_COUNT).map(|row_index| {
37
let left = clicks.left.clone();
38
let right = clicks.right.clone();
39
div()
40
.id(row_index)
41
.h(px(ROW_HEIGHT))
42
.flex_none()
43
.w_full()
44
.on_click(move |_, _, _| left.set(left.get() + 1))
45
.on_mouse_down(MouseButton::Right, move |_, _, _| {
46
right.set(right.get() + 1)
47
})
48
})),
49
)
50
}
51
}
52
53
struct VirtualList {
54
list_state: ListState,
55
}
56
57
impl Render for VirtualList {
58
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
59
list(self.list_state.clone(), |row_index, _, _| {
60
div()
61
.id(row_index)
62
.h(px(ROW_HEIGHT))
63
.flex_none()
64
.w_full()
65
.into_any_element()
66
})
67
.size_full()
68
}
69
}
70
71
struct Finger<'a> {
72
window_cx: &'a mut VisualTestContext,
73
touch_id: TouchId,
74
}
75
76
impl Finger<'_> {
77
fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {
78
self.window_cx.simulate_event(TouchEvent {
79
id: self.touch_id,
80
phase,
81
position: point(px(x), px(y)),
82
predicted_position: None,
83
force: None,
84
});
85
self.window_cx
86
.executor()
87
.advance_clock(Duration::from_millis(8));
88
}
89
90
fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {
91
self.touch(TouchPhase::Started, 100., from_y);
92
for step in 1..=steps {
93
let progress = step as f32 / steps as f32;
94
self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);
95
}
96
self.touch(TouchPhase::Ended, 100., to_y);
97
}
98
99
fn tap(&mut self, x: f32, y: f32) {
100
self.touch(TouchPhase::Started, x, y);
101
self.touch(TouchPhase::Ended, x, y);
102
self.window_cx
103
.executor()
104
.advance_clock(Duration::from_millis(500));
105
}
106
}
107
108
fn open_scroll_container(
109
cx: &mut TestAppContext,
110
) -> (ScrollHandle, Clicks, &mut VisualTestContext) {
111
cx.update(gpui_kit::init);
112
let scroll_handle = ScrollHandle::new();
113
let clicks = Clicks::default();
114
let (_, window_cx) = cx.add_window_view({
115
let scroll_handle = scroll_handle.clone();
116
let clicks = clicks.clone();
117
move |_, _| ScrollContainer {
118
scroll_handle,
119
clicks,
120
}
121
});
122
window_cx.update(|window, cx| window.draw(cx).clear(cx));
123
(scroll_handle, clicks, window_cx)
124
}
125
126
fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {
127
for _ in 0..frame_count {
128
window_cx
129
.executor()
130
.advance_clock(Duration::from_millis(16));
131
window_cx.update(|window, cx| {
132
window.simulate_next_frame(cx);
133
window.draw(cx).clear(cx);
134
});
135
}
136
}
137
138
#[gpui_kit::test]
139
fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {
140
let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
141
let mut finger = Finger {
142
window_cx,
143
touch_id: TouchId(1),
144
};
145
finger.pan(300., 180., 30);
146
let offset_y = f32::from(scroll_handle.offset().y);
147
assert!(
148
(-120.5..=-100.).contains(&offset_y),
149
"a 120 px slow pan scrolls about 120 px, got {offset_y}"
150
);
151
assert_eq!(clicks.left.get(), 0, "a pan never clicks");
152
}
153
154
#[gpui_kit::test]
155
fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {
156
let (scroll_handle, _, window_cx) = open_scroll_container(cx);
157
let mut finger = Finger {
158
window_cx,
159
touch_id: TouchId(1),
160
};
161
finger.pan(300., 100., 5);
162
let released_at = f32::from(scroll_handle.offset().y);
163
run_frames(finger.window_cx, 30);
164
let coasted_to = f32::from(scroll_handle.offset().y);
165
assert!(
166
coasted_to < released_at - 50.,
167
"momentum continues the scroll after release: {released_at} -> {coasted_to}"
168
);
169
}
170
171
#[gpui_kit::test]
172
fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {
173
let (_, clicks, window_cx) = open_scroll_container(cx);
174
let mut finger = Finger {
175
window_cx,
176
touch_id: TouchId(1),
177
};
178
finger.tap(100., 60.);
179
assert_eq!(clicks.left.get(), 1);
180
}
181
182
#[gpui_kit::test]
183
fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {
184
cx.update(gpui_kit::init);
185
let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));
186
let (_, window_cx) = cx.add_window_view({
187
let list_state = list_state.clone();
188
move |_, _| VirtualList { list_state }
189
});
190
window_cx.update(|window, cx| window.draw(cx).clear(cx));
191
let mut finger = Finger {
192
window_cx,
193
touch_id: TouchId(1),
194
};
195
finger.pan(300., 100., 30);
196
let scroll_top = list_state.logical_scroll_top();
197
let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);
198
assert!(
199
(180.0..=200.5).contains(&scrolled),
200
"a 200 px slow pan scrolls the list about 200 px, got {scrolled}"
201
);
202
}
203
204
#[gpui_kit::test]
205
fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {
206
let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
207
let mut finger = Finger {
208
window_cx,
209
touch_id: TouchId(1),
210
};
211
finger.touch(TouchPhase::Started, 100., 60.);
212
finger
213
.window_cx
214
.executor()
215
.advance_clock(Duration::from_millis(600));
216
finger.window_cx.run_until_parked();
217
finger.touch(TouchPhase::Moved, 100., 20.);
218
finger.touch(TouchPhase::Ended, 100., 20.);
219
finger.window_cx.run_until_parked();
220
assert_eq!(clicks.right.get(), 1);
221
assert_eq!(clicks.left.get(), 0);
222
assert_eq!(f32::from(scroll_handle.offset().y), 0.);
223
}
@@ -0,0 +1,223 @@1
use std::cell::Cell;2
use std::rc::Rc;3
use std::time::Duration;4
5
use crate::long_press::long_press_right_click;6
use gpui_kit::{7
Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,8
ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,9
TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,10
px,11
};12
13
const ROW_HEIGHT: f32 = 40.;14
const ROW_COUNT: usize = 60;15
16
#[derive(Clone, Default)]17
struct Clicks {18
left: Rc<Cell<usize>>,19
right: Rc<Cell<usize>>,20
}21
22
struct ScrollContainer {23
scroll_handle: ScrollHandle,24
clicks: Clicks,25
}26
27
impl Render for ScrollContainer {28
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {29
let clicks = self.clicks.clone();30
div().size_full().child(long_press_right_click()).child(31
div()32
.id("scroll-container")33
.size_full()34
.overflow_y_scroll()35
.track_scroll(&self.scroll_handle)36
.children((0..ROW_COUNT).map(|row_index| {37
let left = clicks.left.clone();38
let right = clicks.right.clone();39
div()40
.id(row_index)41
.h(px(ROW_HEIGHT))42
.flex_none()43
.w_full()44
.on_click(move |_, _, _| left.set(left.get() + 1))45
.on_mouse_down(MouseButton::Right, move |_, _, _| {46
right.set(right.get() + 1)47
})48
})),49
)50
}51
}52
53
struct VirtualList {54
list_state: ListState,55
}56
57
impl Render for VirtualList {58
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {59
list(self.list_state.clone(), |row_index, _, _| {60
div()61
.id(row_index)62
.h(px(ROW_HEIGHT))63
.flex_none()64
.w_full()65
.into_any_element()66
})67
.size_full()68
}69
}70
71
struct Finger<'a> {72
window_cx: &'a mut VisualTestContext,73
touch_id: TouchId,74
}75
76
impl Finger<'_> {77
fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {78
self.window_cx.simulate_event(TouchEvent {79
id: self.touch_id,80
phase,81
position: point(px(x), px(y)),82
predicted_position: None,83
force: None,84
});85
self.window_cx86
.executor()87
.advance_clock(Duration::from_millis(8));88
}89
90
fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {91
self.touch(TouchPhase::Started, 100., from_y);92
for step in 1..=steps {93
let progress = step as f32 / steps as f32;94
self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);95
}96
self.touch(TouchPhase::Ended, 100., to_y);97
}98
99
fn tap(&mut self, x: f32, y: f32) {100
self.touch(TouchPhase::Started, x, y);101
self.touch(TouchPhase::Ended, x, y);102
self.window_cx103
.executor()104
.advance_clock(Duration::from_millis(500));105
}106
}107
108
fn open_scroll_container(109
cx: &mut TestAppContext,110
) -> (ScrollHandle, Clicks, &mut VisualTestContext) {111
cx.update(gpui_kit::init);112
let scroll_handle = ScrollHandle::new();113
let clicks = Clicks::default();114
let (_, window_cx) = cx.add_window_view({115
let scroll_handle = scroll_handle.clone();116
let clicks = clicks.clone();117
move |_, _| ScrollContainer {118
scroll_handle,119
clicks,120
}121
});122
window_cx.update(|window, cx| window.draw(cx).clear(cx));123
(scroll_handle, clicks, window_cx)124
}125
126
fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {127
for _ in 0..frame_count {128
window_cx129
.executor()130
.advance_clock(Duration::from_millis(16));131
window_cx.update(|window, cx| {132
window.simulate_next_frame(cx);133
window.draw(cx).clear(cx);134
});135
}136
}137
138
#[gpui_kit::test]139
fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {140
let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);141
let mut finger = Finger {142
window_cx,143
touch_id: TouchId(1),144
};145
finger.pan(300., 180., 30);146
let offset_y = f32::from(scroll_handle.offset().y);147
assert!(148
(-120.5..=-100.).contains(&offset_y),149
"a 120 px slow pan scrolls about 120 px, got {offset_y}"150
);151
assert_eq!(clicks.left.get(), 0, "a pan never clicks");152
}153
154
#[gpui_kit::test]155
fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {156
let (scroll_handle, _, window_cx) = open_scroll_container(cx);157
let mut finger = Finger {158
window_cx,159
touch_id: TouchId(1),160
};161
finger.pan(300., 100., 5);162
let released_at = f32::from(scroll_handle.offset().y);163
run_frames(finger.window_cx, 30);164
let coasted_to = f32::from(scroll_handle.offset().y);165
assert!(166
coasted_to < released_at - 50.,167
"momentum continues the scroll after release: {released_at} -> {coasted_to}"168
);169
}170
171
#[gpui_kit::test]172
fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {173
let (_, clicks, window_cx) = open_scroll_container(cx);174
let mut finger = Finger {175
window_cx,176
touch_id: TouchId(1),177
};178
finger.tap(100., 60.);179
assert_eq!(clicks.left.get(), 1);180
}181
182
#[gpui_kit::test]183
fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {184
cx.update(gpui_kit::init);185
let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));186
let (_, window_cx) = cx.add_window_view({187
let list_state = list_state.clone();188
move |_, _| VirtualList { list_state }189
});190
window_cx.update(|window, cx| window.draw(cx).clear(cx));191
let mut finger = Finger {192
window_cx,193
touch_id: TouchId(1),194
};195
finger.pan(300., 100., 30);196
let scroll_top = list_state.logical_scroll_top();197
let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);198
assert!(199
(180.0..=200.5).contains(&scrolled),200
"a 200 px slow pan scrolls the list about 200 px, got {scrolled}"201
);202
}203
204
#[gpui_kit::test]205
fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {206
let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);207
let mut finger = Finger {208
window_cx,209
touch_id: TouchId(1),210
};211
finger.touch(TouchPhase::Started, 100., 60.);212
finger213
.window_cx214
.executor()215
.advance_clock(Duration::from_millis(600));216
finger.window_cx.run_until_parked();217
finger.touch(TouchPhase::Moved, 100., 20.);218
finger.touch(TouchPhase::Ended, 100., 20.);219
finger.window_cx.run_until_parked();220
assert_eq!(clicks.right.get(), 1);221
assert_eq!(clicks.left.get(), 0);222
assert_eq!(f32::from(scroll_handle.offset().y), 0.);223
}@@ -23,6 +23,10 @@ pub fn icon(name: IconName, size: f32, color: Hsla) -> Icon {
23
23
Icon::new(name).size(px(size)).text_color(color)
24
24
}
25
25
26
pub fn menu_icon(name: IconName) -> Icon {
27
Icon::new(name)
28
}
29
26
30
pub fn symbol(name: &str, size: f32, color: Hsla) -> Icon {
27
31
Icon::empty()
28
32
.path(format!("symbols/{name}.svg"))
@@ -44,27 +48,113 @@ pub fn corner_badge(corner: Corner, overhang: f32) -> Div {
44
48
}
45
49
}
46
50
47
pub fn count_badge(count: u32, muted: bool) -> Div {
48
let (background, foreground) = if muted {
49
(theme::badge_muted(), theme::text_strong())
50
} else {
51
(theme::accent(), theme::on_accent())
52
};
51
#[derive(Clone, Copy)]
52
pub struct BadgeMetrics {
53
pub height: f32,
54
pub padding_x: f32,
55
pub font_size: f32,
56
}
57
58
pub const COUNT_BADGE: BadgeMetrics = BadgeMetrics {
59
height: 18.,
60
padding_x: 5.,
61
font_size: 11.,
62
};
63
64
pub const RAIL_BADGE: BadgeMetrics = BadgeMetrics {
65
height: 16.,
66
padding_x: 4.,
67
font_size: 10.,
68
};
69
70
pub fn badge_selector(text: &str) -> String {
71
format!("count-badge/{text}")
72
}
73
74
pub fn badge_text_selector(text: &str) -> String {
75
format!("count-badge/{text}/text")
76
}
77
78
pub fn badge_pill(count: u32, metrics: BadgeMetrics, background: Hsla, foreground: Hsla) -> Div {
79
let text = format::badge_text(count);
53
80
div()
54
.min_w(px(18.))
55
.h(px(18.))
56
.px(px(5.))
81
.debug_selector(|| badge_selector(&text))
82
.min_w(px(metrics.height))
83
.h(px(metrics.height))
84
.px(px(metrics.padding_x))
57
85
.flex()
58
86
.flex_none()
59
87
.items_center()
60
88
.justify_center()
61
.rounded(px(9.))
89
.rounded(px(metrics.height / 2.))
62
90
.bg(background)
63
91
.text_color(foreground)
64
.text_size(px(11.))
65
.line_height(px(18.))
92
.text_size(px(metrics.font_size))
93
.line_height(px(metrics.height))
66
94
.font_weight(FontWeight::BOLD)
67
.child(format::badge_text(count))
95
.child(BadgeText {
96
text,
97
font_size: metrics.font_size,
98
line_height: metrics.height,
99
})
100
}
101
102
#[derive(IntoElement)]
103
struct BadgeText {
104
text: String,
105
font_size: f32,
106
line_height: f32,
107
}
108
109
impl RenderOnce for BadgeText {
110
fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {
111
let (shift_x, shift_y) = badge_ink_offset(window, &self.text, self.font_size);
112
div()
113
.debug_selector(|| badge_text_selector(&self.text))
114
.relative()
115
.left(px(-shift_x))
116
.top(px(-shift_y))
117
.flex_none()
118
.h(px(self.line_height))
119
.child(self.text)
120
}
121
}
122
123
pub fn badge_ink_offset(window: &Window, text: &str, font_size: f32) -> (f32, f32) {
124
let mut font = window.text_style().font();
125
font.weight = FontWeight::BOLD;
126
let text_system = window.text_system();
127
let font_id = text_system.resolve_font(&font);
128
let size = px(font_size);
129
let ascent = f32::from(text_system.ascent(font_id, size));
130
let descent = f32::from(text_system.descent(font_id, size)).abs();
131
let cap_height = f32::from(text_system.cap_height(font_id, size));
132
let shift_y = (ascent - descent - cap_height) / 2.;
133
let mut pen = 0.;
134
let mut ink_left = None;
135
let mut ink_right = 0.;
136
for character in text.chars() {
137
let advance = text_system
138
.advance(font_id, size, character)
139
.map_or(0., |advance| f32::from(advance.width));
140
if let Ok(bounds) = text_system.typographic_bounds(font_id, size, character) {
141
let left = pen + f32::from(bounds.origin.x);
142
ink_left.get_or_insert(left);
143
ink_right = left + f32::from(bounds.size.width);
144
}
145
pen += advance;
146
}
147
let shift_x = ink_left.map_or(0., |left| (left + ink_right) / 2. - pen / 2.);
148
(shift_x, shift_y)
149
}
150
151
pub fn count_badge(count: u32, muted: bool) -> Div {
152
let (background, foreground) = if muted {
153
(theme::badge_muted(), theme::text_strong())
154
} else {
155
(theme::accent(), theme::on_accent())
156
};
157
badge_pill(count, COUNT_BADGE, background, foreground)
68
158
}
69
159
70
160
pub fn page_header(title: &str) -> Div {
@@ -23,6 +23,10 @@ pub fn icon(name: IconName, size: f32, color: Hsla) -> Icon {23
Icon::new(name).size(px(size)).text_color(color)23
Icon::new(name).size(px(size)).text_color(color)24
}24
}25
25
26
pub fn menu_icon(name: IconName) -> Icon {27
Icon::new(name)28
}29
26
pub fn symbol(name: &str, size: f32, color: Hsla) -> Icon {30
pub fn symbol(name: &str, size: f32, color: Hsla) -> Icon {27
Icon::empty()31
Icon::empty()28
.path(format!("symbols/{name}.svg"))32
.path(format!("symbols/{name}.svg"))@@ -44,27 +48,113 @@ pub fn corner_badge(corner: Corner, overhang: f32) -> Div {44
}48
}45
}49
}46
50
47
pub fn count_badge(count: u32, muted: bool) -> Div {51
#[derive(Clone, Copy)]48
let (background, foreground) = if muted {52
pub struct BadgeMetrics {49
(theme::badge_muted(), theme::text_strong())53
pub height: f32,50
} else {54
pub padding_x: f32,51
(theme::accent(), theme::on_accent())55
pub font_size: f32,52
};56
}57
58
pub const COUNT_BADGE: BadgeMetrics = BadgeMetrics {59
height: 18.,60
padding_x: 5.,61
font_size: 11.,62
};63
64
pub const RAIL_BADGE: BadgeMetrics = BadgeMetrics {65
height: 16.,66
padding_x: 4.,67
font_size: 10.,68
};69
70
pub fn badge_selector(text: &str) -> String {71
format!("count-badge/{text}")72
}73
74
pub fn badge_text_selector(text: &str) -> String {75
format!("count-badge/{text}/text")76
}77
78
pub fn badge_pill(count: u32, metrics: BadgeMetrics, background: Hsla, foreground: Hsla) -> Div {79
let text = format::badge_text(count);53
div()80
div()54
.min_w(px(18.))81
.debug_selector(|| badge_selector(&text))55
.h(px(18.))82
.min_w(px(metrics.height))56
.px(px(5.))83
.h(px(metrics.height))84
.px(px(metrics.padding_x))57
.flex()85
.flex()58
.flex_none()86
.flex_none()59
.items_center()87
.items_center()60
.justify_center()88
.justify_center()61
.rounded(px(9.))89
.rounded(px(metrics.height / 2.))62
.bg(background)90
.bg(background)63
.text_color(foreground)91
.text_color(foreground)64
.text_size(px(11.))92
.text_size(px(metrics.font_size))65
.line_height(px(18.))93
.line_height(px(metrics.height))66
.font_weight(FontWeight::BOLD)94
.font_weight(FontWeight::BOLD)67
.child(format::badge_text(count))95
.child(BadgeText {96
text,97
font_size: metrics.font_size,98
line_height: metrics.height,99
})100
}101
102
#[derive(IntoElement)]103
struct BadgeText {104
text: String,105
font_size: f32,106
line_height: f32,107
}108
109
impl RenderOnce for BadgeText {110
fn render(self, window: &mut Window, _: &mut App) -> impl IntoElement {111
let (shift_x, shift_y) = badge_ink_offset(window, &self.text, self.font_size);112
div()113
.debug_selector(|| badge_text_selector(&self.text))114
.relative()115
.left(px(-shift_x))116
.top(px(-shift_y))117
.flex_none()118
.h(px(self.line_height))119
.child(self.text)120
}121
}122
123
pub fn badge_ink_offset(window: &Window, text: &str, font_size: f32) -> (f32, f32) {124
let mut font = window.text_style().font();125
font.weight = FontWeight::BOLD;126
let text_system = window.text_system();127
let font_id = text_system.resolve_font(&font);128
let size = px(font_size);129
let ascent = f32::from(text_system.ascent(font_id, size));130
let descent = f32::from(text_system.descent(font_id, size)).abs();131
let cap_height = f32::from(text_system.cap_height(font_id, size));132
let shift_y = (ascent - descent - cap_height) / 2.;133
let mut pen = 0.;134
let mut ink_left = None;135
let mut ink_right = 0.;136
for character in text.chars() {137
let advance = text_system138
.advance(font_id, size, character)139
.map_or(0., |advance| f32::from(advance.width));140
if let Ok(bounds) = text_system.typographic_bounds(font_id, size, character) {141
let left = pen + f32::from(bounds.origin.x);142
ink_left.get_or_insert(left);143
ink_right = left + f32::from(bounds.size.width);144
}145
pen += advance;146
}147
let shift_x = ink_left.map_or(0., |left| (left + ink_right) / 2. - pen / 2.);148
(shift_x, shift_y)149
}150
151
pub fn count_badge(count: u32, muted: bool) -> Div {152
let (background, foreground) = if muted {153
(theme::badge_muted(), theme::text_strong())154
} else {155
(theme::accent(), theme::on_accent())156
};157
badge_pill(count, COUNT_BADGE, background, foreground)68
}158
}69
159
70
pub fn page_header(title: &str) -> Div {160
pub fn page_header(title: &str) -> Div {@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M13.26 2.08a.5.5 0 1 0-.52.85C15 4.31 16.86 6.34 17 10.02a.5.5 0 0 0 1-.04c-.16-4.1-2.28-6.4-4.74-7.9ZM12.1 4.73a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 0 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm-7.01.7a5.16 5.16 0 0 0-2.61 6.82L3.69 15l.09 2.32c.02.53.57.87 1.05.65l9.73-4.33c.49-.21.6-.85.22-1.22L13.1 10.8 11.9 8.05a5.16 5.16 0 0 0-6.81-2.61Zm-1.7 6.41a4.16 4.16 0 0 1 7.6-3.38l1.3 2.92 1.54 1.5-9.06 4.03-.08-2.14-1.3-2.93Zm7.3 6.04c-.68.3-1.46.05-1.85-.54l2.68-1.2c.19.7-.16 1.44-.83 1.74Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M13.26 2.08a.5.5 0 1 0-.52.85C15 4.31 16.86 6.34 17 10.02a.5.5 0 0 0 1-.04c-.16-4.1-2.28-6.4-4.74-7.9ZM12.1 4.73a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 0 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm-7.01.7a5.16 5.16 0 0 0-2.61 6.82L3.69 15l.09 2.32c.02.53.57.87 1.05.65l9.73-4.33c.49-.21.6-.85.22-1.22L13.1 10.8 11.9 8.05a5.16 5.16 0 0 0-6.81-2.61Zm-1.7 6.41a4.16 4.16 0 0 1 7.6-3.38l1.3 2.92 1.54 1.5-9.06 4.03-.08-2.14-1.3-2.93Zm7.3 6.04c-.68.3-1.46.05-1.85-.54l2.68-1.2c.19.7-.16 1.44-.83 1.74Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M2.47 12.25a5.16 5.16 0 0 1 9.42-4.2l1.22 2.75 1.67 1.62c.38.37.27 1-.22 1.22l-9.73 4.33a.75.75 0 0 1-1.05-.65L3.68 15l-1.21-2.75Zm6.36 5.09a1.49 1.49 0 0 0 2.68-1.2l-2.68 1.2Zm3.26-12.61a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 1 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm.49-2.49a.5.5 0 0 1 .68-.16c2.46 1.5 4.58 3.8 4.74 7.9a.5.5 0 0 1-1 .04c-.14-3.68-2-5.7-4.26-7.09a.5.5 0 0 1-.16-.69Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M2.47 12.25a5.16 5.16 0 0 1 9.42-4.2l1.22 2.75 1.67 1.62c.38.37.27 1-.22 1.22l-9.73 4.33a.75.75 0 0 1-1.05-.65L3.68 15l-1.21-2.75Zm6.36 5.09a1.49 1.49 0 0 0 2.68-1.2l-2.68 1.2Zm3.26-12.61a.5.5 0 0 1 .69-.14 6.17 6.17 0 0 1 2.91 4.91.5.5 0 1 1-1 0c0-.13 0-.26-.02-.39a5.17 5.17 0 0 0-2.45-3.69.5.5 0 0 1-.13-.7Zm.49-2.49a.5.5 0 0 1 .68-.16c2.46 1.5 4.58 3.8 4.74 7.9a.5.5 0 0 1-1 .04c-.14-3.68-2-5.7-4.26-7.09a.5.5 0 0 1-.16-.69Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a8 8 0 1 1-3.61 15.14l-.12-.07-3.65.92a.5.5 0 0 1-.62-.45v-.08l.01-.08.92-3.64-.07-.12a7.95 7.95 0 0 1-.83-2.9l-.02-.37L2 10a8 8 0 0 1 8-8Zm0 1a7 7 0 0 0-6.1 10.42.5.5 0 0 1 .06.28l-.02.1-.75 3.01 3.02-.75a.5.5 0 0 1 .19-.01l.09.02.09.04A7 7 0 1 0 10 3Zm.5 8a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h3.09Zm2-3a.5.5 0 0 1 .09 1H7.5a.5.5 0 0 1-.09-1h5.09Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a2 2 0 0 0-2 2c0 2.07.75 4.91 1.18 6.4.1.36.44.6.82.6.39 0 .71-.24.82-.6C11.25 9.94 12 7.1 12 5a2 2 0 0 0-2-2ZM7 5a3 3 0 0 1 6 0c0 2.25-.79 5.21-1.22 6.69-.24.8-.97 1.31-1.78 1.31s-1.54-.52-1.78-1.31C7.8 10.2 7 7.23 7 5Zm3 10a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 3a2 2 0 0 0-2 2c0 2.07.75 4.91 1.18 6.4.1.36.44.6.82.6.39 0 .71-.24.82-.6C11.25 9.94 12 7.1 12 5a2 2 0 0 0-2-2ZM7 5a3 3 0 0 1 6 0c0 2.25-.79 5.21-1.22 6.69-.24.8-.97 1.31-1.78 1.31s-1.54-.52-1.78-1.31C7.8 10.2 7 7.23 7 5Zm3 10a1 1 0 1 0 0 2 1 1 0 0 0 0-2Zm-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 20 20"><path d="M10 2a3 3 0 0 0-3 3c0 2.23.79 5.2 1.22 6.69.24.79.97 1.31 1.78 1.31s1.54-.52 1.78-1.31C12.2 10.2 13 7.25 13 5a3 3 0 0 0-3-3Zm0 12a2 2 0 1 0 0 4 2 2 0 0 0 0-4Z"/></svg>@@ -171,11 +171,16 @@ mod frames {
171
171
use crate::app_state::{AppHandle, AppState, Mode, Selection};
172
172
use crate::call::{ActiveCall, CallModel, ConsultCall};
173
173
use crate::demo;
174
use crate::settings::select_selector;
174
175
use crate::settings::{item_selector, label, label_selector, metrics};
175
176
use crate::settings_section::SettingsSection;
176
177
use crate::user_activity::UserInput;
177
178
use crate::views::call_transcript::TranscriptPanel;
178
179
use crate::views::call_view::CHAT_PANEL_TAG;
180
use crate::views::composer::delivery::{
181
COMPOSER_DELIVERY_TAG, COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,
182
DELIVERY_MENU_TAG,
183
};
179
184
use crate::views::composer::{
180
185
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181
186
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
@@ -192,8 +197,9 @@ mod frames {
192
197
use crate::views::find_panel::{
193
198
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
194
199
};
195
use crate::views::message_row::BUBBLE_TAGS;
196
use crate::views::pin_banner::PIN_BANNER_TAG;
200
use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
201
use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
202
use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;
197
203
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
198
204
use crate::views::reaction_proposal_pill::REACTION_PILL;
199
205
use crate::views::recap_tab::RECAP_REGION;
@@ -205,10 +211,24 @@ mod frames {
205
211
OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
206
212
};
207
213
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
214
use crate::views::sidebar::chat_row_selector;
208
215
use crate::views::sidebar::chat_filter_bar::{
209
216
FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
210
217
};
211
218
use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
219
use crate::views::widgets::{
220
COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
221
count_badge,
222
};
223
use gpui_kit::MouseButton;
224
use gpui_kit::component::fluent::{
225
DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
226
OPTION_CHECK_INSET,
227
};
228
use gpui_kit::component::menu::selectors::{
229
ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
230
label_selector as menu_label_selector,
231
};
212
232
213
233
const GUARDED: &[&str] = &[
214
234
"shell",
@@ -276,6 +296,8 @@ mod frames {
276
296
const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";
277
297
const PROPOSAL_CHAT: &str = "demo-chat-release";
278
298
const REACTION_CHAT: &str = "demo-chat-mara";
299
const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
300
const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
279
301
const AGENT_TAGS: [&str; 4] = [
280
302
PROPOSAL_CARD,
281
303
PROPOSAL_THUMBNAILS,
@@ -585,6 +607,7 @@ mod frames {
585
607
.chain(SHARE_GUARDED)
586
608
.chain(CONSULT_GUARDED)
587
609
.chain([
610
&ACTIVITY_PROPOSALS_TAG,
588
611
&AGENTS_LIST,
589
612
&CALL_TRANSCRIPT,
590
613
&MENU,
@@ -1485,6 +1508,343 @@ mod frames {
1485
1508
}
1486
1509
}
1487
1510
1511
const MENU_ITEMS_SCANNED: usize = 40;
1512
const MENU_CHAT: &str = "demo-chat-release";
1513
const THEME_SELECT: &str = "settings-theme";
1514
1515
struct MenuRow {
1516
index: usize,
1517
item: Bounds<Pixels>,
1518
icon: Option<Bounds<Pixels>>,
1519
label: Option<Bounds<Pixels>>,
1520
}
1521
1522
fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1523
(0..MENU_ITEMS_SCANNED)
1524
.filter_map(|index| {
1525
let item =
1526
visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1527
Some(MenuRow {
1528
index,
1529
item,
1530
icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1531
label: visual
1532
.debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1533
})
1534
})
1535
.collect()
1536
}
1537
1538
fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1539
let mut found = Vec::new();
1540
for row in rows {
1541
let Some(icon) = row.icon else {
1542
continue;
1543
};
1544
let key = format!("{MENU}/item-{}", row.index);
1545
if let Some(label) = row.label {
1546
let gap = f32::from(label.left() - icon.right());
1547
if (gap - expected_gap).abs() > TOLERANCE {
1548
found.push((
1549
format!("{key}:icon-gap"),
1550
format!(
1551
"icon {} to label {} is {gap} px, expected {expected_gap}",
1552
describe(icon),
1553
describe(label)
1554
),
1555
));
1556
}
1557
}
1558
let offset = f32::from(icon.center().y - row.item.center().y);
1559
if offset.abs() > TOLERANCE {
1560
found.push((
1561
format!("{key}:icon-off-centre"),
1562
format!(
1563
"icon {} sits {offset} px off the centre of item {}",
1564
describe(icon),
1565
describe(row.item)
1566
),
1567
));
1568
}
1569
}
1570
found
1571
}
1572
1573
fn listbox_violations(
1574
trigger: Bounds<Pixels>,
1575
menu: Bounds<Pixels>,
1576
items: Bounds<Pixels>,
1577
rows: &[MenuRow],
1578
) -> Vec<(String, String)> {
1579
let mut found = Vec::new();
1580
let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1581
if !near(f32::from(menu.left() - trigger.left()), 0.) {
1582
found.push((
1583
format!("{MENU}:not-aligned-to-trigger"),
1584
format!(
1585
"list {} must start at the trigger's left edge {}",
1586
describe(menu),
1587
describe(trigger)
1588
),
1589
));
1590
}
1591
if !near(
1592
f32::from(menu.top() - trigger.bottom()),
1593
f32::from(DROPDOWN_OFFSET),
1594
) {
1595
found.push((
1596
format!("{MENU}:trigger-offset"),
1597
format!(
1598
"list {} must open {} px below the trigger {}",
1599
describe(menu),
1600
f32::from(DROPDOWN_OFFSET),
1601
describe(trigger)
1602
),
1603
));
1604
}
1605
if menu.size.width < trigger.size.width - px(TOLERANCE) {
1606
found.push((
1607
format!("{MENU}:narrower-than-trigger"),
1608
format!(
1609
"list {} is narrower than the trigger {}",
1610
describe(menu),
1611
describe(trigger)
1612
),
1613
));
1614
}
1615
if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1616
let top = f32::from(first.item.top() - items.top());
1617
let bottom = f32::from(items.bottom() - last.item.bottom());
1618
let padding = f32::from(MENU_LIST_PADDING);
1619
if !near(top, padding) || !near(bottom, padding) {
1620
found.push((
1621
format!("{MENU}:uneven-padding"),
1622
format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1623
));
1624
}
1625
let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1626
match first.icon {
1627
Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1628
check => found.push((
1629
format!("{MENU}:check-inset"),
1630
format!(
1631
"check column {check:?} must start {expected_inset} px inside the list {}",
1632
describe(menu)
1633
),
1634
)),
1635
}
1636
}
1637
found
1638
}
1639
1640
#[test]
1641
fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1642
let row =
1643
|index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1644
index,
1645
item: rectangle(4., item_top, 120., 32.),
1646
icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1647
label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1648
};
1649
let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1650
let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1651
.into_iter()
1652
.map(|(key, _)| key)
1653
.collect();
1654
assert_eq!(
1655
keys,
1656
[
1657
"popup-menu/item-1:icon-gap",
1658
"popup-menu/item-1:icon-off-centre"
1659
]
1660
);
1661
1662
let trigger = rectangle(100., 50., 216., 32.);
1663
let option = |index: usize, top: f32| MenuRow {
1664
index,
1665
item: rectangle(104., top, 208., 32.),
1666
icon: Some(rectangle(110., top + 8., 16., 16.)),
1667
label: Some(rectangle(132., top + 6., 80., 20.)),
1668
};
1669
let aligned = [option(0, 88.), option(1, 122.)];
1670
let menu = rectangle(100., 84., 216., 74.);
1671
assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1672
let shifted = rectangle(96., 90., 200., 80.);
1673
let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1674
.into_iter()
1675
.map(|(key, _)| key)
1676
.collect();
1677
assert_eq!(
1678
keys,
1679
[
1680
"popup-menu:not-aligned-to-trigger",
1681
"popup-menu:trigger-offset",
1682
"popup-menu:narrower-than-trigger",
1683
"popup-menu:uneven-padding",
1684
"popup-menu:check-inset",
1685
]
1686
);
1687
}
1688
1689
#[gpui_kit::test]
1690
fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1691
let (handle, _) = mount(cx);
1692
let mut visual = VisualTestContext::from_window(handle, cx);
1693
visual.simulate_resize(size(px(1280.), px(800.)));
1694
let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1695
collect(&mut visual, Some(chat_row));
1696
let mut found = Vec::new();
1697
let own_status = visual
1698
.debug_bounds(OWN_STATUS)
1699
.expect("own status button rendered");
1700
visual.simulate_click(own_status.center(), Default::default());
1701
collect(&mut visual, Some(MENU));
1702
let status_rows = menu_rows(&mut visual);
1703
assert!(
1704
status_rows.iter().any(|row| row.icon.is_some()),
1705
"status menu shows icons"
1706
);
1707
found.extend(menu_row_violations(
1708
&status_rows,
1709
f32::from(MENU_ICON_LABEL_GAP),
1710
));
1711
visual.simulate_keystrokes("escape");
1712
collect(&mut visual, None);
1713
let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1714
visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1715
visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1716
collect(&mut visual, Some(MENU));
1717
let chat_rows = menu_rows(&mut visual);
1718
assert!(
1719
chat_rows.iter().any(|row| row.icon.is_some()),
1720
"chat menu shows icons"
1721
);
1722
found.extend(menu_row_violations(
1723
&chat_rows,
1724
f32::from(MENU_ICON_LABEL_GAP),
1725
));
1726
let found: Vec<String> = found
1727
.into_iter()
1728
.map(|(key, message)| format!("{key}: {message}"))
1729
.collect();
1730
assert!(found.is_empty(), "{}", found.join("\n"));
1731
}
1732
1733
#[gpui_kit::test]
1734
fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1735
let (handle, state) = mount(cx);
1736
let mut visual = VisualTestContext::from_window(handle, cx);
1737
visual.simulate_resize(size(px(1280.), px(800.)));
1738
visual.update(|_, cx| {
1739
state.update(cx, |state, cx| {
1740
state.open_settings(SettingsSection::Appearance, cx)
1741
})
1742
});
1743
let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1744
collect(&mut visual, Some(select));
1745
let trigger = visual.debug_bounds(select).expect("theme select rendered");
1746
visual.simulate_click(trigger.center(), Default::default());
1747
collect(&mut visual, Some(MENU));
1748
let menu = visual.debug_bounds(MENU).expect("list rendered");
1749
let items = visual
1750
.debug_bounds(ITEMS_SELECTOR)
1751
.expect("list items rendered");
1752
let rows = menu_rows(&mut visual);
1753
let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1754
.into_iter()
1755
.chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1756
.map(|(key, message)| format!("{key}: {message}"))
1757
.collect();
1758
assert!(found.is_empty(), "{}", found.join("\n"));
1759
}
1760
1761
const BADGE_SAMPLES: [(u32, bool); 5] =
1762
[(1, false), (42, false), (120, false), (7, true), (15, true)];
1763
1764
struct BadgeSamples;
1765
1766
impl gpui_kit::Render for BadgeSamples {
1767
fn render(
1768
&mut self,
1769
_: &mut gpui_kit::Window,
1770
_: &mut gpui_kit::Context<Self>,
1771
) -> impl gpui_kit::IntoElement {
1772
use gpui_kit::{ParentElement as _, Styled as _};
1773
gpui_kit::div()
1774
.flex()
1775
.gap(px(12.))
1776
.p(px(12.))
1777
.children(BADGE_SAMPLES.map(|(count, rail)| {
1778
if rail {
1779
badge_pill(
1780
count,
1781
RAIL_BADGE,
1782
crate::theme::accent(),
1783
crate::theme::on_accent(),
1784
)
1785
} else {
1786
count_badge(count, false)
1787
}
1788
}))
1789
}
1790
}
1791
1792
fn badge_violation(
1793
text: &str,
1794
pill: Bounds<Pixels>,
1795
label: Bounds<Pixels>,
1796
ink_offset: (f32, f32),
1797
) -> Option<(String, String)> {
1798
let ink_x = f32::from(label.center().x) + ink_offset.0;
1799
let ink_y = f32::from(label.center().y) + ink_offset.1;
1800
let off_x = ink_x - f32::from(pill.center().x);
1801
let off_y = ink_y - f32::from(pill.center().y);
1802
(off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1803
(
1804
format!("count-badge/{text}:off-centre"),
1805
format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1806
)
1807
})
1808
}
1809
1810
#[test]
1811
fn badge_rule_flags_off_centre_text() {
1812
let pill = rectangle(0., 0., 18., 18.);
1813
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1814
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1815
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1816
}
1817
1818
#[gpui_kit::test]
1819
fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1820
cx.update(gpui_kit::init);
1821
cx.update(crate::theme::apply);
1822
let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1823
collect(visual, None);
1824
let mut found = Vec::new();
1825
for (count, rail) in BADGE_SAMPLES {
1826
let text = crate::format::badge_text(count);
1827
let pill = visual
1828
.debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1829
.expect("badge rendered");
1830
let label = visual
1831
.debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1832
.expect("badge text rendered");
1833
let font_size = if rail {
1834
RAIL_BADGE.font_size
1835
} else {
1836
COUNT_BADGE.font_size
1837
};
1838
let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1839
found.extend(badge_violation(&text, pill, label, offset));
1840
}
1841
let found: Vec<String> = found
1842
.into_iter()
1843
.map(|(key, message)| format!("{key}: {message}"))
1844
.collect();
1845
assert!(found.is_empty(), "{}", found.join("\n"));
1846
}
1847
1488
1848
const PINNED_CHAT: &str = "demo-chat-release";
1489
1849
const PINNED_CHANNEL: &str = "demo-channel-1-1";
1490
1850
@@ -1511,12 +1871,13 @@ mod frames {
1511
1871
("below divider", f32::from(banner.top() - divider.bottom())),
1512
1872
];
1513
1873
let side = gaps[1].1;
1514
if gaps
1515
.iter()
1516
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1874
if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1875
|| gaps
1876
.iter()
1877
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1517
1878
{
1518
1879
found.push(format!(
1519
"pin banner@{width}x{height}: gaps {gaps:?} must match"
1880
"pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1520
1881
));
1521
1882
}
1522
1883
}
@@ -1792,6 +2153,154 @@ mod frames {
1792
2153
}
1793
2154
}
1794
2155
2156
#[gpui_kit::test]
2157
fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {
2158
let (handle, _) = mount_with(cx, true);
2159
let mut visual = VisualTestContext::from_window(handle, cx);
2160
visual.dispatch_action(OpenActivity);
2161
for (width, height) in SIZES {
2162
visual.simulate_resize(size(px(width), px(height)));
2163
let window = Bounds {
2164
origin: point(px(0.), px(0.)),
2165
size: size(px(width), px(height)),
2166
};
2167
let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));
2168
let mut expected = GUARDED.to_vec();
2169
expected.push(ACTIVITY_PROPOSALS_TAG);
2170
let found: Vec<String> = violations(&tags, window, &expected)
2171
.into_iter()
2172
.map(|(key, message)| format!("{width}x{height}:{key}: {message}"))
2173
.collect();
2174
assert!(found.is_empty(), "{}", found.join("\n"));
2175
}
2176
}
2177
2178
#[gpui_kit::test]
2179
fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {
2180
const DELIVERY_TAGS: [&str; 5] = [
2181
COMPOSER_BOX_TAG,
2182
COMPOSER_LEADING_TAG,
2183
COMPOSER_DELIVERY_TAG,
2184
COMPOSER_IMPORTANCE_LABEL_TAG,
2185
COMPOSER_URGENT_BANNER_TAG,
2186
];
2187
const URGENT_OPTION: &str = "urgent-delivery-option";
2188
const BUTTON_ICON_INSET: f32 = 6.;
2189
let (handle, _) = mount(cx);
2190
let mut visual = VisualTestContext::from_window(handle, cx);
2191
for (width, height) in SIZES {
2192
visual.simulate_resize(size(px(width), px(height)));
2193
let window = Bounds {
2194
origin: point(px(0.), px(0.)),
2195
size: size(px(width), px(height)),
2196
};
2197
collect(&mut visual, Some(COMPOSER_DELIVERY_TAG));
2198
let button = visual
2199
.debug_bounds(COMPOSER_DELIVERY_TAG)
2200
.expect("delivery button");
2201
visual.simulate_click(button.center(), Default::default());
2202
collect(&mut visual, Some(URGENT_OPTION));
2203
let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");
2204
assert!(
2205
contains(window, menu),
2206
"menu {} leaves the window",
2207
describe(menu)
2208
);
2209
let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");
2210
visual.simulate_click(urgent.center(), Default::default());
2211
collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));
2212
assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());
2213
let tags: Vec<Tag> = DELIVERY_TAGS
2214
.iter()
2215
.filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
2216
.collect();
2217
let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)
2218
.into_iter()
2219
.map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))
2220
.collect();
2221
assert!(found.is_empty(), "{}", found.join("\n"));
2222
let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");
2223
let banner = visual
2224
.debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2225
.expect("banner");
2226
let label = visual
2227
.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)
2228
.expect("label");
2229
let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");
2230
assert!(
2231
(f32::from(banner.left() - composer.left())).abs() <= TOLERANCE
2232
&& (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,
2233
"banner {} not on the composer edges {}",
2234
describe(banner),
2235
describe(composer)
2236
);
2237
assert!(
2238
banner.bottom() <= composer.top(),
2239
"banner {} over the composer {}",
2240
describe(banner),
2241
describe(composer)
2242
);
2243
assert!(
2244
(inset(composer, label, Edge::Left)
2245
- inset(composer, leading, Edge::Left)
2246
- BUTTON_ICON_INSET)
2247
.abs()
2248
<= TOLERANCE,
2249
"label {} not on the icon edge of {}",
2250
describe(label),
2251
describe(leading)
2252
);
2253
let close = visual
2254
.debug_bounds(COMPOSER_URGENT_BANNER_TAG)
2255
.map(|banner| point(banner.right() - px(18.), banner.center().y))
2256
.expect("banner");
2257
visual.simulate_click(close, Default::default());
2258
collect(&mut visual, None);
2259
assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());
2260
assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());
2261
}
2262
}
2263
2264
#[gpui_kit::test]
2265
fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {
2266
let (handle, state) = mount_with(cx, true);
2267
let mut visual = VisualTestContext::from_window(handle, cx);
2268
for (width, height) in SIZES {
2269
visual.simulate_resize(size(px(width), px(height)));
2270
for chat in IMPORTANCE_CHATS {
2271
visual.update(|_, cx| {
2272
state.update(cx, |state, cx| {
2273
state.select(Selection::Chat(chat.to_owned()), cx)
2274
})
2275
});
2276
collect(&mut visual, Some(TIMELINE_TAG));
2277
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");
2278
visual.simulate_event(ScrollWheelEvent {
2279
position: timeline.center(),
2280
delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),
2281
..Default::default()
2282
});
2283
collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));
2284
let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");
2285
let bubble = BUBBLE_TAGS
2286
.iter()
2287
.filter_map(|tag| visual.debug_bounds(tag))
2288
.find(|bubble| contains(*bubble, label))
2289
.unwrap_or_else(|| {
2290
panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")
2291
});
2292
let left = inset(bubble, label, Edge::Left);
2293
let top = inset(bubble, label, Edge::Top);
2294
assert!(
2295
(left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2296
&& (top - bubble_padding_y(false)).abs() <= TOLERANCE,
2297
"{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2298
describe(bubble)
2299
);
2300
}
2301
}
2302
}
2303
1795
2304
#[gpui_kit::test]
1796
2305
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {
1797
2306
let (handle, state) = mount_with(cx, true);
@@ -171,11 +171,16 @@ mod frames {171
use crate::app_state::{AppHandle, AppState, Mode, Selection};171
use crate::app_state::{AppHandle, AppState, Mode, Selection};172
use crate::call::{ActiveCall, CallModel, ConsultCall};172
use crate::call::{ActiveCall, CallModel, ConsultCall};173
use crate::demo;173
use crate::demo;174
use crate::settings::select_selector;174
use crate::settings::{item_selector, label, label_selector, metrics};175
use crate::settings::{item_selector, label, label_selector, metrics};175
use crate::settings_section::SettingsSection;176
use crate::settings_section::SettingsSection;176
use crate::user_activity::UserInput;177
use crate::user_activity::UserInput;177
use crate::views::call_transcript::TranscriptPanel;178
use crate::views::call_transcript::TranscriptPanel;178
use crate::views::call_view::CHAT_PANEL_TAG;179
use crate::views::call_view::CHAT_PANEL_TAG;180
use crate::views::composer::delivery::{181
COMPOSER_DELIVERY_TAG, COMPOSER_IMPORTANCE_LABEL_TAG, COMPOSER_URGENT_BANNER_TAG,182
DELIVERY_MENU_TAG,183
};179
use crate::views::composer::{184
use crate::views::composer::{180
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,185
COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,181
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,186
COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,@@ -192,8 +197,9 @@ mod frames {192
use crate::views::find_panel::{197
use crate::views::find_panel::{193
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,198
FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,194
};199
};195
use crate::views::message_row::BUBBLE_TAGS;200
use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};196
use crate::views::pin_banner::PIN_BANNER_TAG;201
use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};202
use crate::views::activity_panel::ACTIVITY_PROPOSALS_TAG;197
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};203
use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};198
use crate::views::reaction_proposal_pill::REACTION_PILL;204
use crate::views::reaction_proposal_pill::REACTION_PILL;199
use crate::views::recap_tab::RECAP_REGION;205
use crate::views::recap_tab::RECAP_REGION;@@ -205,10 +211,24 @@ mod frames {205
OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,211
OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,206
};212
};207
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;213
use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;214
use crate::views::sidebar::chat_row_selector;208
use crate::views::sidebar::chat_filter_bar::{215
use crate::views::sidebar::chat_filter_bar::{209
FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,216
FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,210
};217
};211
use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};218
use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};219
use crate::views::widgets::{220
COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,221
count_badge,222
};223
use gpui_kit::MouseButton;224
use gpui_kit::component::fluent::{225
DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,226
OPTION_CHECK_INSET,227
};228
use gpui_kit::component::menu::selectors::{229
ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,230
label_selector as menu_label_selector,231
};212
232
213
const GUARDED: &[&str] = &[233
const GUARDED: &[&str] = &[214
"shell",234
"shell",@@ -276,6 +296,8 @@ mod frames {276
const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";296
const RECAP_MEETING_CHAT: &str = "demo-chat-meeting-standup";277
const PROPOSAL_CHAT: &str = "demo-chat-release";297
const PROPOSAL_CHAT: &str = "demo-chat-release";278
const REACTION_CHAT: &str = "demo-chat-mara";298
const REACTION_CHAT: &str = "demo-chat-mara";299
const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];300
const IMPORTANCE_LABEL_INSET_X: f32 = 12.;279
const AGENT_TAGS: [&str; 4] = [301
const AGENT_TAGS: [&str; 4] = [280
PROPOSAL_CARD,302
PROPOSAL_CARD,281
PROPOSAL_THUMBNAILS,303
PROPOSAL_THUMBNAILS,@@ -585,6 +607,7 @@ mod frames {585
.chain(SHARE_GUARDED)607
.chain(SHARE_GUARDED)586
.chain(CONSULT_GUARDED)608
.chain(CONSULT_GUARDED)587
.chain([609
.chain([610
&ACTIVITY_PROPOSALS_TAG,588
&AGENTS_LIST,611
&AGENTS_LIST,589
&CALL_TRANSCRIPT,612
&CALL_TRANSCRIPT,590
&MENU,613
&MENU,@@ -1485,6 +1508,343 @@ mod frames {1485
}1508
}1486
}1509
}1487
1510
1511
const MENU_ITEMS_SCANNED: usize = 40;1512
const MENU_CHAT: &str = "demo-chat-release";1513
const THEME_SELECT: &str = "settings-theme";1514
1515
struct MenuRow {1516
index: usize,1517
item: Bounds<Pixels>,1518
icon: Option<Bounds<Pixels>>,1519
label: Option<Bounds<Pixels>>,1520
}1521
1522
fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {1523
(0..MENU_ITEMS_SCANNED)1524
.filter_map(|index| {1525
let item =1526
visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;1527
Some(MenuRow {1528
index,1529
item,1530
icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),1531
label: visual1532
.debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),1533
})1534
})1535
.collect()1536
}1537
1538
fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {1539
let mut found = Vec::new();1540
for row in rows {1541
let Some(icon) = row.icon else {1542
continue;1543
};1544
let key = format!("{MENU}/item-{}", row.index);1545
if let Some(label) = row.label {1546
let gap = f32::from(label.left() - icon.right());1547
if (gap - expected_gap).abs() > TOLERANCE {1548
found.push((1549
format!("{key}:icon-gap"),1550
format!(1551
"icon {} to label {} is {gap} px, expected {expected_gap}",1552
describe(icon),1553
describe(label)1554
),1555
));1556
}1557
}1558
let offset = f32::from(icon.center().y - row.item.center().y);1559
if offset.abs() > TOLERANCE {1560
found.push((1561
format!("{key}:icon-off-centre"),1562
format!(1563
"icon {} sits {offset} px off the centre of item {}",1564
describe(icon),1565
describe(row.item)1566
),1567
));1568
}1569
}1570
found1571
}1572
1573
fn listbox_violations(1574
trigger: Bounds<Pixels>,1575
menu: Bounds<Pixels>,1576
items: Bounds<Pixels>,1577
rows: &[MenuRow],1578
) -> Vec<(String, String)> {1579
let mut found = Vec::new();1580
let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;1581
if !near(f32::from(menu.left() - trigger.left()), 0.) {1582
found.push((1583
format!("{MENU}:not-aligned-to-trigger"),1584
format!(1585
"list {} must start at the trigger's left edge {}",1586
describe(menu),1587
describe(trigger)1588
),1589
));1590
}1591
if !near(1592
f32::from(menu.top() - trigger.bottom()),1593
f32::from(DROPDOWN_OFFSET),1594
) {1595
found.push((1596
format!("{MENU}:trigger-offset"),1597
format!(1598
"list {} must open {} px below the trigger {}",1599
describe(menu),1600
f32::from(DROPDOWN_OFFSET),1601
describe(trigger)1602
),1603
));1604
}1605
if menu.size.width < trigger.size.width - px(TOLERANCE) {1606
found.push((1607
format!("{MENU}:narrower-than-trigger"),1608
format!(1609
"list {} is narrower than the trigger {}",1610
describe(menu),1611
describe(trigger)1612
),1613
));1614
}1615
if let (Some(first), Some(last)) = (rows.first(), rows.last()) {1616
let top = f32::from(first.item.top() - items.top());1617
let bottom = f32::from(items.bottom() - last.item.bottom());1618
let padding = f32::from(MENU_LIST_PADDING);1619
if !near(top, padding) || !near(bottom, padding) {1620
found.push((1621
format!("{MENU}:uneven-padding"),1622
format!("list padding top {top} / bottom {bottom}, both must be {padding}"),1623
));1624
}1625
let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);1626
match first.icon {1627
Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}1628
check => found.push((1629
format!("{MENU}:check-inset"),1630
format!(1631
"check column {check:?} must start {expected_inset} px inside the list {}",1632
describe(menu)1633
),1634
)),1635
}1636
}1637
found1638
}1639
1640
#[test]1641
fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {1642
let row =1643
|index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {1644
index,1645
item: rectangle(4., item_top, 120., 32.),1646
icon: Some(rectangle(icon_left, icon_top, 20., 20.)),1647
label: Some(rectangle(label_left, item_top + 6., 60., 20.)),1648
};1649
let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];1650
let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))1651
.into_iter()1652
.map(|(key, _)| key)1653
.collect();1654
assert_eq!(1655
keys,1656
[1657
"popup-menu/item-1:icon-gap",1658
"popup-menu/item-1:icon-off-centre"1659
]1660
);1661
1662
let trigger = rectangle(100., 50., 216., 32.);1663
let option = |index: usize, top: f32| MenuRow {1664
index,1665
item: rectangle(104., top, 208., 32.),1666
icon: Some(rectangle(110., top + 8., 16., 16.)),1667
label: Some(rectangle(132., top + 6., 80., 20.)),1668
};1669
let aligned = [option(0, 88.), option(1, 122.)];1670
let menu = rectangle(100., 84., 216., 74.);1671
assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());1672
let shifted = rectangle(96., 90., 200., 80.);1673
let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)1674
.into_iter()1675
.map(|(key, _)| key)1676
.collect();1677
assert_eq!(1678
keys,1679
[1680
"popup-menu:not-aligned-to-trigger",1681
"popup-menu:trigger-offset",1682
"popup-menu:narrower-than-trigger",1683
"popup-menu:uneven-padding",1684
"popup-menu:check-inset",1685
]1686
);1687
}1688
1689
#[gpui_kit::test]1690
fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {1691
let (handle, _) = mount(cx);1692
let mut visual = VisualTestContext::from_window(handle, cx);1693
visual.simulate_resize(size(px(1280.), px(800.)));1694
let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());1695
collect(&mut visual, Some(chat_row));1696
let mut found = Vec::new();1697
let own_status = visual1698
.debug_bounds(OWN_STATUS)1699
.expect("own status button rendered");1700
visual.simulate_click(own_status.center(), Default::default());1701
collect(&mut visual, Some(MENU));1702
let status_rows = menu_rows(&mut visual);1703
assert!(1704
status_rows.iter().any(|row| row.icon.is_some()),1705
"status menu shows icons"1706
);1707
found.extend(menu_row_violations(1708
&status_rows,1709
f32::from(MENU_ICON_LABEL_GAP),1710
));1711
visual.simulate_keystrokes("escape");1712
collect(&mut visual, None);1713
let row = visual.debug_bounds(chat_row).expect("chat row rendered");1714
visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());1715
visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());1716
collect(&mut visual, Some(MENU));1717
let chat_rows = menu_rows(&mut visual);1718
assert!(1719
chat_rows.iter().any(|row| row.icon.is_some()),1720
"chat menu shows icons"1721
);1722
found.extend(menu_row_violations(1723
&chat_rows,1724
f32::from(MENU_ICON_LABEL_GAP),1725
));1726
let found: Vec<String> = found1727
.into_iter()1728
.map(|(key, message)| format!("{key}: {message}"))1729
.collect();1730
assert!(found.is_empty(), "{}", found.join("\n"));1731
}1732
1733
#[gpui_kit::test]1734
fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {1735
let (handle, state) = mount(cx);1736
let mut visual = VisualTestContext::from_window(handle, cx);1737
visual.simulate_resize(size(px(1280.), px(800.)));1738
visual.update(|_, cx| {1739
state.update(cx, |state, cx| {1740
state.open_settings(SettingsSection::Appearance, cx)1741
})1742
});1743
let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());1744
collect(&mut visual, Some(select));1745
let trigger = visual.debug_bounds(select).expect("theme select rendered");1746
visual.simulate_click(trigger.center(), Default::default());1747
collect(&mut visual, Some(MENU));1748
let menu = visual.debug_bounds(MENU).expect("list rendered");1749
let items = visual1750
.debug_bounds(ITEMS_SELECTOR)1751
.expect("list items rendered");1752
let rows = menu_rows(&mut visual);1753
let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)1754
.into_iter()1755
.chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))1756
.map(|(key, message)| format!("{key}: {message}"))1757
.collect();1758
assert!(found.is_empty(), "{}", found.join("\n"));1759
}1760
1761
const BADGE_SAMPLES: [(u32, bool); 5] =1762
[(1, false), (42, false), (120, false), (7, true), (15, true)];1763
1764
struct BadgeSamples;1765
1766
impl gpui_kit::Render for BadgeSamples {1767
fn render(1768
&mut self,1769
_: &mut gpui_kit::Window,1770
_: &mut gpui_kit::Context<Self>,1771
) -> impl gpui_kit::IntoElement {1772
use gpui_kit::{ParentElement as _, Styled as _};1773
gpui_kit::div()1774
.flex()1775
.gap(px(12.))1776
.p(px(12.))1777
.children(BADGE_SAMPLES.map(|(count, rail)| {1778
if rail {1779
badge_pill(1780
count,1781
RAIL_BADGE,1782
crate::theme::accent(),1783
crate::theme::on_accent(),1784
)1785
} else {1786
count_badge(count, false)1787
}1788
}))1789
}1790
}1791
1792
fn badge_violation(1793
text: &str,1794
pill: Bounds<Pixels>,1795
label: Bounds<Pixels>,1796
ink_offset: (f32, f32),1797
) -> Option<(String, String)> {1798
let ink_x = f32::from(label.center().x) + ink_offset.0;1799
let ink_y = f32::from(label.center().y) + ink_offset.1;1800
let off_x = ink_x - f32::from(pill.center().x);1801
let off_y = ink_y - f32::from(pill.center().y);1802
(off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {1803
(1804
format!("count-badge/{text}:off-centre"),1805
format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),1806
)1807
})1808
}1809
1810
#[test]1811
fn badge_rule_flags_off_centre_text() {1812
let pill = rectangle(0., 0., 18., 18.);1813
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());1814
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());1815
assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());1816
}1817
1818
#[gpui_kit::test]1819
fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {1820
cx.update(gpui_kit::init);1821
cx.update(crate::theme::apply);1822
let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);1823
collect(visual, None);1824
let mut found = Vec::new();1825
for (count, rail) in BADGE_SAMPLES {1826
let text = crate::format::badge_text(count);1827
let pill = visual1828
.debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))1829
.expect("badge rendered");1830
let label = visual1831
.debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))1832
.expect("badge text rendered");1833
let font_size = if rail {1834
RAIL_BADGE.font_size1835
} else {1836
COUNT_BADGE.font_size1837
};1838
let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));1839
found.extend(badge_violation(&text, pill, label, offset));1840
}1841
let found: Vec<String> = found1842
.into_iter()1843
.map(|(key, message)| format!("{key}: {message}"))1844
.collect();1845
assert!(found.is_empty(), "{}", found.join("\n"));1846
}1847
1488
const PINNED_CHAT: &str = "demo-chat-release";1848
const PINNED_CHAT: &str = "demo-chat-release";1489
const PINNED_CHANNEL: &str = "demo-channel-1-1";1849
const PINNED_CHANNEL: &str = "demo-channel-1-1";1490
1850
@@ -1511,12 +1871,13 @@ mod frames {1511
("below divider", f32::from(banner.top() - divider.bottom())),1871
("below divider", f32::from(banner.top() - divider.bottom())),1512
];1872
];1513
let side = gaps[1].1;1873
let side = gaps[1].1;1514
if gaps1874
if (side - BANNER_INSET).abs() > INSET_TOLERANCE1515
.iter()1875
|| gaps1516
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)1876
.iter()1877
.any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)1517
{1878
{1518
found.push(format!(1879
found.push(format!(1519
"pin banner@{width}x{height}: gaps {gaps:?} must match"1880
"pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"1520
));1881
));1521
}1882
}1522
}1883
}@@ -1792,6 +2153,154 @@ mod frames {1792
}2153
}1793
}2154
}1794
2155
2156
#[gpui_kit::test]2157
fn agent_proposals_in_activity_stay_inside_the_sidebar(cx: &mut TestAppContext) {2158
let (handle, _) = mount_with(cx, true);2159
let mut visual = VisualTestContext::from_window(handle, cx);2160
visual.dispatch_action(OpenActivity);2161
for (width, height) in SIZES {2162
visual.simulate_resize(size(px(width), px(height)));2163
let window = Bounds {2164
origin: point(px(0.), px(0.)),2165
size: size(px(width), px(height)),2166
};2167
let tags = collect(&mut visual, Some(ACTIVITY_PROPOSALS_TAG));2168
let mut expected = GUARDED.to_vec();2169
expected.push(ACTIVITY_PROPOSALS_TAG);2170
let found: Vec<String> = violations(&tags, window, &expected)2171
.into_iter()2172
.map(|(key, message)| format!("{width}x{height}:{key}: {message}"))2173
.collect();2174
assert!(found.is_empty(), "{}", found.join("\n"));2175
}2176
}2177
2178
#[gpui_kit::test]2179
fn delivery_options_label_and_banner_line_up_with_the_composer(cx: &mut TestAppContext) {2180
const DELIVERY_TAGS: [&str; 5] = [2181
COMPOSER_BOX_TAG,2182
COMPOSER_LEADING_TAG,2183
COMPOSER_DELIVERY_TAG,2184
COMPOSER_IMPORTANCE_LABEL_TAG,2185
COMPOSER_URGENT_BANNER_TAG,2186
];2187
const URGENT_OPTION: &str = "urgent-delivery-option";2188
const BUTTON_ICON_INSET: f32 = 6.;2189
let (handle, _) = mount(cx);2190
let mut visual = VisualTestContext::from_window(handle, cx);2191
for (width, height) in SIZES {2192
visual.simulate_resize(size(px(width), px(height)));2193
let window = Bounds {2194
origin: point(px(0.), px(0.)),2195
size: size(px(width), px(height)),2196
};2197
collect(&mut visual, Some(COMPOSER_DELIVERY_TAG));2198
let button = visual2199
.debug_bounds(COMPOSER_DELIVERY_TAG)2200
.expect("delivery button");2201
visual.simulate_click(button.center(), Default::default());2202
collect(&mut visual, Some(URGENT_OPTION));2203
let menu = visual.debug_bounds(DELIVERY_MENU_TAG).expect("menu");2204
assert!(2205
contains(window, menu),2206
"menu {} leaves the window",2207
describe(menu)2208
);2209
let urgent = visual.debug_bounds(URGENT_OPTION).expect("urgent option");2210
visual.simulate_click(urgent.center(), Default::default());2211
collect(&mut visual, Some(COMPOSER_URGENT_BANNER_TAG));2212
assert!(visual.debug_bounds(DELIVERY_MENU_TAG).is_none());2213
let tags: Vec<Tag> = DELIVERY_TAGS2214
.iter()2215
.filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))2216
.collect();2217
let found: Vec<String> = violations(&tags, window, &DELIVERY_TAGS)2218
.into_iter()2219
.map(|(key, message)| format!("delivery@{width}x{height}:{key}: {message}"))2220
.collect();2221
assert!(found.is_empty(), "{}", found.join("\n"));2222
let composer = visual.debug_bounds(COMPOSER_BOX_TAG).expect("composer");2223
let banner = visual2224
.debug_bounds(COMPOSER_URGENT_BANNER_TAG)2225
.expect("banner");2226
let label = visual2227
.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG)2228
.expect("label");2229
let leading = visual.debug_bounds(COMPOSER_LEADING_TAG).expect("leading");2230
assert!(2231
(f32::from(banner.left() - composer.left())).abs() <= TOLERANCE2232
&& (f32::from(banner.right() - composer.right())).abs() <= TOLERANCE,2233
"banner {} not on the composer edges {}",2234
describe(banner),2235
describe(composer)2236
);2237
assert!(2238
banner.bottom() <= composer.top(),2239
"banner {} over the composer {}",2240
describe(banner),2241
describe(composer)2242
);2243
assert!(2244
(inset(composer, label, Edge::Left)2245
- inset(composer, leading, Edge::Left)2246
- BUTTON_ICON_INSET)2247
.abs()2248
<= TOLERANCE,2249
"label {} not on the icon edge of {}",2250
describe(label),2251
describe(leading)2252
);2253
let close = visual2254
.debug_bounds(COMPOSER_URGENT_BANNER_TAG)2255
.map(|banner| point(banner.right() - px(18.), banner.center().y))2256
.expect("banner");2257
visual.simulate_click(close, Default::default());2258
collect(&mut visual, None);2259
assert!(visual.debug_bounds(COMPOSER_URGENT_BANNER_TAG).is_none());2260
assert!(visual.debug_bounds(COMPOSER_IMPORTANCE_LABEL_TAG).is_none());2261
}2262
}2263
2264
#[gpui_kit::test]2265
fn importance_label_sits_inside_its_bubble_on_the_text_edge(cx: &mut TestAppContext) {2266
let (handle, state) = mount_with(cx, true);2267
let mut visual = VisualTestContext::from_window(handle, cx);2268
for (width, height) in SIZES {2269
visual.simulate_resize(size(px(width), px(height)));2270
for chat in IMPORTANCE_CHATS {2271
visual.update(|_, cx| {2272
state.update(cx, |state, cx| {2273
state.select(Selection::Chat(chat.to_owned()), cx)2274
})2275
});2276
collect(&mut visual, Some(TIMELINE_TAG));2277
let timeline = visual.debug_bounds(TIMELINE_TAG).expect("timeline");2278
visual.simulate_event(ScrollWheelEvent {2279
position: timeline.center(),2280
delta: ScrollDelta::Pixels(point(px(0.), px(-100_000.))),2281
..Default::default()2282
});2283
collect(&mut visual, Some(IMPORTANCE_LABEL_TAG));2284
let label = visual.debug_bounds(IMPORTANCE_LABEL_TAG).expect("label");2285
let bubble = BUBBLE_TAGS2286
.iter()2287
.filter_map(|tag| visual.debug_bounds(tag))2288
.find(|bubble| contains(*bubble, label))2289
.unwrap_or_else(|| {2290
panic!("{chat}@{width}x{height}: label {label:?} outside every bubble")2291
});2292
let left = inset(bubble, label, Edge::Left);2293
let top = inset(bubble, label, Edge::Top);2294
assert!(2295
(left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE2296
&& (top - bubble_padding_y(false)).abs() <= TOLERANCE,2297
"{chat}@{width}x{height}: label inset left {left} top {top} in {}",2298
describe(bubble)2299
);2300
}2301
}2302
}2303
1795
#[gpui_kit::test]2304
#[gpui_kit::test]1796
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {2305
fn agent_proposals_stay_inside_the_main_island(cx: &mut TestAppContext) {1797
let (handle, state) = mount_with(cx, true);2306
let (handle, state) = mount_with(cx, true);@@ -5,7 +5,7 @@ use gpui_kit::*;
5
5
6
6
use super::center::NotificationCenter;
7
7
use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
8
use super::stack::AgentToast;
8
use super::stack::{AgentToast, AgentToastKind};
9
9
use crate::theme;
10
10
use crate::views::widgets::{icon, symbol};
11
11
@@ -45,12 +45,16 @@ pub(super) fn agent_toast_content(
45
45
) -> Div {
46
46
let (open_chat_center, follow_up_center, close_center) =
47
47
(center.clone(), center.clone(), center.clone());
48
let follow_up_label = if agent.failed {
49
"Retry"
50
} else {
51
"Open session"
48
let follow_up_label = match agent.kind {
49
AgentToastKind::Run { failed: true, .. } => Some("Retry"),
50
AgentToastKind::Run { .. } => Some("Open session"),
51
AgentToastKind::Proposal { .. } => None,
52
};
53
let open_label = match agent.kind {
54
AgentToastKind::Run { .. } => "Open chat",
55
AgentToastKind::Proposal { .. } => "Review",
52
56
};
53
let tint = if agent.failed {
57
let tint = if agent.failed() {
54
58
theme::red_soft()
55
59
} else {
56
60
theme::accent_text()
@@ -118,20 +122,18 @@ pub(super) fn agent_toast_content(
118
122
.child(
119
123
h_flex()
120
124
.gap(px(6.))
121
.child(button("agent-toast-open-chat", "Open chat", true).on_click(
125
.child(button("agent-toast-open-chat", open_label, true).on_click(
122
126
move |_, _, cx| {
123
127
cx.stop_propagation();
124
128
open_chat_center.update(cx, |center, cx| center.activate(id, cx));
125
129
},
126
130
))
127
.child(
128
button("agent-toast-follow-up", follow_up_label, false).on_click(
129
move |_, _, cx| {
130
cx.stop_propagation();
131
follow_up_center
132
.update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
133
},
134
),
135
),
131
.children(follow_up_label.map(|label| {
132
button("agent-toast-follow-up", label, false).on_click(move |_, _, cx| {
133
cx.stop_propagation();
134
follow_up_center
135
.update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
136
})
137
})),
136
138
)
137
139
}
@@ -5,7 +5,7 @@ use gpui_kit::*;5
5
6
use super::center::NotificationCenter;6
use super::center::NotificationCenter;7
use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};7
use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};8
use super::stack::AgentToast;8
use super::stack::{AgentToast, AgentToastKind};9
use crate::theme;9
use crate::theme;10
use crate::views::widgets::{icon, symbol};10
use crate::views::widgets::{icon, symbol};11
11
@@ -45,12 +45,16 @@ pub(super) fn agent_toast_content(45
) -> Div {45
) -> Div {46
let (open_chat_center, follow_up_center, close_center) =46
let (open_chat_center, follow_up_center, close_center) =47
(center.clone(), center.clone(), center.clone());47
(center.clone(), center.clone(), center.clone());48
let follow_up_label = if agent.failed {48
let follow_up_label = match agent.kind {49
"Retry"49
AgentToastKind::Run { failed: true, .. } => Some("Retry"),50
} else {50
AgentToastKind::Run { .. } => Some("Open session"),51
"Open session"51
AgentToastKind::Proposal { .. } => None,52
};53
let open_label = match agent.kind {54
AgentToastKind::Run { .. } => "Open chat",55
AgentToastKind::Proposal { .. } => "Review",52
};56
};53
let tint = if agent.failed {57
let tint = if agent.failed() {54
theme::red_soft()58
theme::red_soft()55
} else {59
} else {56
theme::accent_text()60
theme::accent_text()@@ -118,20 +122,18 @@ pub(super) fn agent_toast_content(118
.child(122
.child(119
h_flex()123
h_flex()120
.gap(px(6.))124
.gap(px(6.))121
.child(button("agent-toast-open-chat", "Open chat", true).on_click(125
.child(button("agent-toast-open-chat", open_label, true).on_click(122
move |_, _, cx| {126
move |_, _, cx| {123
cx.stop_propagation();127
cx.stop_propagation();124
open_chat_center.update(cx, |center, cx| center.activate(id, cx));128
open_chat_center.update(cx, |center, cx| center.activate(id, cx));125
},129
},126
))130
))127
.child(131
.children(follow_up_label.map(|label| {128
button("agent-toast-follow-up", follow_up_label, false).on_click(132
button("agent-toast-follow-up", label, false).on_click(move |_, _, cx| {129
move |_, _, cx| {133
cx.stop_propagation();130
cx.stop_propagation();134
follow_up_center131
follow_up_center135
.update(cx, |center, cx| center.agent_toast_follow_up(id, cx));132
.update(cx, |center, cx| center.agent_toast_follow_up(id, cx));136
})133
},137
})),134
),135
),136
)138
)137
}139
}@@ -1,7 +1,7 @@
1
1
use std::collections::{HashMap, HashSet};
2
2
use std::time::{Duration, Instant};
3
3
4
use chrono::Utc;
4
use chrono::{DateTime, Utc};
5
5
use gpui_kit::*;
6
6
use store::Sidebar;
7
7
@@ -12,20 +12,24 @@ use super::meeting_view::MeetingToastView;
12
12
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13
13
use super::ring_view::RingView;
14
14
use super::rules::{
15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16
meeting_start_sound, ringtone_for, should_flash, should_ringback,
15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,
16
decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,
17
shows_preview,
17
18
};
18
19
use super::settings;
19
20
use super::sound_cache::{self, SoundHandle};
20
21
use super::sounds::{CallTone, Ringtone};
21
22
use super::stack::{
22
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
23
AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,
24
ToastModel, ToastStack,
23
25
};
24
26
use super::taskbar::taskbar_badge_count;
25
27
use super::text::describe;
26
28
use super::toast::{PillView, ToastView};
29
use super::urgent_repeat::UrgentRepeats;
27
30
use crate::active_appearance::{self, ActiveAppearance};
28
31
use crate::activity::ActivityCenter;
32
use crate::agent_api::{self, pending::PendingProposal};
29
33
use crate::agents::{AgentRun, AgentRunsEvent, RunState};
30
34
use crate::app_state::{AppEvent, AppState, selection_for};
31
35
use crate::appearance::AppIcon;
@@ -76,6 +80,7 @@ pub struct NotificationCenter {
76
80
stack: ToastStack,
77
81
tracker: IncomingTracker,
78
82
throttle: SoundThrottle,
83
urgent_repeats: UrgentRepeats,
79
84
windows: HashMap<u64, OpenWindow>,
80
85
opening: HashSet<u64>,
81
86
call_windows: HashMap<CallToast, OpenWindow>,
@@ -97,6 +102,9 @@ pub struct NotificationCenter {
97
102
_activity_observation: Subscription,
98
103
_appearance_observation: Subscription,
99
104
_agent_subscription: Option<Subscription>,
105
started_at: DateTime<Utc>,
106
known_proposals: HashSet<String>,
107
_proposal_observation: Option<Subscription>,
100
108
}
101
109
102
110
impl NotificationCenter {
@@ -106,7 +114,8 @@ impl NotificationCenter {
106
114
window: &mut Window,
107
115
cx: &mut Context<Self>,
108
116
) -> Self {
109
let settings = settings::load(&app.read(cx).store);
117
let mut settings = settings::load(&app.read(cx).store);
118
settings.account = app.read(cx).account_chat_settings().notifications;
110
119
let app_icon = active_appearance::current(cx).app_icon;
111
120
let tray = if app.read(cx).mode.demo {
112
121
None
@@ -134,13 +143,19 @@ impl NotificationCenter {
134
143
}
135
144
})
136
145
});
146
let proposal_observation =
147
agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));
137
148
let center = NotificationCenter {
149
started_at: Utc::now(),
150
known_proposals: HashSet::new(),
151
_proposal_observation: proposal_observation,
138
152
main_window: window.window_handle(),
139
153
main_native: platform::native_handle(window),
140
154
settings,
141
155
stack: ToastStack::default(),
142
156
tracker: IncomingTracker::new(Utc::now()),
143
157
throttle: SoundThrottle::default(),
158
urgent_repeats: UrgentRepeats::default(),
144
159
windows: HashMap::new(),
145
160
opening: HashSet::new(),
146
161
call_windows: HashMap::new(),
@@ -272,13 +287,19 @@ impl NotificationCenter {
272
287
self.sync_tray();
273
288
if self.settings.sounds != previous {
274
289
let updated = self.settings.sounds.clone();
275
self.app
276
.update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
290
self.app.update(cx, |state, cx| {
291
state.save_sound_settings(previous, updated, cx)
292
});
277
293
self.prefetch_sounds(cx);
278
294
}
279
295
cx.notify();
280
296
}
281
297
298
fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
299
self.settings.account = self.app.read(cx).account_chat_settings().notifications;
300
cx.notify();
301
}
302
282
303
fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
283
304
let Some(account) = self.app.read(cx).account_sounds.clone() else {
284
305
return;
@@ -317,6 +338,11 @@ impl NotificationCenter {
317
338
sound_cache::play_or(file_name, platform::play_sound, cx);
318
339
}
319
340
341
fn play_urgent_sound(&self, cx: &App) {
342
let file_name = self.settings.sounds.urgent_sound_type.file_name();
343
sound_cache::play_or(file_name, platform::play_sound, cx);
344
}
345
320
346
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
321
347
match event {
322
348
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -328,6 +354,7 @@ impl NotificationCenter {
328
354
AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
329
355
AppEvent::Call => self.sync_call_sounds(cx),
330
356
AppEvent::SoundSettings => self.on_account_sounds(cx),
357
AppEvent::ChatSettings => self.on_account_notifications(cx),
331
358
_ => {}
332
359
}
333
360
}
@@ -342,6 +369,7 @@ impl NotificationCenter {
342
369
if let Some(conversation_id) = selected {
343
370
self.unread_mentions.remove(&conversation_id);
344
371
self.stack.remove_conversation(&conversation_id);
372
self.urgent_repeats.stop_conversation(&conversation_id);
345
373
}
346
374
self.refresh_badge(cx);
347
375
}
@@ -390,7 +418,11 @@ impl NotificationCenter {
390
418
.unwrap_or(false)
391
419
}
392
420
393
pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
421
pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
422
incoming.chat.desktop = self
423
.app
424
.read(cx)
425
.chat_desktop_notifications(&incoming.conversation_id);
394
426
let bubble_text = match &incoming.preview {
395
427
Preview::Text(text) => text.replace('\n', " "),
396
428
Preview::Image => "Sent a picture".to_owned(),
@@ -412,6 +444,9 @@ impl NotificationCenter {
412
444
}
413
445
let decision = decide(&self.settings, &incoming, environment);
414
446
self.present(&incoming, decision, cx);
447
if !environment.chat_in_foreground {
448
self.urgent_repeats.track(&incoming, Utc::now());
449
}
415
450
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
416
451
&& let Some(native) = self.main_native
417
452
{
@@ -429,8 +464,14 @@ impl NotificationCenter {
429
464
model.time = chrono::Local::now().format("%H:%M").to_string();
430
465
}
431
466
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
432
if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
433
self.play_notification_sound(cx);
467
let audible =
468
outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);
469
if decision.sound && audible && !self.app.read(cx).mode.demo {
470
if decision.urgent_sound {
471
self.play_urgent_sound(cx);
472
} else {
473
self.play_notification_sound(cx);
474
}
434
475
}
435
476
if let Some(user_id) = incoming.sender_id.clone() {
436
477
self.app
@@ -448,8 +489,11 @@ impl NotificationCenter {
448
489
first_lines(&run.final_text, AGENT_BODY_LINES)
449
490
};
450
491
let toast = AgentToast {
451
run_id: run.id,
452
session_id: run.session_id.clone(),
492
kind: AgentToastKind::Run {
493
run_id: run.id,
494
session_id: run.session_id.clone(),
495
failed,
496
},
453
497
header: format!(
454
498
"{} - {} - {}",
455
499
run.action_label,
@@ -465,7 +509,6 @@ impl NotificationCenter {
465
509
} else {
466
510
body
467
511
},
468
failed,
469
512
};
470
513
let now = Instant::now();
471
514
let id = self
@@ -486,11 +529,90 @@ impl NotificationCenter {
486
529
return;
487
530
};
488
531
self.drop_toast(id, cx);
489
if agent.failed {
490
crate::agents::retry_run(agent.run_id, cx);
491
} else {
492
crate::agents::open_session(&agent.session_id, cx);
532
match agent.kind {
533
AgentToastKind::Run {
534
run_id,
535
failed: true,
536
..
537
} => crate::agents::retry_run(run_id, cx),
538
AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),
539
AgentToastKind::Proposal { .. } => {}
540
}
541
}
542
543
fn on_proposals(&mut self, cx: &mut Context<Self>) {
544
let pending = agent_api::pending_proposals(cx);
545
let unseen: HashSet<&str> = pending
546
.iter()
547
.filter(|proposal| !proposal.seen)
548
.map(|proposal| proposal.id.as_str())
549
.collect();
550
let resolved: Vec<u64> = self
551
.stack
552
.ids()
553
.into_iter()
554
.filter(|id| {
555
self.stack
556
.get(*id)
557
.and_then(|toast| toast.agent.as_ref()?.proposal_id())
558
.is_some_and(|proposal_id| !unseen.contains(proposal_id))
559
})
560
.collect();
561
for id in resolved {
562
self.drop_toast(id, cx);
563
}
564
let arrived: Vec<PendingProposal> = pending
565
.iter()
566
.filter(|proposal| {
567
!self.known_proposals.contains(&proposal.id)
568
&& !proposal.seen
569
&& proposal.created_at >= self.started_at
570
})
571
.cloned()
572
.collect();
573
self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();
574
for proposal in arrived {
575
self.present_proposal(&proposal, cx);
576
}
577
self.refresh_badge(cx);
578
}
579
580
fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {
581
let state = self.app.read(cx);
582
let desktop = state.chat_desktop_notifications(&proposal.conversation_id);
583
let conversation =
584
agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);
585
let environment = self.environment(&proposal.conversation_id, cx);
586
let decision = decide_proposal(&self.settings, desktop, environment);
587
if !decision.toast {
588
return;
493
589
}
590
let toast = AgentToast {
591
kind: AgentToastKind::Proposal {
592
proposal_id: proposal.id.clone(),
593
},
594
header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),
595
title: proposal.title(),
596
body: proposal.detail(),
597
};
598
let id = self.stack.push_agent(
599
toast,
600
&proposal.conversation_id,
601
proposal.jump_message_id(),
602
Instant::now(),
603
);
604
if let Some(model) = self.stack.get_mut(id) {
605
model.time = chrono::Local::now().format("%H:%M").to_string();
606
}
607
if decision.sound && !self.demo_mode {
608
self.play_notification_sound(cx);
609
}
610
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
611
&& let Some(native) = self.main_native
612
{
613
platform::flash(native);
614
}
615
self.sync_windows(cx);
494
616
}
495
617
496
618
fn visible_ids(&self) -> Vec<u64> {
@@ -558,7 +680,9 @@ impl NotificationCenter {
558
680
.map(|toast| {
559
681
let lines = match &toast.agent {
560
682
Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
561
None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
683
None => {
684
preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
685
}
562
686
};
563
687
layout::toast_height(toast, lines)
564
688
})
@@ -708,7 +832,12 @@ impl NotificationCenter {
708
832
let reconnecting =
709
833
model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
710
834
sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
711
sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
835
sync_loop(
836
&mut self.reconnecting,
837
reconnecting,
838
CallTone::Reconnecting,
839
cx,
840
);
712
841
}
713
842
714
843
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -849,6 +978,9 @@ impl NotificationCenter {
849
978
}
850
979
self.stack.promote(now, fade_in);
851
980
self.sync_hover_hold(now);
981
if !self.urgent_repeats.is_empty() {
982
self.repeat_urgent(cx);
983
}
852
984
if !self.app.read(cx).rings.is_empty() {
853
985
self.app.update(cx, |state, cx| state.tick_rings(cx));
854
986
}
@@ -876,6 +1008,33 @@ impl NotificationCenter {
876
1008
}
877
1009
}
878
1010
1011
fn repeat_urgent(&mut self, cx: &mut Context<Self>) {
1012
let sidebar = &self.app.read(cx).sidebar;
1013
self.urgent_repeats.stop_read(|conversation_id| {
1014
sidebar
1015
.chats
1016
.iter()
1017
.find(|chat| chat.id == conversation_id)
1018
.and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))
1019
});
1020
for incoming in self.urgent_repeats.due(Utc::now()) {
1021
let environment = self.environment(&incoming.conversation_id, cx);
1022
if environment.chat_in_foreground {
1023
self.urgent_repeats
1024
.stop_conversation(&incoming.conversation_id);
1025
continue;
1026
}
1027
self.stack.remove_conversation(&incoming.conversation_id);
1028
let decision = decide(&self.settings, &incoming, environment);
1029
self.present(&incoming, decision, cx);
1030
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
1031
&& let Some(native) = self.main_native
1032
{
1033
platform::flash(native);
1034
}
1035
}
1036
}
1037
879
1038
fn poll_tray(&mut self, cx: &mut Context<Self>) {
880
1039
let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();
881
1040
for command in commands {
@@ -948,7 +1107,7 @@ impl NotificationCenter {
948
1107
&state.sidebar,
949
1108
self.activity.read(cx).feed(),
950
1109
state.directory.section_settings.adaptive_rail(),
951
);
1110
) + crate::agent_api::unseen_proposal_count(cx);
952
1111
let still_unread = unread_conversation_ids(&state.sidebar);
953
1112
self.unread_mentions
954
1113
.retain(|conversation_id| still_unread.contains(conversation_id.as_str()));
@@ -1089,19 +1248,31 @@ impl NotificationCenter {
1089
1248
if self.is_dismissed(id) {
1090
1249
return;
1091
1250
}
1092
let Some((conversation_id, message_id)) = self
1093
.stack
1094
.get(id)
1095
.map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))
1096
else {
1251
let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {
1252
(
1253
toast.conversation_id.clone(),
1254
toast.message_id.clone(),
1255
toast
1256
.agent
1257
.as_ref()
1258
.and_then(|agent| agent.proposal_id().map(str::to_owned)),
1259
)
1260
}) else {
1097
1261
return;
1098
1262
};
1099
1263
self.drop_toast(id, cx);
1264
if let Some(proposal_id) = proposal_id {
1265
agent_api::mark_proposal_seen(&proposal_id, cx);
1266
}
1100
1267
self.raise_main_window(cx);
1101
1268
let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);
1102
1269
if let Some(selection) = selection {
1103
1270
self.app.update(cx, |state, cx| {
1104
state.jump_to_message(selection, message_id, cx)
1271
if message_id.is_empty() {
1272
state.select(selection, cx)
1273
} else {
1274
state.jump_to_message(selection, message_id, cx)
1275
}
1105
1276
});
1106
1277
}
1107
1278
}
@@ -1118,11 +1289,14 @@ impl NotificationCenter {
1118
1289
mentions_me: false,
1119
1290
muted: false,
1120
1291
signals: Default::default(),
1292
chat: Default::default(),
1121
1293
created_at: Utc::now(),
1294
importance: Default::default(),
1122
1295
};
1123
1296
let decision = Decision {
1124
1297
toast: true,
1125
1298
sound: self.settings.sounds.notification_sound,
1299
urgent_sound: false,
1126
1300
};
1127
1301
self.throttle = SoundThrottle::default();
1128
1302
self.present(&incoming, decision, cx);
@@ -1133,6 +1307,7 @@ impl NotificationCenter {
1133
1307
let decision = Decision {
1134
1308
toast: true,
1135
1309
sound: false,
1310
urgent_sound: false,
1136
1311
};
1137
1312
self.present(&incoming, decision, cx);
1138
1313
}
@@ -1287,7 +1462,9 @@ fn demo_incoming() -> Vec<Incoming> {
1287
1462
mentions_me: mention,
1288
1463
muted: false,
1289
1464
signals: Default::default(),
1465
chat: Default::default(),
1290
1466
created_at: Utc::now(),
1467
importance: Default::default(),
1291
1468
};
1292
1469
vec![
1293
1470
item(
@@ -1363,7 +1540,10 @@ mod tests {
1363
1540
scale: 1.,
1364
1541
};
1365
1542
let options = popup_options(slot, area);
1366
assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1543
assert_eq!(
1544
options.window_background,
1545
WindowBackgroundAppearance::Transparent
1546
);
1367
1547
assert_eq!(options.kind, WindowKind::PopUp);
1368
1548
}
1369
1549
@@ -1,7 +1,7 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet};2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use chrono::Utc;4
use chrono::{DateTime, Utc};5
use gpui_kit::*;5
use gpui_kit::*;6
use store::Sidebar;6
use store::Sidebar;7
7
@@ -12,20 +12,24 @@ use super::meeting_view::MeetingToastView;12
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};12
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};13
use super::ring_view::RingView;13
use super::ring_view::RingView;14
use super::rules::{14
use super::rules::{15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide,16
meeting_start_sound, ringtone_for, should_flash, should_ringback,16
decide_proposal, in_call, meeting_start_sound, ringtone_for, should_flash, should_ringback,17
shows_preview,17
};18
};18
use super::settings;19
use super::settings;19
use super::sound_cache::{self, SoundHandle};20
use super::sound_cache::{self, SoundHandle};20
use super::sounds::{CallTone, Ringtone};21
use super::sounds::{CallTone, Ringtone};21
use super::stack::{22
use super::stack::{22
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,23
AgentToast, AgentToastKind, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE,24
ToastModel, ToastStack,23
};25
};24
use super::taskbar::taskbar_badge_count;26
use super::taskbar::taskbar_badge_count;25
use super::text::describe;27
use super::text::describe;26
use super::toast::{PillView, ToastView};28
use super::toast::{PillView, ToastView};29
use super::urgent_repeat::UrgentRepeats;27
use crate::active_appearance::{self, ActiveAppearance};30
use crate::active_appearance::{self, ActiveAppearance};28
use crate::activity::ActivityCenter;31
use crate::activity::ActivityCenter;32
use crate::agent_api::{self, pending::PendingProposal};29
use crate::agents::{AgentRun, AgentRunsEvent, RunState};33
use crate::agents::{AgentRun, AgentRunsEvent, RunState};30
use crate::app_state::{AppEvent, AppState, selection_for};34
use crate::app_state::{AppEvent, AppState, selection_for};31
use crate::appearance::AppIcon;35
use crate::appearance::AppIcon;@@ -76,6 +80,7 @@ pub struct NotificationCenter {76
stack: ToastStack,80
stack: ToastStack,77
tracker: IncomingTracker,81
tracker: IncomingTracker,78
throttle: SoundThrottle,82
throttle: SoundThrottle,83
urgent_repeats: UrgentRepeats,79
windows: HashMap<u64, OpenWindow>,84
windows: HashMap<u64, OpenWindow>,80
opening: HashSet<u64>,85
opening: HashSet<u64>,81
call_windows: HashMap<CallToast, OpenWindow>,86
call_windows: HashMap<CallToast, OpenWindow>,@@ -97,6 +102,9 @@ pub struct NotificationCenter {97
_activity_observation: Subscription,102
_activity_observation: Subscription,98
_appearance_observation: Subscription,103
_appearance_observation: Subscription,99
_agent_subscription: Option<Subscription>,104
_agent_subscription: Option<Subscription>,105
started_at: DateTime<Utc>,106
known_proposals: HashSet<String>,107
_proposal_observation: Option<Subscription>,100
}108
}101
109
102
impl NotificationCenter {110
impl NotificationCenter {@@ -106,7 +114,8 @@ impl NotificationCenter {106
window: &mut Window,114
window: &mut Window,107
cx: &mut Context<Self>,115
cx: &mut Context<Self>,108
) -> Self {116
) -> Self {109
let settings = settings::load(&app.read(cx).store);117
let mut settings = settings::load(&app.read(cx).store);118
settings.account = app.read(cx).account_chat_settings().notifications;110
let app_icon = active_appearance::current(cx).app_icon;119
let app_icon = active_appearance::current(cx).app_icon;111
let tray = if app.read(cx).mode.demo {120
let tray = if app.read(cx).mode.demo {112
None121
None@@ -134,13 +143,19 @@ impl NotificationCenter {134
}143
}135
})144
})136
});145
});146
let proposal_observation =147
agent_api::handle(cx).map(|api| cx.observe(&api, |this, _, cx| this.on_proposals(cx)));137
let center = NotificationCenter {148
let center = NotificationCenter {149
started_at: Utc::now(),150
known_proposals: HashSet::new(),151
_proposal_observation: proposal_observation,138
main_window: window.window_handle(),152
main_window: window.window_handle(),139
main_native: platform::native_handle(window),153
main_native: platform::native_handle(window),140
settings,154
settings,141
stack: ToastStack::default(),155
stack: ToastStack::default(),142
tracker: IncomingTracker::new(Utc::now()),156
tracker: IncomingTracker::new(Utc::now()),143
throttle: SoundThrottle::default(),157
throttle: SoundThrottle::default(),158
urgent_repeats: UrgentRepeats::default(),144
windows: HashMap::new(),159
windows: HashMap::new(),145
opening: HashSet::new(),160
opening: HashSet::new(),146
call_windows: HashMap::new(),161
call_windows: HashMap::new(),@@ -272,13 +287,19 @@ impl NotificationCenter {272
self.sync_tray();287
self.sync_tray();273
if self.settings.sounds != previous {288
if self.settings.sounds != previous {274
let updated = self.settings.sounds.clone();289
let updated = self.settings.sounds.clone();275
self.app290
self.app.update(cx, |state, cx| {276
.update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));291
state.save_sound_settings(previous, updated, cx)292
});277
self.prefetch_sounds(cx);293
self.prefetch_sounds(cx);278
}294
}279
cx.notify();295
cx.notify();280
}296
}281
297
298
fn on_account_notifications(&mut self, cx: &mut Context<Self>) {299
self.settings.account = self.app.read(cx).account_chat_settings().notifications;300
cx.notify();301
}302
282
fn on_account_sounds(&mut self, cx: &mut Context<Self>) {303
fn on_account_sounds(&mut self, cx: &mut Context<Self>) {283
let Some(account) = self.app.read(cx).account_sounds.clone() else {304
let Some(account) = self.app.read(cx).account_sounds.clone() else {284
return;305
return;@@ -317,6 +338,11 @@ impl NotificationCenter {317
sound_cache::play_or(file_name, platform::play_sound, cx);338
sound_cache::play_or(file_name, platform::play_sound, cx);318
}339
}319
340
341
fn play_urgent_sound(&self, cx: &App) {342
let file_name = self.settings.sounds.urgent_sound_type.file_name();343
sound_cache::play_or(file_name, platform::play_sound, cx);344
}345
320
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {346
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {321
match event {347
match event {322
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),348
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),@@ -328,6 +354,7 @@ impl NotificationCenter {328
AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),354
AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),329
AppEvent::Call => self.sync_call_sounds(cx),355
AppEvent::Call => self.sync_call_sounds(cx),330
AppEvent::SoundSettings => self.on_account_sounds(cx),356
AppEvent::SoundSettings => self.on_account_sounds(cx),357
AppEvent::ChatSettings => self.on_account_notifications(cx),331
_ => {}358
_ => {}332
}359
}333
}360
}@@ -342,6 +369,7 @@ impl NotificationCenter {342
if let Some(conversation_id) = selected {369
if let Some(conversation_id) = selected {343
self.unread_mentions.remove(&conversation_id);370
self.unread_mentions.remove(&conversation_id);344
self.stack.remove_conversation(&conversation_id);371
self.stack.remove_conversation(&conversation_id);372
self.urgent_repeats.stop_conversation(&conversation_id);345
}373
}346
self.refresh_badge(cx);374
self.refresh_badge(cx);347
}375
}@@ -390,7 +418,11 @@ impl NotificationCenter {390
.unwrap_or(false)418
.unwrap_or(false)391
}419
}392
420
393
pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {421
pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {422
incoming.chat.desktop = self423
.app424
.read(cx)425
.chat_desktop_notifications(&incoming.conversation_id);394
let bubble_text = match &incoming.preview {426
let bubble_text = match &incoming.preview {395
Preview::Text(text) => text.replace('\n', " "),427
Preview::Text(text) => text.replace('\n', " "),396
Preview::Image => "Sent a picture".to_owned(),428
Preview::Image => "Sent a picture".to_owned(),@@ -412,6 +444,9 @@ impl NotificationCenter {412
}444
}413
let decision = decide(&self.settings, &incoming, environment);445
let decision = decide(&self.settings, &incoming, environment);414
self.present(&incoming, decision, cx);446
self.present(&incoming, decision, cx);447
if !environment.chat_in_foreground {448
self.urgent_repeats.track(&incoming, Utc::now());449
}415
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))450
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))416
&& let Some(native) = self.main_native451
&& let Some(native) = self.main_native417
{452
{@@ -429,8 +464,14 @@ impl NotificationCenter {429
model.time = chrono::Local::now().format("%H:%M").to_string();464
model.time = chrono::Local::now().format("%H:%M").to_string();430
}465
}431
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);466
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);432
if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {467
let audible =433
self.play_notification_sound(cx);468
outcome.plays_sound(throttle_allows) || (decision.urgent_sound && throttle_allows);469
if decision.sound && audible && !self.app.read(cx).mode.demo {470
if decision.urgent_sound {471
self.play_urgent_sound(cx);472
} else {473
self.play_notification_sound(cx);474
}434
}475
}435
if let Some(user_id) = incoming.sender_id.clone() {476
if let Some(user_id) = incoming.sender_id.clone() {436
self.app477
self.app@@ -448,8 +489,11 @@ impl NotificationCenter {448
first_lines(&run.final_text, AGENT_BODY_LINES)489
first_lines(&run.final_text, AGENT_BODY_LINES)449
};490
};450
let toast = AgentToast {491
let toast = AgentToast {451
run_id: run.id,492
kind: AgentToastKind::Run {452
session_id: run.session_id.clone(),493
run_id: run.id,494
session_id: run.session_id.clone(),495
failed,496
},453
header: format!(497
header: format!(454
"{} - {} - {}",498
"{} - {} - {}",455
run.action_label,499
run.action_label,@@ -465,7 +509,6 @@ impl NotificationCenter {465
} else {509
} else {466
body510
body467
},511
},468
failed,469
};512
};470
let now = Instant::now();513
let now = Instant::now();471
let id = self514
let id = self@@ -486,11 +529,90 @@ impl NotificationCenter {486
return;529
return;487
};530
};488
self.drop_toast(id, cx);531
self.drop_toast(id, cx);489
if agent.failed {532
match agent.kind {490
crate::agents::retry_run(agent.run_id, cx);533
AgentToastKind::Run {491
} else {534
run_id,492
crate::agents::open_session(&agent.session_id, cx);535
failed: true,536
..537
} => crate::agents::retry_run(run_id, cx),538
AgentToastKind::Run { session_id, .. } => crate::agents::open_session(&session_id, cx),539
AgentToastKind::Proposal { .. } => {}540
}541
}542
543
fn on_proposals(&mut self, cx: &mut Context<Self>) {544
let pending = agent_api::pending_proposals(cx);545
let unseen: HashSet<&str> = pending546
.iter()547
.filter(|proposal| !proposal.seen)548
.map(|proposal| proposal.id.as_str())549
.collect();550
let resolved: Vec<u64> = self551
.stack552
.ids()553
.into_iter()554
.filter(|id| {555
self.stack556
.get(*id)557
.and_then(|toast| toast.agent.as_ref()?.proposal_id())558
.is_some_and(|proposal_id| !unseen.contains(proposal_id))559
})560
.collect();561
for id in resolved {562
self.drop_toast(id, cx);563
}564
let arrived: Vec<PendingProposal> = pending565
.iter()566
.filter(|proposal| {567
!self.known_proposals.contains(&proposal.id)568
&& !proposal.seen569
&& proposal.created_at >= self.started_at570
})571
.cloned()572
.collect();573
self.known_proposals = pending.into_iter().map(|proposal| proposal.id).collect();574
for proposal in arrived {575
self.present_proposal(&proposal, cx);576
}577
self.refresh_badge(cx);578
}579
580
fn present_proposal(&mut self, proposal: &PendingProposal, cx: &mut Context<Self>) {581
let state = self.app.read(cx);582
let desktop = state.chat_desktop_notifications(&proposal.conversation_id);583
let conversation =584
agent_api::pending::conversation_label(&state.sidebar, &proposal.conversation_id);585
let environment = self.environment(&proposal.conversation_id, cx);586
let decision = decide_proposal(&self.settings, desktop, environment);587
if !decision.toast {588
return;493
}589
}590
let toast = AgentToast {591
kind: AgentToastKind::Proposal {592
proposal_id: proposal.id.clone(),593
},594
header: conversation.unwrap_or_else(|| proposal.agent.to_owned()),595
title: proposal.title(),596
body: proposal.detail(),597
};598
let id = self.stack.push_agent(599
toast,600
&proposal.conversation_id,601
proposal.jump_message_id(),602
Instant::now(),603
);604
if let Some(model) = self.stack.get_mut(id) {605
model.time = chrono::Local::now().format("%H:%M").to_string();606
}607
if decision.sound && !self.demo_mode {608
self.play_notification_sound(cx);609
}610
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))611
&& let Some(native) = self.main_native612
{613
platform::flash(native);614
}615
self.sync_windows(cx);494
}616
}495
617
496
fn visible_ids(&self) -> Vec<u64> {618
fn visible_ids(&self) -> Vec<u64> {@@ -558,7 +680,9 @@ impl NotificationCenter {558
.map(|toast| {680
.map(|toast| {559
let lines = match &toast.agent {681
let lines = match &toast.agent {560
Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),682
Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),561
None => preview_lines(&describe(toast, self.settings.preview).preview, cx),683
None => {684
preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)685
}562
};686
};563
layout::toast_height(toast, lines)687
layout::toast_height(toast, lines)564
})688
})@@ -708,7 +832,12 @@ impl NotificationCenter {708
let reconnecting =832
let reconnecting =709
model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;833
model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;710
sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);834
sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);711
sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);835
sync_loop(836
&mut self.reconnecting,837
reconnecting,838
CallTone::Reconnecting,839
cx,840
);712
}841
}713
842
714
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {843
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {@@ -849,6 +978,9 @@ impl NotificationCenter {849
}978
}850
self.stack.promote(now, fade_in);979
self.stack.promote(now, fade_in);851
self.sync_hover_hold(now);980
self.sync_hover_hold(now);981
if !self.urgent_repeats.is_empty() {982
self.repeat_urgent(cx);983
}852
if !self.app.read(cx).rings.is_empty() {984
if !self.app.read(cx).rings.is_empty() {853
self.app.update(cx, |state, cx| state.tick_rings(cx));985
self.app.update(cx, |state, cx| state.tick_rings(cx));854
}986
}@@ -876,6 +1008,33 @@ impl NotificationCenter {876
}1008
}877
}1009
}878
1010
1011
fn repeat_urgent(&mut self, cx: &mut Context<Self>) {1012
let sidebar = &self.app.read(cx).sidebar;1013
self.urgent_repeats.stop_read(|conversation_id| {1014
sidebar1015
.chats1016
.iter()1017
.find(|chat| chat.id == conversation_id)1018
.and_then(|chat| chat.last_read_at.filter(|_| !chat.unread))1019
});1020
for incoming in self.urgent_repeats.due(Utc::now()) {1021
let environment = self.environment(&incoming.conversation_id, cx);1022
if environment.chat_in_foreground {1023
self.urgent_repeats1024
.stop_conversation(&incoming.conversation_id);1025
continue;1026
}1027
self.stack.remove_conversation(&incoming.conversation_id);1028
let decision = decide(&self.settings, &incoming, environment);1029
self.present(&incoming, decision, cx);1030
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))1031
&& let Some(native) = self.main_native1032
{1033
platform::flash(native);1034
}1035
}1036
}1037
879
fn poll_tray(&mut self, cx: &mut Context<Self>) {1038
fn poll_tray(&mut self, cx: &mut Context<Self>) {880
let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();1039
let commands = self.tray.as_ref().map(Tray::poll).unwrap_or_default();881
for command in commands {1040
for command in commands {@@ -948,7 +1107,7 @@ impl NotificationCenter {948
&state.sidebar,1107
&state.sidebar,949
self.activity.read(cx).feed(),1108
self.activity.read(cx).feed(),950
state.directory.section_settings.adaptive_rail(),1109
state.directory.section_settings.adaptive_rail(),951
);1110
) + crate::agent_api::unseen_proposal_count(cx);952
let still_unread = unread_conversation_ids(&state.sidebar);1111
let still_unread = unread_conversation_ids(&state.sidebar);953
self.unread_mentions1112
self.unread_mentions954
.retain(|conversation_id| still_unread.contains(conversation_id.as_str()));1113
.retain(|conversation_id| still_unread.contains(conversation_id.as_str()));@@ -1089,19 +1248,31 @@ impl NotificationCenter {1089
if self.is_dismissed(id) {1248
if self.is_dismissed(id) {1090
return;1249
return;1091
}1250
}1092
let Some((conversation_id, message_id)) = self1251
let Some((conversation_id, message_id, proposal_id)) = self.stack.get(id).map(|toast| {1093
.stack1252
(1094
.get(id)1253
toast.conversation_id.clone(),1095
.map(|toast| (toast.conversation_id.clone(), toast.message_id.clone()))1254
toast.message_id.clone(),1096
else {1255
toast1256
.agent1257
.as_ref()1258
.and_then(|agent| agent.proposal_id().map(str::to_owned)),1259
)1260
}) else {1097
return;1261
return;1098
};1262
};1099
self.drop_toast(id, cx);1263
self.drop_toast(id, cx);1264
if let Some(proposal_id) = proposal_id {1265
agent_api::mark_proposal_seen(&proposal_id, cx);1266
}1100
self.raise_main_window(cx);1267
self.raise_main_window(cx);1101
let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);1268
let selection = selection_for(&self.app.read(cx).sidebar, &conversation_id);1102
if let Some(selection) = selection {1269
if let Some(selection) = selection {1103
self.app.update(cx, |state, cx| {1270
self.app.update(cx, |state, cx| {1104
state.jump_to_message(selection, message_id, cx)1271
if message_id.is_empty() {1272
state.select(selection, cx)1273
} else {1274
state.jump_to_message(selection, message_id, cx)1275
}1105
});1276
});1106
}1277
}1107
}1278
}@@ -1118,11 +1289,14 @@ impl NotificationCenter {1118
mentions_me: false,1289
mentions_me: false,1119
muted: false,1290
muted: false,1120
signals: Default::default(),1291
signals: Default::default(),1292
chat: Default::default(),1121
created_at: Utc::now(),1293
created_at: Utc::now(),1294
importance: Default::default(),1122
};1295
};1123
let decision = Decision {1296
let decision = Decision {1124
toast: true,1297
toast: true,1125
sound: self.settings.sounds.notification_sound,1298
sound: self.settings.sounds.notification_sound,1299
urgent_sound: false,1126
};1300
};1127
self.throttle = SoundThrottle::default();1301
self.throttle = SoundThrottle::default();1128
self.present(&incoming, decision, cx);1302
self.present(&incoming, decision, cx);@@ -1133,6 +1307,7 @@ impl NotificationCenter {1133
let decision = Decision {1307
let decision = Decision {1134
toast: true,1308
toast: true,1135
sound: false,1309
sound: false,1310
urgent_sound: false,1136
};1311
};1137
self.present(&incoming, decision, cx);1312
self.present(&incoming, decision, cx);1138
}1313
}@@ -1287,7 +1462,9 @@ fn demo_incoming() -> Vec<Incoming> {1287
mentions_me: mention,1462
mentions_me: mention,1288
muted: false,1463
muted: false,1289
signals: Default::default(),1464
signals: Default::default(),1465
chat: Default::default(),1290
created_at: Utc::now(),1466
created_at: Utc::now(),1467
importance: Default::default(),1291
};1468
};1292
vec![1469
vec![1293
item(1470
item(@@ -1363,7 +1540,10 @@ mod tests {1363
scale: 1.,1540
scale: 1.,1364
};1541
};1365
let options = popup_options(slot, area);1542
let options = popup_options(slot, area);1366
assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);1543
assert_eq!(1544
options.window_background,1545
WindowBackgroundAppearance::Transparent1546
);1367
assert_eq!(options.kind, WindowKind::PopUp);1547
assert_eq!(options.kind, WindowKind::PopUp);1368
}1548
}1369
1549
@@ -485,7 +485,7 @@ impl Render for ToastView {
485
485
let id = self.id;
486
486
let (model, preview_on) = {
487
487
let center = self.center.read(cx);
488
(center.model(id).cloned(), center.settings().preview)
488
(center.model(id).cloned(), center.settings().account.show_preview)
489
489
};
490
490
let Some(model) = model else {
491
491
return div().size_full().bg(theme::popup()).into_any_element();
@@ -485,7 +485,7 @@ impl Render for ToastView {485
let id = self.id;485
let id = self.id;486
let (model, preview_on) = {486
let (model, preview_on) = {487
let center = self.center.read(cx);487
let center = self.center.read(cx);488
(center.model(id).cloned(), center.settings().preview)488
(center.model(id).cloned(), center.settings().account.show_preview)489
};489
};490
let Some(model) = model else {490
let Some(model) = model else {491
return div().size_full().bg(theme::popup()).into_any_element();491
return div().size_full().bg(theme::popup()).into_any_element();@@ -0,0 +1,144 @@
1
use gpui_kit::*;
2
use teams_core::{
3
ActivityAlert, ChatSettingChange, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
4
NotificationPreset, UpArrowBehavior,
5
};
6
7
use super::rows::{Choice, control_row, select};
8
use crate::app_state::AppState;
9
10
pub struct Labeled<T: 'static> {
11
pub label: &'static str,
12
pub value: T,
13
}
14
15
const fn option<T>(label: &'static str, value: T) -> Labeled<T> {
16
Labeled { label, value }
17
}
18
19
pub const DENSITY: [Labeled<MessageDensity>; 2] = [
20
option("Comfy", MessageDensity::Comfy),
21
option("Compact", MessageDensity::Compact),
22
];
23
24
pub const ENTER_KEY: [Labeled<EnterKeyBehavior>; 2] = [
25
option("Send the message", EnterKeyBehavior::Send),
26
option(
27
"Start a new line (to send, select Send or use Ctrl+Enter).",
28
EnterKeyBehavior::NewLine,
29
),
30
];
31
32
pub const UP_ARROW: [Labeled<UpArrowBehavior>; 3] = [
33
option(
34
"Move focus to message list",
35
UpArrowBehavior::NavigateToMessages,
36
),
37
option("Edit last message", UpArrowBehavior::EditLastMessage),
38
option("Stay in compose box", UpArrowBehavior::StayInCompose),
39
];
40
41
pub const PRESETS: [Labeled<NotificationPreset>; 3] = [
42
option("All activity", NotificationPreset::AllActivity),
43
option("Mentions & replies", NotificationPreset::MentionsAndReplies),
44
option("Customised", NotificationPreset::Customised),
45
];
46
47
pub const CHAT_MESSAGES: [Labeled<ActivityAlert>; 2] = [
48
option("Show in banner", ActivityAlert::OnlyBanner),
49
option("Off", ActivityAlert::Off),
50
];
51
52
pub const MENTIONS: [Labeled<ActivityAlert>; 2] = [
53
option("Show in Activity and banner", ActivityAlert::BannerAndFeed),
54
option("Show in Activity", ActivityAlert::OnlyFeed),
55
];
56
57
pub const ACTIVITY_OR_OFF: [Labeled<ActivityAlert>; 3] = [
58
option("Show in Activity and banner", ActivityAlert::BannerAndFeed),
59
option("Show in Activity", ActivityAlert::OnlyFeed),
60
option("Off", ActivityAlert::Off),
61
];
62
63
pub const MEETING_CHATS: [Labeled<MeetingChatNotifications>; 3] = [
64
option("Mute", MeetingChatNotifications::Mute),
65
option("Unmute", MeetingChatNotifications::Unmute),
66
option(
67
"Mute until I join or send a message",
68
MeetingChatNotifications::MuteUntilJoin,
69
),
70
];
71
72
pub fn preset_detail(preset: NotificationPreset) -> &'static str {
73
match preset {
74
NotificationPreset::AllActivity => "New messages, reactions, and all mentions",
75
NotificationPreset::MentionsAndReplies => "Personal mentions and replies to your messages",
76
NotificationPreset::Customised => "Your customised settings are active.",
77
}
78
}
79
80
pub fn meeting_chats_detail(setting: MeetingChatNotifications) -> &'static str {
81
match setting {
82
MeetingChatNotifications::Mute => "Don't send notifications for any meetings.",
83
MeetingChatNotifications::Unmute => "Send notifications for all meetings.",
84
MeetingChatNotifications::MuteUntilJoin => {
85
"Only send notifications if I've joined a meeting or sent a message."
86
}
87
}
88
}
89
90
pub fn label_of<T: PartialEq + Copy>(options: &[Labeled<T>], current: T) -> &'static str {
91
options
92
.iter()
93
.find(|option| option.value == current)
94
.map(|option| option.label)
95
.unwrap_or_default()
96
}
97
98
pub fn account_select<T: PartialEq + Copy + 'static>(
99
app: &Entity<AppState>,
100
(id, title, detail): (&'static str, &'static str, &'static str),
101
options: &'static [Labeled<T>],
102
current: T,
103
change: fn(T) -> ChatSettingChange,
104
) -> Div {
105
let choices = options
106
.iter()
107
.map(|option| {
108
let (app, value) = (app.clone(), option.value);
109
Choice::new(option.label, value == current, move |cx| {
110
app.update(cx, |state, cx| state.save_chat_setting(change(value), cx))
111
})
112
})
113
.collect();
114
control_row(
115
title,
116
detail,
117
select(id, label_of(options, current), false, choices),
118
)
119
}
120
121
#[cfg(test)]
122
mod tests {
123
use teams_core::{ActivityAlert, MeetingChatNotifications, MessageDensity, UpArrowBehavior};
124
125
use super::{CHAT_MESSAGES, DENSITY, MEETING_CHATS, MENTIONS, UP_ARROW, label_of};
126
127
#[test]
128
fn every_value_has_a_teams_label() {
129
assert_eq!(label_of(&DENSITY, MessageDensity::Compact), "Compact");
130
assert_eq!(
131
label_of(&UP_ARROW, UpArrowBehavior::default()),
132
"Edit last message"
133
);
134
assert_eq!(
135
label_of(&MEETING_CHATS, MeetingChatNotifications::default()),
136
"Mute until I join or send a message"
137
);
138
assert_eq!(
139
label_of(&CHAT_MESSAGES, ActivityAlert::OnlyBanner),
140
"Show in banner"
141
);
142
assert_eq!(label_of(&MENTIONS, ActivityAlert::Off), "");
143
}
144
}
@@ -0,0 +1,144 @@1
use gpui_kit::*;2
use teams_core::{3
ActivityAlert, ChatSettingChange, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,4
NotificationPreset, UpArrowBehavior,5
};6
7
use super::rows::{Choice, control_row, select};8
use crate::app_state::AppState;9
10
pub struct Labeled<T: 'static> {11
pub label: &'static str,12
pub value: T,13
}14
15
const fn option<T>(label: &'static str, value: T) -> Labeled<T> {16
Labeled { label, value }17
}18
19
pub const DENSITY: [Labeled<MessageDensity>; 2] = [20
option("Comfy", MessageDensity::Comfy),21
option("Compact", MessageDensity::Compact),22
];23
24
pub const ENTER_KEY: [Labeled<EnterKeyBehavior>; 2] = [25
option("Send the message", EnterKeyBehavior::Send),26
option(27
"Start a new line (to send, select Send or use Ctrl+Enter).",28
EnterKeyBehavior::NewLine,29
),30
];31
32
pub const UP_ARROW: [Labeled<UpArrowBehavior>; 3] = [33
option(34
"Move focus to message list",35
UpArrowBehavior::NavigateToMessages,36
),37
option("Edit last message", UpArrowBehavior::EditLastMessage),38
option("Stay in compose box", UpArrowBehavior::StayInCompose),39
];40
41
pub const PRESETS: [Labeled<NotificationPreset>; 3] = [42
option("All activity", NotificationPreset::AllActivity),43
option("Mentions & replies", NotificationPreset::MentionsAndReplies),44
option("Customised", NotificationPreset::Customised),45
];46
47
pub const CHAT_MESSAGES: [Labeled<ActivityAlert>; 2] = [48
option("Show in banner", ActivityAlert::OnlyBanner),49
option("Off", ActivityAlert::Off),50
];51
52
pub const MENTIONS: [Labeled<ActivityAlert>; 2] = [53
option("Show in Activity and banner", ActivityAlert::BannerAndFeed),54
option("Show in Activity", ActivityAlert::OnlyFeed),55
];56
57
pub const ACTIVITY_OR_OFF: [Labeled<ActivityAlert>; 3] = [58
option("Show in Activity and banner", ActivityAlert::BannerAndFeed),59
option("Show in Activity", ActivityAlert::OnlyFeed),60
option("Off", ActivityAlert::Off),61
];62
63
pub const MEETING_CHATS: [Labeled<MeetingChatNotifications>; 3] = [64
option("Mute", MeetingChatNotifications::Mute),65
option("Unmute", MeetingChatNotifications::Unmute),66
option(67
"Mute until I join or send a message",68
MeetingChatNotifications::MuteUntilJoin,69
),70
];71
72
pub fn preset_detail(preset: NotificationPreset) -> &'static str {73
match preset {74
NotificationPreset::AllActivity => "New messages, reactions, and all mentions",75
NotificationPreset::MentionsAndReplies => "Personal mentions and replies to your messages",76
NotificationPreset::Customised => "Your customised settings are active.",77
}78
}79
80
pub fn meeting_chats_detail(setting: MeetingChatNotifications) -> &'static str {81
match setting {82
MeetingChatNotifications::Mute => "Don't send notifications for any meetings.",83
MeetingChatNotifications::Unmute => "Send notifications for all meetings.",84
MeetingChatNotifications::MuteUntilJoin => {85
"Only send notifications if I've joined a meeting or sent a message."86
}87
}88
}89
90
pub fn label_of<T: PartialEq + Copy>(options: &[Labeled<T>], current: T) -> &'static str {91
options92
.iter()93
.find(|option| option.value == current)94
.map(|option| option.label)95
.unwrap_or_default()96
}97
98
pub fn account_select<T: PartialEq + Copy + 'static>(99
app: &Entity<AppState>,100
(id, title, detail): (&'static str, &'static str, &'static str),101
options: &'static [Labeled<T>],102
current: T,103
change: fn(T) -> ChatSettingChange,104
) -> Div {105
let choices = options106
.iter()107
.map(|option| {108
let (app, value) = (app.clone(), option.value);109
Choice::new(option.label, value == current, move |cx| {110
app.update(cx, |state, cx| state.save_chat_setting(change(value), cx))111
})112
})113
.collect();114
control_row(115
title,116
detail,117
select(id, label_of(options, current), false, choices),118
)119
}120
121
#[cfg(test)]122
mod tests {123
use teams_core::{ActivityAlert, MeetingChatNotifications, MessageDensity, UpArrowBehavior};124
125
use super::{CHAT_MESSAGES, DENSITY, MEETING_CHATS, MENTIONS, UP_ARROW, label_of};126
127
#[test]128
fn every_value_has_a_teams_label() {129
assert_eq!(label_of(&DENSITY, MessageDensity::Compact), "Compact");130
assert_eq!(131
label_of(&UP_ARROW, UpArrowBehavior::default()),132
"Edit last message"133
);134
assert_eq!(135
label_of(&MEETING_CHATS, MeetingChatNotifications::default()),136
"Mute until I join or send a message"137
);138
assert_eq!(139
label_of(&CHAT_MESSAGES, ActivityAlert::OnlyBanner),140
"Show in banner"141
);142
assert_eq!(label_of(&MENTIONS, ActivityAlert::Off), "");143
}144
}@@ -1,30 +1,88 @@
1
1
use gpui_kit::component::v_flex;
2
2
use gpui_kit::*;
3
use teams_core::ChatSection;
3
use teams_core::{ChatSection, ChatSettingChange};
4
4
5
use super::account::{DENSITY, ENTER_KEY, account_select};
5
6
use super::rows::{caption, toggle_row};
6
7
use crate::app_state::AppState;
7
8
use crate::theme;
8
9
10
const MARKDOWN_DETAIL: &str = "Use mark-down language to define the structure and appearance of messages. Your formatting will take effect once you send your message. When this is on, the formatting options menu won't be visible.";
11
const RECEIPTS_DETAIL: &str = "Let people know when you've seen their messages and know when they've seen yours. Close and reopen any chat windows for the setting to take effect in those chats.";
12
9
13
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10
let enabled = app
11
.read(cx)
12
.directory
13
.section_settings
14
.enabled(ChatSection::Muted);
15
let toggle_app = app.clone();
16
v_flex().w_full().child(caption("CHAT LIST")).child(
17
toggle_row(
18
"settings-muted-section",
19
"Show muted items in their own section",
20
"Read from your Teams account",
21
theme::text_muted(),
22
enabled,
14
let state = app.read(cx);
15
let muted_section = state.directory.section_settings.enabled(ChatSection::Muted);
16
let settings = state.account_chat_settings();
17
let markdown_mode = state.markdown_mode;
18
let (section_app, markdown_app, receipts_app) = (app.clone(), app.clone(), app.clone());
19
v_flex()
20
.w_full()
21
.child(caption("CHAT LIST"))
22
.child(
23
toggle_row(
24
"settings-muted-section",
25
"Show muted items in their own section",
26
"Read from your Teams account",
27
theme::text_muted(),
28
muted_section,
29
)
30
.on_click(move |_, _, cx| {
31
section_app.update(cx, |state, cx| {
32
state.set_chat_section(ChatSection::Muted, !muted_section, cx)
33
})
34
}),
35
)
36
.child(caption("CHATS"))
37
.child(account_select(
38
app,
39
(
40
"settings-message-density",
41
"Message density",
42
"Compact your chats and see more messages",
43
),
44
&DENSITY,
45
settings.message_density,
46
ChatSettingChange::MessageDensity,
47
))
48
.child(account_select(
49
app,
50
(
51
"settings-enter-key",
52
"When writing a message, press Enter to",
53
"This setting doesn't apply when message formatting is active.",
54
),
55
&ENTER_KEY,
56
settings.enter_key,
57
ChatSettingChange::EnterKey,
58
))
59
.child(
60
toggle_row(
61
"settings-markdown",
62
"Format messages using mark-down",
63
MARKDOWN_DETAIL,
64
theme::text_muted(),
65
markdown_mode,
66
)
67
.on_click(move |_, _, cx| {
68
markdown_app.update(cx, |state, cx| state.set_markdown_mode(!markdown_mode, cx))
69
}),
70
)
71
.child(
72
toggle_row(
73
"settings-read-receipts",
74
"Read receipts",
75
RECEIPTS_DETAIL,
76
theme::text_muted(),
77
settings.read_receipts,
78
)
79
.on_click(move |_, _, cx| {
80
receipts_app.update(cx, |state, cx| {
81
state.save_chat_setting(
82
ChatSettingChange::ReadReceipts(!settings.read_receipts),
83
cx,
84
)
85
})
86
}),
23
87
)
24
.on_click(move |_, _, cx| {
25
toggle_app.update(cx, |state, cx| {
26
state.set_chat_section(ChatSection::Muted, !enabled, cx)
27
})
28
}),
29
)
30
88
}
@@ -1,30 +1,88 @@1
use gpui_kit::component::v_flex;1
use gpui_kit::component::v_flex;2
use gpui_kit::*;2
use gpui_kit::*;3
use teams_core::ChatSection;3
use teams_core::{ChatSection, ChatSettingChange};4
4
5
use super::account::{DENSITY, ENTER_KEY, account_select};5
use super::rows::{caption, toggle_row};6
use super::rows::{caption, toggle_row};6
use crate::app_state::AppState;7
use crate::app_state::AppState;7
use crate::theme;8
use crate::theme;8
9
10
const MARKDOWN_DETAIL: &str = "Use mark-down language to define the structure and appearance of messages. Your formatting will take effect once you send your message. When this is on, the formatting options menu won't be visible.";11
const RECEIPTS_DETAIL: &str = "Let people know when you've seen their messages and know when they've seen yours. Close and reopen any chat windows for the setting to take effect in those chats.";12
9
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {13
pub fn render(app: &Entity<AppState>, cx: &App) -> Div {10
let enabled = app14
let state = app.read(cx);11
.read(cx)15
let muted_section = state.directory.section_settings.enabled(ChatSection::Muted);12
.directory16
let settings = state.account_chat_settings();13
.section_settings17
let markdown_mode = state.markdown_mode;14
.enabled(ChatSection::Muted);18
let (section_app, markdown_app, receipts_app) = (app.clone(), app.clone(), app.clone());15
let toggle_app = app.clone();19
v_flex()16
v_flex().w_full().child(caption("CHAT LIST")).child(20
.w_full()17
toggle_row(21
.child(caption("CHAT LIST"))18
"settings-muted-section",22
.child(19
"Show muted items in their own section",23
toggle_row(20
"Read from your Teams account",24
"settings-muted-section",21
theme::text_muted(),25
"Show muted items in their own section",22
enabled,26
"Read from your Teams account",27
theme::text_muted(),28
muted_section,29
)30
.on_click(move |_, _, cx| {31
section_app.update(cx, |state, cx| {32
state.set_chat_section(ChatSection::Muted, !muted_section, cx)33
})34
}),35
)36
.child(caption("CHATS"))37
.child(account_select(38
app,39
(40
"settings-message-density",41
"Message density",42
"Compact your chats and see more messages",43
),44
&DENSITY,45
settings.message_density,46
ChatSettingChange::MessageDensity,47
))48
.child(account_select(49
app,50
(51
"settings-enter-key",52
"When writing a message, press Enter to",53
"This setting doesn't apply when message formatting is active.",54
),55
&ENTER_KEY,56
settings.enter_key,57
ChatSettingChange::EnterKey,58
))59
.child(60
toggle_row(61
"settings-markdown",62
"Format messages using mark-down",63
MARKDOWN_DETAIL,64
theme::text_muted(),65
markdown_mode,66
)67
.on_click(move |_, _, cx| {68
markdown_app.update(cx, |state, cx| state.set_markdown_mode(!markdown_mode, cx))69
}),70
)71
.child(72
toggle_row(73
"settings-read-receipts",74
"Read receipts",75
RECEIPTS_DETAIL,76
theme::text_muted(),77
settings.read_receipts,78
)79
.on_click(move |_, _, cx| {80
receipts_app.update(cx, |state, cx| {81
state.save_chat_setting(82
ChatSettingChange::ReadReceipts(!settings.read_receipts),83
cx,84
)85
})86
}),23
)87
)24
.on_click(move |_, _, cx| {25
toggle_app.update(cx, |state, cx| {26
state.set_chat_section(ChatSection::Muted, !enabled, cx)27
})28
}),29
)30
}88
}@@ -135,7 +135,7 @@ impl SettingsDialog {
135
135
general::render(&self.center, &self.app, cx).into_any_element()
136
136
}
137
137
SettingsSection::Notifications => {
138
notifications::render(&self.center, cx).into_any_element()
138
notifications::render(&self.center, &self.app, cx).into_any_element()
139
139
}
140
140
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),
141
141
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),
@@ -135,7 +135,7 @@ impl SettingsDialog {135
general::render(&self.center, &self.app, cx).into_any_element()135
general::render(&self.center, &self.app, cx).into_any_element()136
}136
}137
SettingsSection::Notifications => {137
SettingsSection::Notifications => {138
notifications::render(&self.center, cx).into_any_element()138
notifications::render(&self.center, &self.app, cx).into_any_element()139
}139
}140
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),140
SettingsSection::Appearance => appearance::render(&self.app, cx).into_any_element(),141
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),141
SettingsSection::Chats => chats::render(&self.app, cx).into_any_element(),@@ -6,8 +6,9 @@ use gpui_kit::component::{
6
6
v_flex,
7
7
};
8
8
use gpui_kit::*;
9
use teams_core::TranslationBehavior;
9
use teams_core::{ChatSettingChange, TranslationBehavior};
10
10
11
use super::account::{UP_ARROW, account_select};
11
12
use super::rows::{Choice, caption, control_row, select, toggle_row};
12
13
use crate::app_state::AppState;
13
14
use crate::notify::NotificationCenter;
@@ -44,6 +45,18 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
44
45
})
45
46
}),
46
47
)
48
.child(caption("COMPOSE BOX"))
49
.child(account_select(
50
app,
51
(
52
"settings-up-arrow",
53
"Up arrow key behaviour in compose box",
54
"Choose what happens when you press Up arrow at the beginning of the compose box.",
55
),
56
&UP_ARROW,
57
app.read(cx).account_chat_settings().up_arrow,
58
ChatSettingChange::UpArrow,
59
))
47
60
.child(caption("TRANSLATION"))
48
61
.children(translation_rows(app, cx))
49
62
}
@@ -6,8 +6,9 @@ use gpui_kit::component::{6
v_flex,6
v_flex,7
};7
};8
use gpui_kit::*;8
use gpui_kit::*;9
use teams_core::TranslationBehavior;9
use teams_core::{ChatSettingChange, TranslationBehavior};10
10
11
use super::account::{UP_ARROW, account_select};11
use super::rows::{Choice, caption, control_row, select, toggle_row};12
use super::rows::{Choice, caption, control_row, select, toggle_row};12
use crate::app_state::AppState;13
use crate::app_state::AppState;13
use crate::notify::NotificationCenter;14
use crate::notify::NotificationCenter;@@ -44,6 +45,18 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &44
})45
})45
}),46
}),46
)47
)48
.child(caption("COMPOSE BOX"))49
.child(account_select(50
app,51
(52
"settings-up-arrow",53
"Up arrow key behaviour in compose box",54
"Choose what happens when you press Up arrow at the beginning of the compose box.",55
),56
&UP_ARROW,57
app.read(cx).account_chat_settings().up_arrow,58
ChatSettingChange::UpArrow,59
))47
.child(caption("TRANSLATION"))60
.child(caption("TRANSLATION"))48
.children(translation_rows(app, cx))61
.children(translation_rows(app, cx))49
}62
}@@ -1,4 +1,5 @@
1
1
mod about;
2
mod account;
2
3
mod appearance;
3
4
mod calls;
4
5
mod chats;
@@ -15,4 +16,4 @@ pub use dialog::metrics;
15
16
pub use dialog::{SettingsDialog, SettingsDialogEvent};
16
17
#[cfg(test)]
17
18
pub use nav::{item_selector, label, label_selector};
18
pub(crate) use rows::switch;
19
pub(crate) use rows::{select_selector, switch};
@@ -1,4 +1,5 @@1
mod about;1
mod about;2
mod account;2
mod appearance;3
mod appearance;3
mod calls;4
mod calls;4
mod chats;5
mod chats;@@ -15,4 +16,4 @@ pub use dialog::metrics;15
pub use dialog::{SettingsDialog, SettingsDialogEvent};16
pub use dialog::{SettingsDialog, SettingsDialogEvent};16
#[cfg(test)]17
#[cfg(test)]17
pub use nav::{item_selector, label, label_selector};18
pub use nav::{item_selector, label, label_selector};18
pub(crate) use rows::switch;19
pub(crate) use rows::{select_selector, switch};@@ -1,7 +1,14 @@
1
1
use gpui_kit::component::{h_flex, v_flex};
2
2
use gpui_kit::*;
3
3
4
use teams_core::ChatSettingChange;
5
6
use super::account::{
7
ACTIVITY_OR_OFF, CHAT_MESSAGES, MEETING_CHATS, MENTIONS, PRESETS, account_select,
8
meeting_chats_detail, preset_detail,
9
};
4
10
use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11
use crate::app_state::AppState;
5
12
use crate::notify::NotificationCenter;
6
13
use crate::notify::rules::{Corner, Settings};
7
14
use crate::notify::sounds::AlertSound;
@@ -17,20 +24,12 @@ struct Toggle {
17
24
field: Accessor,
18
25
}
19
26
20
const APPEARANCE: [Toggle; 2] = [
21
Toggle {
22
id: "settings-preview",
23
title: "Show message preview",
24
detail: "Off: only \"New message\"",
25
field: |settings| &mut settings.preview,
26
},
27
Toggle {
28
id: "settings-flash",
29
title: "Flash taskbar when notifications are received",
30
detail: "On new messages, until you open the window",
31
field: |settings| &mut settings.flash,
32
},
33
];
27
const FLASH: Toggle = Toggle {
28
id: "settings-flash",
29
title: "Flash taskbar when notifications are received",
30
detail: "On new messages, until you open the window",
31
field: |settings| &mut settings.flash,
32
};
34
33
35
34
const NOTIFICATION_SOUND: Toggle = Toggle {
36
35
id: "settings-notification-sound",
@@ -61,13 +60,6 @@ const CALL_SOUNDS: [Toggle; 2] = [
61
60
},
62
61
];
63
62
64
const MENTIONS_ONLY: Toggle = Toggle {
65
id: "settings-mentions-only",
66
title: "Mentions only",
67
detail: "Direct messages and @mentions",
68
field: |settings| &mut settings.mentions_only,
69
};
70
71
63
const HIDE_IN_CALLS: Toggle = Toggle {
72
64
id: "settings-hide-in-calls",
73
65
title: "Hide notifications during calls and meetings",
@@ -75,7 +67,8 @@ const HIDE_IN_CALLS: Toggle = Toggle {
75
67
field: |settings| &mut settings.mute_in_calls,
76
68
};
77
69
78
pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
70
pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &App) -> Div {
71
let account = app.read(cx).account_chat_settings().notifications;
79
72
let mut current = center.read(cx).settings().clone();
80
73
let corner = current.corner;
81
74
let sounds = current.sounds.clone();
@@ -83,17 +76,17 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
83
76
let on = *(toggle.field)(&mut current);
84
77
toggle_element(center, toggle, on)
85
78
};
86
let appearance: Vec<Stateful<Div>> = APPEARANCE.iter().map(&mut toggle).collect();
79
let flash = toggle(&FLASH);
87
80
let notification_sound = toggle(&NOTIFICATION_SOUND);
88
81
let urgent_sound = toggle(&URGENT_SOUND);
89
82
let call_sounds: Vec<Stateful<Div>> = CALL_SOUNDS.iter().map(&mut toggle).collect();
90
let mentions_only = toggle(&MENTIONS_ONLY);
91
83
let hide_in_calls = toggle(&HIDE_IN_CALLS);
92
84
let test_center = center.clone();
93
85
v_flex()
94
86
.w_full()
95
87
.child(caption("APPEARANCE AND SOUND"))
96
.children(appearance)
88
.child(preview_toggle(app, account.show_preview))
89
.child(flash)
97
90
.child(control_row(
98
91
"Position on the screen",
99
92
"Corner of the main screen",
@@ -141,12 +134,82 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
141
134
|settings| &mut settings.sounds.urgent_sound_type,
142
135
))
143
136
.children(call_sounds)
144
.child(caption("WHAT YOU GET NOTIFIED FOR"))
145
.child(mentions_only)
137
.child(caption("TEAMS AND CHANNELS"))
138
.child(account_select(
139
app,
140
(
141
"settings-notification-preset",
142
"Teams and channels",
143
preset_detail(account.preset),
144
),
145
&PRESETS,
146
account.preset,
147
ChatSettingChange::Preset,
148
))
149
.child(caption("CHAT"))
150
.child(account_select(
151
app,
152
("settings-chat-messages", "Chat message notifications", ""),
153
&CHAT_MESSAGES,
154
account.chat_messages,
155
ChatSettingChange::ChatMessages,
156
))
157
.child(account_select(
158
app,
159
("settings-personal-mentions", "Personal @mentions", ""),
160
&MENTIONS,
161
account.personal_mentions,
162
ChatSettingChange::PersonalMentions,
163
))
164
.child(account_select(
165
app,
166
(
167
"settings-everyone-mentions",
168
"Everyone in chat @mentions",
169
"",
170
),
171
&ACTIVITY_OR_OFF,
172
account.everyone_mentions,
173
ChatSettingChange::EveryoneMentions,
174
))
175
.child(account_select(
176
app,
177
("settings-likes", "Likes and reactions", ""),
178
&ACTIVITY_OR_OFF,
179
account.likes,
180
ChatSettingChange::Likes,
181
))
146
182
.child(caption("MEETINGS AND CALLS"))
183
.child(account_select(
184
app,
185
(
186
"settings-meeting-chats",
187
"Meeting chat notifications",
188
meeting_chats_detail(account.meeting_chats),
189
),
190
&MEETING_CHATS,
191
account.meeting_chats,
192
ChatSettingChange::MeetingChats,
193
))
147
194
.child(hide_in_calls)
148
195
}
149
196
197
fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {
198
let app = app.clone();
199
toggle_row(
200
"settings-preview",
201
"Show message preview",
202
"Off: only \"New message\"",
203
theme::text_muted(),
204
on,
205
)
206
.on_click(move |_, _, cx| {
207
app.update(cx, |state, cx| {
208
state.save_chat_setting(ChatSettingChange::ShowPreview(!on), cx)
209
})
210
})
211
}
212
150
213
fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {
151
214
let center = center.clone();
152
215
let field = toggle.field;
@@ -1,7 +1,14 @@1
use gpui_kit::component::{h_flex, v_flex};1
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::*;2
use gpui_kit::*;3
3
4
use teams_core::ChatSettingChange;5
6
use super::account::{7
ACTIVITY_OR_OFF, CHAT_MESSAGES, MEETING_CHATS, MENTIONS, PRESETS, account_select,8
meeting_chats_detail, preset_detail,9
};4
use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};10
use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};11
use crate::app_state::AppState;5
use crate::notify::NotificationCenter;12
use crate::notify::NotificationCenter;6
use crate::notify::rules::{Corner, Settings};13
use crate::notify::rules::{Corner, Settings};7
use crate::notify::sounds::AlertSound;14
use crate::notify::sounds::AlertSound;@@ -17,20 +24,12 @@ struct Toggle {17
field: Accessor,24
field: Accessor,18
}25
}19
26
20
const APPEARANCE: [Toggle; 2] = [27
const FLASH: Toggle = Toggle {21
Toggle {28
id: "settings-flash",22
id: "settings-preview",29
title: "Flash taskbar when notifications are received",23
title: "Show message preview",30
detail: "On new messages, until you open the window",24
detail: "Off: only \"New message\"",31
field: |settings| &mut settings.flash,25
field: |settings| &mut settings.preview,32
};26
},27
Toggle {28
id: "settings-flash",29
title: "Flash taskbar when notifications are received",30
detail: "On new messages, until you open the window",31
field: |settings| &mut settings.flash,32
},33
];34
33
35
const NOTIFICATION_SOUND: Toggle = Toggle {34
const NOTIFICATION_SOUND: Toggle = Toggle {36
id: "settings-notification-sound",35
id: "settings-notification-sound",@@ -61,13 +60,6 @@ const CALL_SOUNDS: [Toggle; 2] = [61
},60
},62
];61
];63
62
64
const MENTIONS_ONLY: Toggle = Toggle {65
id: "settings-mentions-only",66
title: "Mentions only",67
detail: "Direct messages and @mentions",68
field: |settings| &mut settings.mentions_only,69
};70
71
const HIDE_IN_CALLS: Toggle = Toggle {63
const HIDE_IN_CALLS: Toggle = Toggle {72
id: "settings-hide-in-calls",64
id: "settings-hide-in-calls",73
title: "Hide notifications during calls and meetings",65
title: "Hide notifications during calls and meetings",@@ -75,7 +67,8 @@ const HIDE_IN_CALLS: Toggle = Toggle {75
field: |settings| &mut settings.mute_in_calls,67
field: |settings| &mut settings.mute_in_calls,76
};68
};77
69
78
pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {70
pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &App) -> Div {71
let account = app.read(cx).account_chat_settings().notifications;79
let mut current = center.read(cx).settings().clone();72
let mut current = center.read(cx).settings().clone();80
let corner = current.corner;73
let corner = current.corner;81
let sounds = current.sounds.clone();74
let sounds = current.sounds.clone();@@ -83,17 +76,17 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {83
let on = *(toggle.field)(&mut current);76
let on = *(toggle.field)(&mut current);84
toggle_element(center, toggle, on)77
toggle_element(center, toggle, on)85
};78
};86
let appearance: Vec<Stateful<Div>> = APPEARANCE.iter().map(&mut toggle).collect();79
let flash = toggle(&FLASH);87
let notification_sound = toggle(&NOTIFICATION_SOUND);80
let notification_sound = toggle(&NOTIFICATION_SOUND);88
let urgent_sound = toggle(&URGENT_SOUND);81
let urgent_sound = toggle(&URGENT_SOUND);89
let call_sounds: Vec<Stateful<Div>> = CALL_SOUNDS.iter().map(&mut toggle).collect();82
let call_sounds: Vec<Stateful<Div>> = CALL_SOUNDS.iter().map(&mut toggle).collect();90
let mentions_only = toggle(&MENTIONS_ONLY);91
let hide_in_calls = toggle(&HIDE_IN_CALLS);83
let hide_in_calls = toggle(&HIDE_IN_CALLS);92
let test_center = center.clone();84
let test_center = center.clone();93
v_flex()85
v_flex()94
.w_full()86
.w_full()95
.child(caption("APPEARANCE AND SOUND"))87
.child(caption("APPEARANCE AND SOUND"))96
.children(appearance)88
.child(preview_toggle(app, account.show_preview))89
.child(flash)97
.child(control_row(90
.child(control_row(98
"Position on the screen",91
"Position on the screen",99
"Corner of the main screen",92
"Corner of the main screen",@@ -141,12 +134,82 @@ pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {141
|settings| &mut settings.sounds.urgent_sound_type,134
|settings| &mut settings.sounds.urgent_sound_type,142
))135
))143
.children(call_sounds)136
.children(call_sounds)144
.child(caption("WHAT YOU GET NOTIFIED FOR"))137
.child(caption("TEAMS AND CHANNELS"))145
.child(mentions_only)138
.child(account_select(139
app,140
(141
"settings-notification-preset",142
"Teams and channels",143
preset_detail(account.preset),144
),145
&PRESETS,146
account.preset,147
ChatSettingChange::Preset,148
))149
.child(caption("CHAT"))150
.child(account_select(151
app,152
("settings-chat-messages", "Chat message notifications", ""),153
&CHAT_MESSAGES,154
account.chat_messages,155
ChatSettingChange::ChatMessages,156
))157
.child(account_select(158
app,159
("settings-personal-mentions", "Personal @mentions", ""),160
&MENTIONS,161
account.personal_mentions,162
ChatSettingChange::PersonalMentions,163
))164
.child(account_select(165
app,166
(167
"settings-everyone-mentions",168
"Everyone in chat @mentions",169
"",170
),171
&ACTIVITY_OR_OFF,172
account.everyone_mentions,173
ChatSettingChange::EveryoneMentions,174
))175
.child(account_select(176
app,177
("settings-likes", "Likes and reactions", ""),178
&ACTIVITY_OR_OFF,179
account.likes,180
ChatSettingChange::Likes,181
))146
.child(caption("MEETINGS AND CALLS"))182
.child(caption("MEETINGS AND CALLS"))183
.child(account_select(184
app,185
(186
"settings-meeting-chats",187
"Meeting chat notifications",188
meeting_chats_detail(account.meeting_chats),189
),190
&MEETING_CHATS,191
account.meeting_chats,192
ChatSettingChange::MeetingChats,193
))147
.child(hide_in_calls)194
.child(hide_in_calls)148
}195
}149
196
197
fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {198
let app = app.clone();199
toggle_row(200
"settings-preview",201
"Show message preview",202
"Off: only \"New message\"",203
theme::text_muted(),204
on,205
)206
.on_click(move |_, _, cx| {207
app.update(cx, |state, cx| {208
state.save_chat_setting(ChatSettingChange::ShowPreview(!on), cx)209
})210
})211
}212
150
fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {213
fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {151
let center = center.clone();214
let center = center.clone();152
let field = toggle.field;215
let field = toggle.field;@@ -162,6 +162,10 @@ pub fn text_button(id: impl Into<ElementId>, label: impl Into<SharedString>) ->
162
162
.child(label.into())
163
163
}
164
164
165
pub fn select_selector(id: &str) -> String {
166
format!("settings-select/{id}")
167
}
168
165
169
pub fn select(
166
170
id: impl Into<ElementId>,
167
171
label: impl Into<SharedString>,
@@ -179,7 +183,9 @@ pub fn select_with_width(
179
183
choices: Vec<Choice>,
180
184
) -> impl IntoElement {
181
185
let scrollable = choices.len() > SCROLL_MENU_AFTER;
182
Button::new(id)
186
let id: ElementId = id.into();
187
Button::new(id.clone())
188
.debug_selector(|| select_selector(&id.to_string()))
183
189
.outline()
184
190
.w(px(width))
185
191
.flex_none()
@@ -209,4 +215,5 @@ pub fn select_with_width(
209
215
)
210
216
})
211
217
})
218
.listbox()
212
219
}
@@ -162,6 +162,10 @@ pub fn text_button(id: impl Into<ElementId>, label: impl Into<SharedString>) ->162
.child(label.into())162
.child(label.into())163
}163
}164
164
165
pub fn select_selector(id: &str) -> String {166
format!("settings-select/{id}")167
}168
165
pub fn select(169
pub fn select(166
id: impl Into<ElementId>,170
id: impl Into<ElementId>,167
label: impl Into<SharedString>,171
label: impl Into<SharedString>,@@ -179,7 +183,9 @@ pub fn select_with_width(179
choices: Vec<Choice>,183
choices: Vec<Choice>,180
) -> impl IntoElement {184
) -> impl IntoElement {181
let scrollable = choices.len() > SCROLL_MENU_AFTER;185
let scrollable = choices.len() > SCROLL_MENU_AFTER;182
Button::new(id)186
let id: ElementId = id.into();187
Button::new(id.clone())188
.debug_selector(|| select_selector(&id.to_string()))183
.outline()189
.outline()184
.w(px(width))190
.w(px(width))185
.flex_none()191
.flex_none()@@ -209,4 +215,5 @@ pub fn select_with_width(209
)215
)210
})216
})211
})217
})218
.listbox()212
}219
}@@ -1,4 +1,5 @@
1
1
use std::collections::{HashMap, HashSet};
2
use std::rc::Rc;
2
3
3
4
use chrono::{DateTime, Local, NaiveDate, Offset};
4
5
use gpui_kit::assets::IconName;
@@ -12,6 +13,10 @@ use super::scroll_edge::with_top_edge;
12
13
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
13
14
use super::widgets::{Corner, corner_badge, dot, icon};
14
15
use crate::activity::{ActivityCenter, Entry, Filter, Kind};
16
use crate::agent_api::{
17
self,
18
pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
19
};
15
20
use crate::app_state::{AppState, chat_title};
16
21
use crate::data::is_one_on_one;
17
22
use crate::format;
@@ -23,6 +28,8 @@ const KIND_MARKER_SIZE: f32 = 16.;
23
28
const BUTTON_SIZE: f32 = 32.;
24
29
const MARK_READ_SIZE: f32 = 20.;
25
30
const FILTER_KEY: &str = "activity_filter";
31
const PROPOSALS_LABEL: &str = "Agent proposals";
32
pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
26
33
27
34
pub enum ActivityPanelEvent {
28
35
OpenSettings,
@@ -185,92 +192,181 @@ impl ActivityPanel {
185
192
) -> AnyElement {
186
193
let activity = self.activity.clone();
187
194
let id = entry.id;
188
let resolved_names = &self.resolved_names;
189
let unread = !entry.read;
190
195
let actor = entry.latest_actor();
191
196
let avatar = person_avatar(
192
197
directory,
193
198
actor.and_then(|actor| actor.user_id.as_deref()),
194
actor.map_or("", |actor| actor.display_name(resolved_names)),
199
actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
195
200
AVATAR_SIZE,
196
201
);
197
202
let group = SharedString::from(format!("activity-row-group-{id}"));
198
h_flex()
199
.id(ElementId::Name(format!("activity-row-{id}").into()))
200
.debug_selector(|| format!("activity-row-{id}"))
201
.group(group.clone())
202
.mx(px(6.))
203
.px(px(10.))
204
.py(px(8.))
205
.gap(px(12.))
206
.items_start()
207
.rounded(px(8.))
208
.cursor_pointer()
209
.hover(|row| row.bg(theme::row_hover()))
210
.child(
211
div()
212
.relative()
213
.flex_none()
214
.size(px(AVATAR_SIZE))
215
.child(avatar)
216
.child(kind_marker(entry, group.clone())),
217
)
218
.child(
219
v_flex()
220
.flex_1()
221
.min_w_0()
222
.gap(px(2.))
223
.child(
224
div()
225
.truncate()
226
.text_size(px(13.))
227
.font_weight(if unread {
228
FontWeight::SEMIBOLD
229
} else {
230
FontWeight::NORMAL
231
})
232
.text_color(if unread {
233
theme::text()
234
} else {
235
theme::text_soft()
236
})
237
.child(headline(entry, sidebar, resolved_names)),
238
)
239
.child(
240
div()
241
.truncate()
242
.text_size(px(12.))
243
.text_color(if unread {
244
theme::text_soft()
245
} else {
246
theme::text_muted()
247
})
248
.child(detail(entry)),
249
),
250
)
251
.child(
252
v_flex()
253
.flex_none()
254
.items_end()
255
.child(
256
div()
257
.text_size(px(11.))
258
.text_color(theme::text_muted())
259
.child(format::list_time_label(entry.updated_at, today, offset)),
260
)
261
.child(status_slot(id, unread, group, activity)),
262
)
263
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
264
.into_any_element()
203
row_frame(RowParts {
204
element_id: format!("activity-row-{id}"),
205
avatar: avatar.into_any_element(),
206
marker: kind_marker(entry, group.clone()),
207
group,
208
headline: headline(entry, sidebar, &self.resolved_names),
209
detail: detail(entry),
210
unread: !entry.read,
211
time: format::list_time_label(entry.updated_at, today, offset),
212
mark_read: Rc::new(move |cx: &mut App| {
213
activity.update(cx, |activity, cx| activity.mark_read(id, cx))
214
}),
215
})
216
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
217
.into_any_element()
218
}
219
220
fn proposal_row(
221
&self,
222
pending: &PendingProposal,
223
sidebar: &Sidebar,
224
today: NaiveDate,
225
offset: chrono::FixedOffset,
226
panel: Entity<ActivityPanel>,
227
) -> AnyElement {
228
let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
229
let label = proposal_conversation_label(sidebar, &pending.conversation_id);
230
let proposal_id = pending.id.clone();
231
let opened = pending.clone();
232
row_frame(RowParts {
233
element_id: format!("activity-proposal-{}", pending.id),
234
avatar: agent_avatar().into_any_element(),
235
marker: proposal_marker(pending, group.clone()),
236
group,
237
headline: pending.headline(label.as_deref()),
238
detail: pending.detail(),
239
unread: !pending.seen,
240
time: format::list_time_label(pending.created_at, today, offset),
241
mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
242
})
243
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
244
.into_any_element()
245
}
246
247
fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
248
agent_api::mark_proposal_seen(&pending.id, cx);
249
cx.emit(ActivityPanelEvent::Open {
250
conversation_id: pending.conversation_id.clone(),
251
message_id: pending.jump_message_id().to_owned(),
252
});
265
253
}
266
254
}
267
255
268
fn status_slot(
269
id: i64,
270
unread: bool,
256
struct RowParts {
257
element_id: String,
271
258
group: SharedString,
272
activity: Entity<ActivityCenter>,
273
) -> Div {
259
avatar: AnyElement,
260
marker: Div,
261
headline: String,
262
detail: String,
263
unread: bool,
264
time: String,
265
mark_read: MarkRead,
266
}
267
268
type MarkRead = Rc<dyn Fn(&mut App)>;
269
270
fn row_frame(parts: RowParts) -> Stateful<Div> {
271
let RowParts {
272
element_id,
273
group,
274
avatar,
275
marker,
276
headline,
277
detail,
278
unread,
279
time,
280
mark_read,
281
} = parts;
282
let selector = element_id.clone();
283
h_flex()
284
.id(ElementId::Name(element_id.clone().into()))
285
.debug_selector(move || selector)
286
.group(group.clone())
287
.mx(px(6.))
288
.px(px(10.))
289
.py(px(8.))
290
.gap(px(12.))
291
.items_start()
292
.rounded(px(8.))
293
.cursor_pointer()
294
.hover(|row| row.bg(theme::row_hover()))
295
.child(
296
div()
297
.relative()
298
.flex_none()
299
.size(px(AVATAR_SIZE))
300
.child(avatar)
301
.child(marker),
302
)
303
.child(
304
v_flex()
305
.flex_1()
306
.min_w_0()
307
.gap(px(2.))
308
.child(
309
div()
310
.truncate()
311
.text_size(px(13.))
312
.font_weight(if unread {
313
FontWeight::SEMIBOLD
314
} else {
315
FontWeight::NORMAL
316
})
317
.text_color(if unread {
318
theme::text()
319
} else {
320
theme::text_soft()
321
})
322
.child(headline),
323
)
324
.child(
325
div()
326
.truncate()
327
.text_size(px(12.))
328
.text_color(if unread {
329
theme::text_soft()
330
} else {
331
theme::text_muted()
332
})
333
.child(detail),
334
),
335
)
336
.child(
337
v_flex()
338
.flex_none()
339
.items_end()
340
.child(
341
div()
342
.text_size(px(11.))
343
.text_color(theme::text_muted())
344
.child(time),
345
)
346
.child(status_slot(element_id, unread, group, mark_read)),
347
)
348
}
349
350
fn agent_avatar() -> Div {
351
div()
352
.size(px(AVATAR_SIZE))
353
.flex()
354
.items_center()
355
.justify_center()
356
.rounded_full()
357
.bg(theme::accent_soft())
358
.child(icon(IconName::Bot, 16., theme::accent_text()))
359
}
360
361
fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
362
match filter {
363
Filter::All => true,
364
Filter::Mentions => false,
365
Filter::Unread => !pending.seen,
366
}
367
}
368
369
fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
274
370
let slot = div()
275
371
.h(px(MARK_READ_SIZE))
276
372
.flex()
@@ -292,7 +388,7 @@ fn status_slot(
292
388
)
293
389
.child(
294
390
div()
295
.id(ElementId::Name(format!("activity-mark-read-{id}").into()))
391
.id(ElementId::Name(format!("{element_id}-mark-read").into()))
296
392
.absolute()
297
393
.top_0()
298
394
.right_0()
@@ -309,13 +405,13 @@ fn status_slot(
309
405
.tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
310
406
.on_click(move |_, _, cx| {
311
407
cx.stop_propagation();
312
activity.update(cx, |activity, cx| activity.mark_read(id, cx));
408
mark_read(cx);
313
409
}),
314
410
)
315
411
}
316
412
317
fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
318
let marker = corner_badge(Corner::BottomRight, 4.)
413
fn marker_frame(row_group: SharedString) -> Div {
414
corner_badge(Corner::BottomRight, 4.)
319
415
.size(px(KIND_MARKER_SIZE))
320
416
.flex()
321
417
.items_center()
@@ -325,7 +421,21 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
325
421
.border_color(theme::surface())
326
422
.group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
327
423
.bg(theme::surface_raised())
328
.text_size(px(10.));
424
.text_size(px(10.))
425
}
426
427
fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
428
let marker = marker_frame(row_group);
429
match &pending.kind {
430
PendingKind::Reply { .. } => {
431
marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
432
}
433
PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
434
}
435
}
436
437
fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438
let marker = marker_frame(row_group);
329
439
match entry.kind {
330
440
Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
331
441
Kind::Mention => marker
@@ -374,7 +484,7 @@ fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String
374
484
})
375
485
}
376
486
377
fn date_header(label: &'static str) -> AnyElement {
487
fn group_header(label: &'static str) -> Div {
378
488
div()
379
489
.h(px(26.))
380
490
.mt(px(4.))
@@ -386,7 +496,6 @@ fn date_header(label: &'static str) -> AnyElement {
386
496
.font_weight(FontWeight::SEMIBOLD)
387
497
.text_color(theme::text_muted())
388
498
.child(label)
389
.into_any_element()
390
499
}
391
500
392
501
impl Render for ActivityPanel {
@@ -414,8 +523,22 @@ impl Render for ActivityPanel {
414
523
.extend(resolve_names(state, &unresolved));
415
524
}
416
525
let mut rows: Vec<AnyElement> = Vec::new();
526
let proposal_rows: Vec<AnyElement> = agent_api::pending_proposals(cx)
527
.iter()
528
.filter(|pending| admits_proposal(self.filter, pending))
529
.map(|pending| self.proposal_row(pending, &state.sidebar, today, offset, panel.clone()))
530
.collect();
531
if !proposal_rows.is_empty() {
532
rows.push(
533
v_flex()
534
.debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
535
.child(group_header(PROPOSALS_LABEL))
536
.children(proposal_rows)
537
.into_any_element(),
538
);
539
}
417
540
for section in sections {
418
rows.push(date_header(section.bucket.label()));
541
rows.push(group_header(section.bucket.label()).into_any_element());
419
542
for entry in section.entries {
420
543
rows.push(self.row(
421
544
entry,
@@ -1,4 +1,5 @@1
use std::collections::{HashMap, HashSet};1
use std::collections::{HashMap, HashSet};2
use std::rc::Rc;2
3
3
use chrono::{DateTime, Local, NaiveDate, Offset};4
use chrono::{DateTime, Local, NaiveDate, Offset};4
use gpui_kit::assets::IconName;5
use gpui_kit::assets::IconName;@@ -12,6 +13,10 @@ use super::scroll_edge::with_top_edge;12
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;13
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;13
use super::widgets::{Corner, corner_badge, dot, icon};14
use super::widgets::{Corner, corner_badge, dot, icon};14
use crate::activity::{ActivityCenter, Entry, Filter, Kind};15
use crate::activity::{ActivityCenter, Entry, Filter, Kind};16
use crate::agent_api::{17
self,18
pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},19
};15
use crate::app_state::{AppState, chat_title};20
use crate::app_state::{AppState, chat_title};16
use crate::data::is_one_on_one;21
use crate::data::is_one_on_one;17
use crate::format;22
use crate::format;@@ -23,6 +28,8 @@ const KIND_MARKER_SIZE: f32 = 16.;23
const BUTTON_SIZE: f32 = 32.;28
const BUTTON_SIZE: f32 = 32.;24
const MARK_READ_SIZE: f32 = 20.;29
const MARK_READ_SIZE: f32 = 20.;25
const FILTER_KEY: &str = "activity_filter";30
const FILTER_KEY: &str = "activity_filter";31
const PROPOSALS_LABEL: &str = "Agent proposals";32
pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";26
33
27
pub enum ActivityPanelEvent {34
pub enum ActivityPanelEvent {28
OpenSettings,35
OpenSettings,@@ -185,92 +192,181 @@ impl ActivityPanel {185
) -> AnyElement {192
) -> AnyElement {186
let activity = self.activity.clone();193
let activity = self.activity.clone();187
let id = entry.id;194
let id = entry.id;188
let resolved_names = &self.resolved_names;189
let unread = !entry.read;190
let actor = entry.latest_actor();195
let actor = entry.latest_actor();191
let avatar = person_avatar(196
let avatar = person_avatar(192
directory,197
directory,193
actor.and_then(|actor| actor.user_id.as_deref()),198
actor.and_then(|actor| actor.user_id.as_deref()),194
actor.map_or("", |actor| actor.display_name(resolved_names)),199
actor.map_or("", |actor| actor.display_name(&self.resolved_names)),195
AVATAR_SIZE,200
AVATAR_SIZE,196
);201
);197
let group = SharedString::from(format!("activity-row-group-{id}"));202
let group = SharedString::from(format!("activity-row-group-{id}"));198
h_flex()203
row_frame(RowParts {199
.id(ElementId::Name(format!("activity-row-{id}").into()))204
element_id: format!("activity-row-{id}"),200
.debug_selector(|| format!("activity-row-{id}"))205
avatar: avatar.into_any_element(),201
.group(group.clone())206
marker: kind_marker(entry, group.clone()),202
.mx(px(6.))207
group,203
.px(px(10.))208
headline: headline(entry, sidebar, &self.resolved_names),204
.py(px(8.))209
detail: detail(entry),205
.gap(px(12.))210
unread: !entry.read,206
.items_start()211
time: format::list_time_label(entry.updated_at, today, offset),207
.rounded(px(8.))212
mark_read: Rc::new(move |cx: &mut App| {208
.cursor_pointer()213
activity.update(cx, |activity, cx| activity.mark_read(id, cx))209
.hover(|row| row.bg(theme::row_hover()))214
}),210
.child(215
})211
div()216
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))212
.relative()217
.into_any_element()213
.flex_none()218
}214
.size(px(AVATAR_SIZE))219
215
.child(avatar)220
fn proposal_row(216
.child(kind_marker(entry, group.clone())),221
&self,217
)222
pending: &PendingProposal,218
.child(223
sidebar: &Sidebar,219
v_flex()224
today: NaiveDate,220
.flex_1()225
offset: chrono::FixedOffset,221
.min_w_0()226
panel: Entity<ActivityPanel>,222
.gap(px(2.))227
) -> AnyElement {223
.child(228
let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));224
div()229
let label = proposal_conversation_label(sidebar, &pending.conversation_id);225
.truncate()230
let proposal_id = pending.id.clone();226
.text_size(px(13.))231
let opened = pending.clone();227
.font_weight(if unread {232
row_frame(RowParts {228
FontWeight::SEMIBOLD233
element_id: format!("activity-proposal-{}", pending.id),229
} else {234
avatar: agent_avatar().into_any_element(),230
FontWeight::NORMAL235
marker: proposal_marker(pending, group.clone()),231
})236
group,232
.text_color(if unread {237
headline: pending.headline(label.as_deref()),233
theme::text()238
detail: pending.detail(),234
} else {239
unread: !pending.seen,235
theme::text_soft()240
time: format::list_time_label(pending.created_at, today, offset),236
})241
mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),237
.child(headline(entry, sidebar, resolved_names)),242
})238
)243
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))239
.child(244
.into_any_element()240
div()245
}241
.truncate()246
242
.text_size(px(12.))247
fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {243
.text_color(if unread {248
agent_api::mark_proposal_seen(&pending.id, cx);244
theme::text_soft()249
cx.emit(ActivityPanelEvent::Open {245
} else {250
conversation_id: pending.conversation_id.clone(),246
theme::text_muted()251
message_id: pending.jump_message_id().to_owned(),247
})252
});248
.child(detail(entry)),249
),250
)251
.child(252
v_flex()253
.flex_none()254
.items_end()255
.child(256
div()257
.text_size(px(11.))258
.text_color(theme::text_muted())259
.child(format::list_time_label(entry.updated_at, today, offset)),260
)261
.child(status_slot(id, unread, group, activity)),262
)263
.on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))264
.into_any_element()265
}253
}266
}254
}267
255
268
fn status_slot(256
struct RowParts {269
id: i64,257
element_id: String,270
unread: bool,271
group: SharedString,258
group: SharedString,272
activity: Entity<ActivityCenter>,259
avatar: AnyElement,273
) -> Div {260
marker: Div,261
headline: String,262
detail: String,263
unread: bool,264
time: String,265
mark_read: MarkRead,266
}267
268
type MarkRead = Rc<dyn Fn(&mut App)>;269
270
fn row_frame(parts: RowParts) -> Stateful<Div> {271
let RowParts {272
element_id,273
group,274
avatar,275
marker,276
headline,277
detail,278
unread,279
time,280
mark_read,281
} = parts;282
let selector = element_id.clone();283
h_flex()284
.id(ElementId::Name(element_id.clone().into()))285
.debug_selector(move || selector)286
.group(group.clone())287
.mx(px(6.))288
.px(px(10.))289
.py(px(8.))290
.gap(px(12.))291
.items_start()292
.rounded(px(8.))293
.cursor_pointer()294
.hover(|row| row.bg(theme::row_hover()))295
.child(296
div()297
.relative()298
.flex_none()299
.size(px(AVATAR_SIZE))300
.child(avatar)301
.child(marker),302
)303
.child(304
v_flex()305
.flex_1()306
.min_w_0()307
.gap(px(2.))308
.child(309
div()310
.truncate()311
.text_size(px(13.))312
.font_weight(if unread {313
FontWeight::SEMIBOLD314
} else {315
FontWeight::NORMAL316
})317
.text_color(if unread {318
theme::text()319
} else {320
theme::text_soft()321
})322
.child(headline),323
)324
.child(325
div()326
.truncate()327
.text_size(px(12.))328
.text_color(if unread {329
theme::text_soft()330
} else {331
theme::text_muted()332
})333
.child(detail),334
),335
)336
.child(337
v_flex()338
.flex_none()339
.items_end()340
.child(341
div()342
.text_size(px(11.))343
.text_color(theme::text_muted())344
.child(time),345
)346
.child(status_slot(element_id, unread, group, mark_read)),347
)348
}349
350
fn agent_avatar() -> Div {351
div()352
.size(px(AVATAR_SIZE))353
.flex()354
.items_center()355
.justify_center()356
.rounded_full()357
.bg(theme::accent_soft())358
.child(icon(IconName::Bot, 16., theme::accent_text()))359
}360
361
fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {362
match filter {363
Filter::All => true,364
Filter::Mentions => false,365
Filter::Unread => !pending.seen,366
}367
}368
369
fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {274
let slot = div()370
let slot = div()275
.h(px(MARK_READ_SIZE))371
.h(px(MARK_READ_SIZE))276
.flex()372
.flex()@@ -292,7 +388,7 @@ fn status_slot(292
)388
)293
.child(389
.child(294
div()390
div()295
.id(ElementId::Name(format!("activity-mark-read-{id}").into()))391
.id(ElementId::Name(format!("{element_id}-mark-read").into()))296
.absolute()392
.absolute()297
.top_0()393
.top_0()298
.right_0()394
.right_0()@@ -309,13 +405,13 @@ fn status_slot(309
.tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))405
.tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))310
.on_click(move |_, _, cx| {406
.on_click(move |_, _, cx| {311
cx.stop_propagation();407
cx.stop_propagation();312
activity.update(cx, |activity, cx| activity.mark_read(id, cx));408
mark_read(cx);313
}),409
}),314
)410
)315
}411
}316
412
317
fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {413
fn marker_frame(row_group: SharedString) -> Div {318
let marker = corner_badge(Corner::BottomRight, 4.)414
corner_badge(Corner::BottomRight, 4.)319
.size(px(KIND_MARKER_SIZE))415
.size(px(KIND_MARKER_SIZE))320
.flex()416
.flex()321
.items_center()417
.items_center()@@ -325,7 +421,21 @@ fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {325
.border_color(theme::surface())421
.border_color(theme::surface())326
.group_hover(row_group, |marker| marker.border_color(theme::row_hover()))422
.group_hover(row_group, |marker| marker.border_color(theme::row_hover()))327
.bg(theme::surface_raised())423
.bg(theme::surface_raised())328
.text_size(px(10.));424
.text_size(px(10.))425
}426
427
fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {428
let marker = marker_frame(row_group);429
match &pending.kind {430
PendingKind::Reply { .. } => {431
marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))432
}433
PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),434
}435
}436
437
fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {438
let marker = marker_frame(row_group);329
match entry.kind {439
match entry.kind {330
Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),440
Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),331
Kind::Mention => marker441
Kind::Mention => marker@@ -374,7 +484,7 @@ fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String374
})484
})375
}485
}376
486
377
fn date_header(label: &'static str) -> AnyElement {487
fn group_header(label: &'static str) -> Div {378
div()488
div()379
.h(px(26.))489
.h(px(26.))380
.mt(px(4.))490
.mt(px(4.))@@ -386,7 +496,6 @@ fn date_header(label: &'static str) -> AnyElement {386
.font_weight(FontWeight::SEMIBOLD)496
.font_weight(FontWeight::SEMIBOLD)387
.text_color(theme::text_muted())497
.text_color(theme::text_muted())388
.child(label)498
.child(label)389
.into_any_element()390
}499
}391
500
392
impl Render for ActivityPanel {501
impl Render for ActivityPanel {@@ -414,8 +523,22 @@ impl Render for ActivityPanel {414
.extend(resolve_names(state, &unresolved));523
.extend(resolve_names(state, &unresolved));415
}524
}416
let mut rows: Vec<AnyElement> = Vec::new();525
let mut rows: Vec<AnyElement> = Vec::new();526
let proposal_rows: Vec<AnyElement> = agent_api::pending_proposals(cx)527
.iter()528
.filter(|pending| admits_proposal(self.filter, pending))529
.map(|pending| self.proposal_row(pending, &state.sidebar, today, offset, panel.clone()))530
.collect();531
if !proposal_rows.is_empty() {532
rows.push(533
v_flex()534
.debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())535
.child(group_header(PROPOSALS_LABEL))536
.children(proposal_rows)537
.into_any_element(),538
);539
}417
for section in sections {540
for section in sections {418
rows.push(date_header(section.bucket.label()));541
rows.push(group_header(section.bucket.label()).into_any_element());419
for entry in section.entries {542
for entry in section.entries {420
rows.push(self.row(543
rows.push(self.row(421
entry,544
entry,@@ -13,7 +13,7 @@ use super::join_dialog::open_join_with_id;
13
13
use super::new_meeting_dialog::open_new_meeting;
14
14
use super::scroll_edge::with_top_edge;
15
15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
16
use super::widgets::icon;
16
use super::widgets::{icon, menu_icon};
17
17
use crate::app_state::AppState;
18
18
use crate::call::{
19
19
AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
@@ -25,7 +25,6 @@ const FALLBACK_VIEWPORT: f32 = 900.;
25
25
const VIEWPORT_MARGIN: f32 = 300.;
26
26
const TIME_COLUMN_WIDTH: f32 = 96.;
27
27
const AVATAR_SIZE: f32 = 36.;
28
const MENU_ICON_SIZE: f32 = 15.;
29
28
30
29
fn meeting_avatar() -> Div {
31
30
div()
@@ -122,7 +121,7 @@ fn call_row(
122
121
.when(can_call_back, |popup| {
123
122
popup.item(
124
123
PopupMenuItem::new("Call back")
125
.icon(icon(IconName::Phone, MENU_ICON_SIZE, theme::text_muted()))
124
.icon(menu_icon(IconName::Phone))
126
125
.on_click(move |_, _, cx| {
127
126
call_state.update(cx, |state, cx| {
128
127
state.call_back_from_history(&call_row, cx)
@@ -133,11 +132,7 @@ fn call_row(
133
132
.when(can_open_chat, |popup| {
134
133
popup.item(
135
134
PopupMenuItem::new("Open chat")
136
.icon(icon(
137
IconName::MessageSquare,
138
MENU_ICON_SIZE,
139
theme::text_muted(),
140
))
135
.icon(menu_icon(IconName::MessageSquare))
141
136
.on_click(move |_, _, cx| {
142
137
chat_state.update(cx, |state, cx| {
143
138
state.open_chat_of_call_row(&chat_row, cx)
@@ -13,7 +13,7 @@ use super::join_dialog::open_join_with_id;13
use super::new_meeting_dialog::open_new_meeting;13
use super::new_meeting_dialog::open_new_meeting;14
use super::scroll_edge::with_top_edge;14
use super::scroll_edge::with_top_edge;15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;15
use super::sidebar::SIDEBAR_SCROLL_DIVIDER;16
use super::widgets::icon;16
use super::widgets::{icon, menu_icon};17
use crate::app_state::AppState;17
use crate::app_state::AppState;18
use crate::call::{18
use crate::call::{19
AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,19
AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,@@ -25,7 +25,6 @@ const FALLBACK_VIEWPORT: f32 = 900.;25
const VIEWPORT_MARGIN: f32 = 300.;25
const VIEWPORT_MARGIN: f32 = 300.;26
const TIME_COLUMN_WIDTH: f32 = 96.;26
const TIME_COLUMN_WIDTH: f32 = 96.;27
const AVATAR_SIZE: f32 = 36.;27
const AVATAR_SIZE: f32 = 36.;28
const MENU_ICON_SIZE: f32 = 15.;29
28
30
fn meeting_avatar() -> Div {29
fn meeting_avatar() -> Div {31
div()30
div()@@ -122,7 +121,7 @@ fn call_row(122
.when(can_call_back, |popup| {121
.when(can_call_back, |popup| {123
popup.item(122
popup.item(124
PopupMenuItem::new("Call back")123
PopupMenuItem::new("Call back")125
.icon(icon(IconName::Phone, MENU_ICON_SIZE, theme::text_muted()))124
.icon(menu_icon(IconName::Phone))126
.on_click(move |_, _, cx| {125
.on_click(move |_, _, cx| {127
call_state.update(cx, |state, cx| {126
call_state.update(cx, |state, cx| {128
state.call_back_from_history(&call_row, cx)127
state.call_back_from_history(&call_row, cx)@@ -133,11 +132,7 @@ fn call_row(133
.when(can_open_chat, |popup| {132
.when(can_open_chat, |popup| {134
popup.item(133
popup.item(135
PopupMenuItem::new("Open chat")134
PopupMenuItem::new("Open chat")136
.icon(icon(135
.icon(menu_icon(IconName::MessageSquare))137
IconName::MessageSquare,138
MENU_ICON_SIZE,139
theme::text_muted(),140
))141
.on_click(move |_, _, cx| {136
.on_click(move |_, _, cx| {142
chat_state.update(cx, |state, cx| {137
chat_state.update(cx, |state, cx| {143
state.open_chat_of_call_row(&chat_row, cx)138
state.open_chat_of_call_row(&chat_row, cx)@@ -24,11 +24,13 @@ use gpui_kit::component::{
24
24
use gpui_kit::prelude::FluentBuilder as _;
25
25
use gpui_kit::*;
26
26
use teams_core::{
27
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,
28
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,
29
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
27
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,
28
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,
29
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,
30
reverse_edits,
30
31
};
31
32
33
pub(crate) mod delivery;
32
34
mod drafts;
33
35
mod schedule;
34
36
mod table;
@@ -120,6 +122,7 @@ pub enum ComposerEvent {
120
122
send_at: DateTime<Utc>,
121
123
},
122
124
EditLast,
125
FocusMessages,
123
126
Typing(bool),
124
127
}
125
128
@@ -225,11 +228,26 @@ pub struct Composer {
225
228
active_cell: Option<(String, teams_core::Cell)>,
226
229
caret_before_table: usize,
227
230
caret_text: String,
231
importance: store::MessageImportance,
232
delivery_menu: bool,
228
233
_subscriptions: [Subscription; 4],
229
234
}
230
235
231
236
impl EventEmitter<ComposerEvent> for Composer {}
232
237
238
/// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.
239
pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {
240
behavior == EnterKeyBehavior::NewLine && !shift && !secondary
241
}
242
243
pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {
244
match behavior {
245
UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),
246
UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),
247
UpArrowBehavior::StayInCompose => None,
248
}
249
}
250
233
251
pub fn is_plain_enter(event: &InputEvent) -> bool {
234
252
matches!(event, InputEvent::PressEnter { shift: false, .. })
235
253
}
@@ -436,6 +454,8 @@ impl Composer {
436
454
active_cell: None,
437
455
caret_before_table: 0,
438
456
caret_text: String::new(),
457
importance: store::MessageImportance::Normal,
458
delivery_menu: false,
439
459
_subscriptions: [subscription, observer, image_observer, picker_subscription],
440
460
}
441
461
}
@@ -536,7 +556,10 @@ impl Composer {
536
556
return;
537
557
}
538
558
let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
539
if typed.is_some() && self.convert_markdown(cursor, window, cx) {
559
if typed.is_some()
560
&& !self.app.read(cx).markdown_mode
561
&& self.convert_markdown(cursor, window, cx)
562
{
540
563
return;
541
564
}
542
565
if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
@@ -1637,6 +1660,7 @@ impl Composer {
1637
1660
self.schedule = None;
1638
1661
self.table_picker = None;
1639
1662
self.table_menu = None;
1663
self.reset_importance();
1640
1664
if !carry {
1641
1665
self.load_stored_draft(conversation_id, window, cx);
1642
1666
}
@@ -1706,12 +1730,15 @@ impl Composer {
1706
1730
draft.replace(range, glyph);
1707
1731
draft.take_edits();
1708
1732
}
1709
let mentions = state
1733
let mentions: Vec<MentionInput> = state
1710
1734
.tokens()
1711
1735
.iter()
1712
1736
.filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1713
1737
.cloned()
1714
1738
.collect();
1739
if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {
1740
draft = Draft::from_markdown(draft.text());
1741
}
1715
1742
Outgoing {
1716
1743
draft,
1717
1744
subject: None,
@@ -1729,6 +1756,7 @@ impl Composer {
1729
1756
} else {
1730
1757
Vec::new()
1731
1758
},
1759
importance: self.sendable_importance(cx),
1732
1760
}
1733
1761
}
1734
1762
@@ -2205,6 +2233,7 @@ impl Composer {
2205
2233
self.editing = None;
2206
2234
self.link.reset();
2207
2235
self.close_popup();
2236
self.reset_importance();
2208
2237
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
2209
2238
cx.notify();
2210
2239
}
@@ -2426,7 +2455,10 @@ impl Composer {
2426
2455
2427
2456
fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2428
2457
let composer = cx.entity().downgrade();
2429
let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();
2458
let floating = focused
2459
&& self.toolbar_requested(cx)
2460
&& !self.format_bar_open()
2461
&& !self.app.read(cx).markdown_mode;
2430
2462
if self.link_editor.is_none() && !floating {
2431
2463
return None;
2432
2464
}
@@ -2729,36 +2761,39 @@ impl Render for Composer {
2729
2761
))
2730
2762
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2731
2763
});
2732
let format_open = self.format_bar_open();
2733
let format_toggle = div()
2734
.id("composer-format")
2735
.debug_selector(|| COMPOSER_FORMAT_TAG.into())
2736
.size(px(COMPOSER_BUTTON_SIZE))
2737
.flex_none()
2738
.flex()
2739
.items_center()
2740
.justify_center()
2741
.rounded(px(8.))
2742
.cursor_pointer()
2743
.when(format_open, |button| button.bg(theme::popup_hover()))
2744
.hover(|button| button.bg(theme::popup_hover()))
2745
.tooltip(move |window, cx| {
2746
Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2747
})
2748
.child(symbol(
2749
format_toolbar::toggle_symbol(format_open),
2750
COMPOSER_ICON_SIZE,
2751
if format_open {
2752
theme::accent_soft()
2753
} else {
2754
theme::text_muted()
2755
},
2756
))
2757
.on_mouse_down(MouseButton::Left, |_, window, cx| {
2758
window.prevent_default();
2759
cx.stop_propagation();
2760
})
2761
.on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)));
2764
let markdown_mode = self.app.read(cx).markdown_mode;
2765
let format_open = self.format_bar_open() && !markdown_mode;
2766
let format_toggle = (!markdown_mode).then(|| {
2767
div()
2768
.id("composer-format")
2769
.debug_selector(|| COMPOSER_FORMAT_TAG.into())
2770
.size(px(COMPOSER_BUTTON_SIZE))
2771
.flex_none()
2772
.flex()
2773
.items_center()
2774
.justify_center()
2775
.rounded(px(8.))
2776
.cursor_pointer()
2777
.when(format_open, |button| button.bg(theme::popup_hover()))
2778
.hover(|button| button.bg(theme::popup_hover()))
2779
.tooltip(move |window, cx| {
2780
Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2781
})
2782
.child(symbol(
2783
format_toolbar::toggle_symbol(format_open),
2784
COMPOSER_ICON_SIZE,
2785
if format_open {
2786
theme::accent_soft()
2787
} else {
2788
theme::text_muted()
2789
},
2790
))
2791
.on_mouse_down(MouseButton::Left, |_, window, cx| {
2792
window.prevent_default();
2793
cx.stop_propagation();
2794
})
2795
.on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
2796
});
2762
2797
let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2763
2798
let composer = cx.weak_entity();
2764
2799
let tokens_composer = composer.clone();
@@ -2979,8 +3014,12 @@ impl Render for Composer {
2979
3014
} else if this.popup_is_open() {
2980
3015
this.move_highlight(-1, cx);
2981
3016
cx.stop_propagation();
2982
} else if this.editing.is_none() && this.is_empty(cx) {
2983
cx.emit(ComposerEvent::EditLast);
3017
} else if this.editing.is_none()
3018
&& this.is_empty(cx)
3019
&& let Some(event) =
3020
up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3021
{
3022
cx.emit(event);
2984
3023
cx.stop_propagation();
2985
3024
}
2986
3025
}))
@@ -3026,6 +3065,19 @@ impl Render for Composer {
3026
3065
} else if this.popup_is_open() {
3027
3066
this.accept_popup(window, cx);
3028
3067
cx.stop_propagation();
3068
} else if enter_starts_line(
3069
this.app.read(cx).account_chat_settings().enter_key,
3070
action.shift,
3071
action.secondary,
3072
) {
3073
cx.stop_propagation();
3074
window.dispatch_action(
3075
Box::new(Enter {
3076
secondary: false,
3077
shift: true,
3078
}),
3079
cx,
3080
);
3029
3081
} else if this.break_line(action.shift, window, cx) {
3030
3082
cx.stop_propagation();
3031
3083
}
@@ -3104,6 +3156,7 @@ impl Render for Composer {
3104
3156
.children(notice)
3105
3157
.children(self.render_reply_strip(cx))
3106
3158
.children(self.render_edit_strip(cx))
3159
.children(self.render_urgent_banner(cx))
3107
3160
.children(self.render_meeting_chip())
3108
3161
.children(self.render_link_preview(cx))
3109
3162
.child(
@@ -3114,6 +3167,7 @@ impl Render for Composer {
3114
3167
.children(self.render_emoji_popup(window, cx))
3115
3168
.children(self.render_toolbar(focused, cx))
3116
3169
.children(self.render_schedule(cx))
3170
.children(self.render_delivery_menu(cx))
3117
3171
.child(
3118
3172
v_flex()
3119
3173
.debug_selector(|| COMPOSER_BOX_TAG.into())
@@ -3136,6 +3190,7 @@ impl Render for Composer {
3136
3190
.size_full(),
3137
3191
)
3138
3192
.children(format_bar)
3193
.children(self.render_importance_label(cx))
3139
3194
.children(tray)
3140
3195
.child(
3141
3196
h_flex()
@@ -3154,7 +3209,8 @@ impl Render for Composer {
3154
3209
.debug_selector(|| COMPOSER_LEADING_TAG.into())
3155
3210
.flex_none()
3156
3211
.gap(px(COMPOSER_BUTTON_INSET))
3157
.child(format_toggle)
3212
.children(format_toggle)
3213
.children(self.render_delivery_button(cx))
3158
3214
.children(fun)
3159
3215
.children(attach),
3160
3216
)
@@ -3194,7 +3250,31 @@ impl Render for Composer {
3194
3250
3195
3251
#[cfg(test)]
3196
3252
mod tests {
3197
use super::{active_mention, submitted_text};
3253
use super::{
3254
ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,
3255
submitted_text, up_arrow_event,
3256
};
3257
3258
#[test]
3259
fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3260
assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3261
assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3262
assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3263
assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3264
}
3265
3266
#[test]
3267
fn up_arrow_follows_the_account_setting() {
3268
assert!(matches!(
3269
up_arrow_event(UpArrowBehavior::EditLastMessage),
3270
Some(ComposerEvent::EditLast)
3271
));
3272
assert!(matches!(
3273
up_arrow_event(UpArrowBehavior::NavigateToMessages),
3274
Some(ComposerEvent::FocusMessages)
3275
));
3276
assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3277
}
3198
3278
use gpui_kit::component::input::InputEvent;
3199
3279
3200
3280
fn press(shift: bool) -> InputEvent {
@@ -3295,6 +3375,7 @@ mod tests {
3295
3375
name: "plan.pdf".into(),
3296
3376
},
3297
3377
}],
3378
importance: Default::default(),
3298
3379
};
3299
3380
let extras = outgoing.extras();
3300
3381
assert_eq!(extras.images[0].content_type, "image/png");
@@ -3338,6 +3419,7 @@ mod tests {
3338
3419
edit: None,
3339
3420
images,
3340
3421
files: Vec::new(),
3422
importance: Default::default(),
3341
3423
}
3342
3424
}
3343
3425
@@ -4797,6 +4879,7 @@ mod tests {
4797
4879
}),
4798
4880
images: Vec::new(),
4799
4881
files: Vec::new(),
4882
importance: Default::default(),
4800
4883
};
4801
4884
composer.begin_edit(draft, window, cx);
4802
4885
});
@@ -24,11 +24,13 @@ use gpui_kit::component::{24
use gpui_kit::prelude::FluentBuilder as _;24
use gpui_kit::prelude::FluentBuilder as _;25
use gpui_kit::*;25
use gpui_kit::*;26
use teams_core::{26
use teams_core::{27
Draft, DraftLine, Edit, FileReference, FormatState, LineKind, LinkPreview, MarkKind,27
Draft, DraftLine, Edit, EnterKeyBehavior, FileReference, FormatState, LineKind, LinkPreview,28
MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit, TypingStyle,28
MarkKind, MentionCandidate, MentionInput, OBJECT_MARK, SizeStep, TABLE_MARK, TableEdit,29
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,29
TypingStyle, UpArrowBehavior, UploadedFile, changed_span, has_markdown, link_url, map_offset,30
reverse_edits,30
};31
};31
32
33
pub(crate) mod delivery;32
mod drafts;34
mod drafts;33
mod schedule;35
mod schedule;34
mod table;36
mod table;@@ -120,6 +122,7 @@ pub enum ComposerEvent {120
send_at: DateTime<Utc>,122
send_at: DateTime<Utc>,121
},123
},122
EditLast,124
EditLast,125
FocusMessages,123
Typing(bool),126
Typing(bool),124
}127
}125
128
@@ -225,11 +228,26 @@ pub struct Composer {225
active_cell: Option<(String, teams_core::Cell)>,228
active_cell: Option<(String, teams_core::Cell)>,226
caret_before_table: usize,229
caret_before_table: usize,227
caret_text: String,230
caret_text: String,231
importance: store::MessageImportance,232
delivery_menu: bool,228
_subscriptions: [Subscription; 4],233
_subscriptions: [Subscription; 4],229
}234
}230
235
231
impl EventEmitter<ComposerEvent> for Composer {}236
impl EventEmitter<ComposerEvent> for Composer {}232
237
238
/// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.239
pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {240
behavior == EnterKeyBehavior::NewLine && !shift && !secondary241
}242
243
pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {244
match behavior {245
UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),246
UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),247
UpArrowBehavior::StayInCompose => None,248
}249
}250
233
pub fn is_plain_enter(event: &InputEvent) -> bool {251
pub fn is_plain_enter(event: &InputEvent) -> bool {234
matches!(event, InputEvent::PressEnter { shift: false, .. })252
matches!(event, InputEvent::PressEnter { shift: false, .. })235
}253
}@@ -436,6 +454,8 @@ impl Composer {436
active_cell: None,454
active_cell: None,437
caret_before_table: 0,455
caret_before_table: 0,438
caret_text: String::new(),456
caret_text: String::new(),457
importance: store::MessageImportance::Normal,458
delivery_menu: false,439
_subscriptions: [subscription, observer, image_observer, picker_subscription],459
_subscriptions: [subscription, observer, image_observer, picker_subscription],440
}460
}441
}461
}@@ -536,7 +556,10 @@ impl Composer {536
return;556
return;537
}557
}538
let typed = emoji::typed_char(&previous, self.draft.text(), cursor);558
let typed = emoji::typed_char(&previous, self.draft.text(), cursor);539
if typed.is_some() && self.convert_markdown(cursor, window, cx) {559
if typed.is_some()560
&& !self.app.read(cx).markdown_mode561
&& self.convert_markdown(cursor, window, cx)562
{540
return;563
return;541
}564
}542
if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {565
if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {@@ -1637,6 +1660,7 @@ impl Composer {1637
self.schedule = None;1660
self.schedule = None;1638
self.table_picker = None;1661
self.table_picker = None;1639
self.table_menu = None;1662
self.table_menu = None;1663
self.reset_importance();1640
if !carry {1664
if !carry {1641
self.load_stored_draft(conversation_id, window, cx);1665
self.load_stored_draft(conversation_id, window, cx);1642
}1666
}@@ -1706,12 +1730,15 @@ impl Composer {1706
draft.replace(range, glyph);1730
draft.replace(range, glyph);1707
draft.take_edits();1731
draft.take_edits();1708
}1732
}1709
let mentions = state1733
let mentions: Vec<MentionInput> = state1710
.tokens()1734
.tokens()1711
.iter()1735
.iter()1712
.filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))1736
.filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))1713
.cloned()1737
.cloned()1714
.collect();1738
.collect();1739
if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {1740
draft = Draft::from_markdown(draft.text());1741
}1715
Outgoing {1742
Outgoing {1716
draft,1743
draft,1717
subject: None,1744
subject: None,@@ -1729,6 +1756,7 @@ impl Composer {1729
} else {1756
} else {1730
Vec::new()1757
Vec::new()1731
},1758
},1759
importance: self.sendable_importance(cx),1732
}1760
}1733
}1761
}1734
1762
@@ -2205,6 +2233,7 @@ impl Composer {2205
self.editing = None;2233
self.editing = None;2206
self.link.reset();2234
self.link.reset();2207
self.close_popup();2235
self.close_popup();2236
self.reset_importance();2208
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));2237
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));2209
cx.notify();2238
cx.notify();2210
}2239
}@@ -2426,7 +2455,10 @@ impl Composer {2426
2455
2427
fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {2456
fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {2428
let composer = cx.entity().downgrade();2457
let composer = cx.entity().downgrade();2429
let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();2458
let floating = focused2459
&& self.toolbar_requested(cx)2460
&& !self.format_bar_open()2461
&& !self.app.read(cx).markdown_mode;2430
if self.link_editor.is_none() && !floating {2462
if self.link_editor.is_none() && !floating {2431
return None;2463
return None;2432
}2464
}@@ -2729,36 +2761,39 @@ impl Render for Composer {2729
))2761
))2730
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2762
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2731
});2763
});2732
let format_open = self.format_bar_open();2764
let markdown_mode = self.app.read(cx).markdown_mode;2733
let format_toggle = div()2765
let format_open = self.format_bar_open() && !markdown_mode;2734
.id("composer-format")2766
let format_toggle = (!markdown_mode).then(|| {2735
.debug_selector(|| COMPOSER_FORMAT_TAG.into())2767
div()2736
.size(px(COMPOSER_BUTTON_SIZE))2768
.id("composer-format")2737
.flex_none()2769
.debug_selector(|| COMPOSER_FORMAT_TAG.into())2738
.flex()2770
.size(px(COMPOSER_BUTTON_SIZE))2739
.items_center()2771
.flex_none()2740
.justify_center()2772
.flex()2741
.rounded(px(8.))2773
.items_center()2742
.cursor_pointer()2774
.justify_center()2743
.when(format_open, |button| button.bg(theme::popup_hover()))2775
.rounded(px(8.))2744
.hover(|button| button.bg(theme::popup_hover()))2776
.cursor_pointer()2745
.tooltip(move |window, cx| {2777
.when(format_open, |button| button.bg(theme::popup_hover()))2746
Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)2778
.hover(|button| button.bg(theme::popup_hover()))2747
})2779
.tooltip(move |window, cx| {2748
.child(symbol(2780
Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)2749
format_toolbar::toggle_symbol(format_open),2781
})2750
COMPOSER_ICON_SIZE,2782
.child(symbol(2751
if format_open {2783
format_toolbar::toggle_symbol(format_open),2752
theme::accent_soft()2784
COMPOSER_ICON_SIZE,2753
} else {2785
if format_open {2754
theme::text_muted()2786
theme::accent_soft()2755
},2787
} else {2756
))2788
theme::text_muted()2757
.on_mouse_down(MouseButton::Left, |_, window, cx| {2789
},2758
window.prevent_default();2790
))2759
cx.stop_propagation();2791
.on_mouse_down(MouseButton::Left, |_, window, cx| {2760
})2792
window.prevent_default();2761
.on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)));2793
cx.stop_propagation();2794
})2795
.on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))2796
});2762
let format_bar = format_open.then(|| self.render_format_bar(window, cx));2797
let format_bar = format_open.then(|| self.render_format_bar(window, cx));2763
let composer = cx.weak_entity();2798
let composer = cx.weak_entity();2764
let tokens_composer = composer.clone();2799
let tokens_composer = composer.clone();@@ -2979,8 +3014,12 @@ impl Render for Composer {2979
} else if this.popup_is_open() {3014
} else if this.popup_is_open() {2980
this.move_highlight(-1, cx);3015
this.move_highlight(-1, cx);2981
cx.stop_propagation();3016
cx.stop_propagation();2982
} else if this.editing.is_none() && this.is_empty(cx) {3017
} else if this.editing.is_none()2983
cx.emit(ComposerEvent::EditLast);3018
&& this.is_empty(cx)3019
&& let Some(event) =3020
up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)3021
{3022
cx.emit(event);2984
cx.stop_propagation();3023
cx.stop_propagation();2985
}3024
}2986
}))3025
}))@@ -3026,6 +3065,19 @@ impl Render for Composer {3026
} else if this.popup_is_open() {3065
} else if this.popup_is_open() {3027
this.accept_popup(window, cx);3066
this.accept_popup(window, cx);3028
cx.stop_propagation();3067
cx.stop_propagation();3068
} else if enter_starts_line(3069
this.app.read(cx).account_chat_settings().enter_key,3070
action.shift,3071
action.secondary,3072
) {3073
cx.stop_propagation();3074
window.dispatch_action(3075
Box::new(Enter {3076
secondary: false,3077
shift: true,3078
}),3079
cx,3080
);3029
} else if this.break_line(action.shift, window, cx) {3081
} else if this.break_line(action.shift, window, cx) {3030
cx.stop_propagation();3082
cx.stop_propagation();3031
}3083
}@@ -3104,6 +3156,7 @@ impl Render for Composer {3104
.children(notice)3156
.children(notice)3105
.children(self.render_reply_strip(cx))3157
.children(self.render_reply_strip(cx))3106
.children(self.render_edit_strip(cx))3158
.children(self.render_edit_strip(cx))3159
.children(self.render_urgent_banner(cx))3107
.children(self.render_meeting_chip())3160
.children(self.render_meeting_chip())3108
.children(self.render_link_preview(cx))3161
.children(self.render_link_preview(cx))3109
.child(3162
.child(@@ -3114,6 +3167,7 @@ impl Render for Composer {3114
.children(self.render_emoji_popup(window, cx))3167
.children(self.render_emoji_popup(window, cx))3115
.children(self.render_toolbar(focused, cx))3168
.children(self.render_toolbar(focused, cx))3116
.children(self.render_schedule(cx))3169
.children(self.render_schedule(cx))3170
.children(self.render_delivery_menu(cx))3117
.child(3171
.child(3118
v_flex()3172
v_flex()3119
.debug_selector(|| COMPOSER_BOX_TAG.into())3173
.debug_selector(|| COMPOSER_BOX_TAG.into())@@ -3136,6 +3190,7 @@ impl Render for Composer {3136
.size_full(),3190
.size_full(),3137
)3191
)3138
.children(format_bar)3192
.children(format_bar)3193
.children(self.render_importance_label(cx))3139
.children(tray)3194
.children(tray)3140
.child(3195
.child(3141
h_flex()3196
h_flex()@@ -3154,7 +3209,8 @@ impl Render for Composer {3154
.debug_selector(|| COMPOSER_LEADING_TAG.into())3209
.debug_selector(|| COMPOSER_LEADING_TAG.into())3155
.flex_none()3210
.flex_none()3156
.gap(px(COMPOSER_BUTTON_INSET))3211
.gap(px(COMPOSER_BUTTON_INSET))3157
.child(format_toggle)3212
.children(format_toggle)3213
.children(self.render_delivery_button(cx))3158
.children(fun)3214
.children(fun)3159
.children(attach),3215
.children(attach),3160
)3216
)@@ -3194,7 +3250,31 @@ impl Render for Composer {3194
3250
3195
#[cfg(test)]3251
#[cfg(test)]3196
mod tests {3252
mod tests {3197
use super::{active_mention, submitted_text};3253
use super::{3254
ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,3255
submitted_text, up_arrow_event,3256
};3257
3258
#[test]3259
fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {3260
assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));3261
assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));3262
assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));3263
assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));3264
}3265
3266
#[test]3267
fn up_arrow_follows_the_account_setting() {3268
assert!(matches!(3269
up_arrow_event(UpArrowBehavior::EditLastMessage),3270
Some(ComposerEvent::EditLast)3271
));3272
assert!(matches!(3273
up_arrow_event(UpArrowBehavior::NavigateToMessages),3274
Some(ComposerEvent::FocusMessages)3275
));3276
assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());3277
}3198
use gpui_kit::component::input::InputEvent;3278
use gpui_kit::component::input::InputEvent;3199
3279
3200
fn press(shift: bool) -> InputEvent {3280
fn press(shift: bool) -> InputEvent {@@ -3295,6 +3375,7 @@ mod tests {3295
name: "plan.pdf".into(),3375
name: "plan.pdf".into(),3296
},3376
},3297
}],3377
}],3378
importance: Default::default(),3298
};3379
};3299
let extras = outgoing.extras();3380
let extras = outgoing.extras();3300
assert_eq!(extras.images[0].content_type, "image/png");3381
assert_eq!(extras.images[0].content_type, "image/png");@@ -3338,6 +3419,7 @@ mod tests {3338
edit: None,3419
edit: None,3339
images,3420
images,3340
files: Vec::new(),3421
files: Vec::new(),3422
importance: Default::default(),3341
}3423
}3342
}3424
}3343
3425
@@ -4797,6 +4879,7 @@ mod tests {4797
}),4879
}),4798
images: Vec::new(),4880
images: Vec::new(),4799
files: Vec::new(),4881
files: Vec::new(),4882
importance: Default::default(),4800
};4883
};4801
composer.begin_edit(draft, window, cx);4884
composer.begin_edit(draft, window, cx);4802
});4885
});@@ -0,0 +1,287 @@
1
use gpui_kit::component::fluent::{
2
MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3
MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4
};
5
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6
use gpui_kit::prelude::FluentBuilder as _;
7
use gpui_kit::*;
8
use store::MessageImportance;
9
10
use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
11
use crate::delivery_options::{
12
DELIVERY_BUTTON_TITLE, DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,
13
allowed_importance, delivery_options, urgent_banner,
14
};
15
use crate::importance::importance_label;
16
use crate::theme::{self, ElevatedSurface as _};
17
use crate::views::widgets::symbol;
18
19
pub const COMPOSER_DELIVERY_TAG: &str = "composer/leading/delivery";
20
pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";
21
pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
22
pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
23
const MENU_WIDTH: f32 = 320.;
24
const OPTION_ICON_SIZE: f32 = 20.;
25
const BANNER_ICON_SIZE: f32 = 16.;
26
const DISABLED_OPACITY: f32 = 0.4;
27
const LABEL_SIZE: f32 = 12.;
28
const LABEL_LINE_HEIGHT: f32 = 16.;
29
const BANNER_HEIGHT: f32 = 36.;
30
const BANNER_PADDING: f32 = 12.;
31
const BANNER_TINT: f32 = 0.14;
32
pub const LABEL_INSET_X: f32 =
33
COMPOSER_BUTTON_INSET + (COMPOSER_BUTTON_SIZE - COMPOSER_ICON_SIZE) / 2.;
34
35
impl Composer {
36
fn urgent_availability(&self, cx: &App) -> UrgentAvailability {
37
let conversation_id = self.conversation_id.as_deref().unwrap_or_default();
38
self.app
39
.read(cx)
40
.urgent_availability(conversation_id, self.editing.is_some())
41
}
42
43
/// Teams sends edits and scheduled messages as Standard, and drops Urgent where it is no longer offered.
44
pub(super) fn sendable_importance(&self, cx: &App) -> MessageImportance {
45
if self.editing.is_some() {
46
return MessageImportance::Normal;
47
}
48
allowed_importance(self.importance, self.urgent_availability(cx))
49
}
50
51
pub(super) fn reset_importance(&mut self) {
52
self.importance = MessageImportance::Normal;
53
self.delivery_menu = false;
54
}
55
56
fn choose_importance(
57
&mut self,
58
importance: MessageImportance,
59
window: &mut Window,
60
cx: &mut Context<Self>,
61
) {
62
self.importance = importance;
63
self.delivery_menu = false;
64
self.focus(window, cx);
65
cx.notify();
66
}
67
68
pub(super) fn render_delivery_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {
69
if self.editing.is_some() {
70
return None;
71
}
72
let open = self.delivery_menu;
73
let marked = self.importance.is_marked();
74
Some(
75
div()
76
.id("composer-delivery")
77
.debug_selector(|| COMPOSER_DELIVERY_TAG.into())
78
.size(px(COMPOSER_BUTTON_SIZE))
79
.flex_none()
80
.flex()
81
.items_center()
82
.justify_center()
83
.rounded(px(8.))
84
.cursor_pointer()
85
.when(open, |button| button.bg(theme::popup_hover()))
86
.hover(|button| button.bg(theme::popup_hover()))
87
.tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))
88
.child(symbol(
89
"fluent_important",
90
COMPOSER_ICON_SIZE,
91
if marked {
92
theme::red()
93
} else {
94
theme::text_muted()
95
},
96
))
97
.on_mouse_down(MouseButton::Left, |_, window, cx| {
98
window.prevent_default();
99
cx.stop_propagation();
100
})
101
.on_click(cx.listener(|this, _, _, cx| {
102
this.delivery_menu = !this.delivery_menu;
103
cx.notify();
104
})),
105
)
106
}
107
108
pub(super) fn render_delivery_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
109
if !self.delivery_menu || self.editing.is_some() {
110
return None;
111
}
112
let selected = self.sendable_importance(cx);
113
let rows = delivery_options(self.urgent_availability(cx))
114
.into_iter()
115
.map(|(option, enabled)| {
116
self.render_option(option, enabled, option.importance == selected, cx)
117
})
118
.collect::<Vec<_>>();
119
Some(
120
v_flex()
121
.id("delivery-menu")
122
.debug_selector(|| DELIVERY_MENU_TAG.into())
123
.absolute()
124
.bottom(relative(1.))
125
.left_0()
126
.mb(px(6.))
127
.w(px(MENU_WIDTH))
128
.max_w(relative(1.))
129
.p(MENU_LIST_PADDING)
130
.gap(MENU_ITEM_GAP)
131
.rounded(px(10.))
132
.flyout_surface()
133
.occlude()
134
.on_mouse_down_out(cx.listener(|this, _, _, cx| {
135
this.delivery_menu = false;
136
cx.notify();
137
}))
138
.children(rows)
139
.into_any_element(),
140
)
141
}
142
143
fn render_option(
144
&self,
145
option: DeliveryOption,
146
enabled: bool,
147
selected: bool,
148
cx: &mut Context<Self>,
149
) -> Stateful<Div> {
150
let accent = if option.importance.is_marked() {
151
theme::red()
152
} else {
153
theme::text_soft()
154
};
155
let row = h_flex()
156
.id(option.tag)
157
.debug_selector(|| option.tag.into())
158
.w_full()
159
.min_h(MENU_ITEM_HEIGHT)
160
.px(MENU_ITEM_PADDING_X)
161
.py(MENU_ITEM_PADDING_X)
162
.gap(MENU_ICON_LABEL_GAP)
163
.items_center()
164
.rounded(px(6.))
165
.child(
166
div()
167
.size(MENU_ICON_SLOT)
168
.flex_none()
169
.flex()
170
.items_center()
171
.justify_center()
172
.child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),
173
)
174
.child(
175
v_flex()
176
.flex_1()
177
.min_w_0()
178
.child(
179
div()
180
.text_size(px(13.))
181
.font_weight(FontWeight::SEMIBOLD)
182
.text_color(theme::text())
183
.child(option.header),
184
)
185
.child(
186
div()
187
.text_size(px(12.))
188
.text_color(theme::text_muted())
189
.child(option.content),
190
),
191
)
192
.children(
193
selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),
194
);
195
if !enabled {
196
return row
197
.opacity(DISABLED_OPACITY)
198
.tooltip(|window, cx| Tooltip::new(URGENT_TOO_MANY_MEMBERS).build(window, cx));
199
}
200
let importance = option.importance;
201
row.cursor_pointer()
202
.hover(|row| row.bg(theme::popup_hover()))
203
.on_click(cx.listener(move |this, _, window, cx| {
204
this.choose_importance(importance, window, cx)
205
}))
206
}
207
208
pub(super) fn render_importance_label(&self, cx: &App) -> Option<Div> {
209
let label = importance_label(self.sendable_importance(cx))?;
210
Some(
211
div()
212
.pt(px(COMPOSER_BUTTON_INSET * 2.))
213
.px(px(LABEL_INSET_X))
214
.text_size(px(LABEL_SIZE))
215
.line_height(px(LABEL_LINE_HEIGHT))
216
.font_weight(FontWeight::BOLD)
217
.text_color(theme::red())
218
.child(
219
div()
220
.debug_selector(|| COMPOSER_IMPORTANCE_LABEL_TAG.into())
221
.child(label),
222
),
223
)
224
}
225
226
pub(super) fn render_urgent_banner(&self, cx: &mut Context<Self>) -> Option<Div> {
227
if self.sendable_importance(cx) != MessageImportance::Urgent {
228
return None;
229
}
230
let member_count = self
231
.conversation_id
232
.as_deref()
233
.and_then(|id| {
234
self.app
235
.read(cx)
236
.sidebar
237
.chats
238
.iter()
239
.find(|chat| chat.id == id)
240
.map(|chat| chat.members.len())
241
})
242
.unwrap_or_default();
243
Some(
244
h_flex()
245
.debug_selector(|| COMPOSER_URGENT_BANNER_TAG.into())
246
.w_full()
247
.h(px(BANNER_HEIGHT))
248
.mb(px(8.))
249
.px(px(BANNER_PADDING))
250
.gap(px(8.))
251
.items_center()
252
.rounded(px(10.))
253
.bg(theme::red().opacity(BANNER_TINT))
254
.text_size(px(12.))
255
.text_color(theme::red_tint())
256
.child(symbol(
257
"fluent_alert_urgent",
258
BANNER_ICON_SIZE,
259
theme::red_tint(),
260
))
261
.child(
262
div()
263
.flex_1()
264
.min_w_0()
265
.truncate()
266
.child(urgent_banner(member_count)),
267
)
268
.child(
269
div()
270
.id("composer-urgent-banner-close")
271
.size(px(24.))
272
.flex_none()
273
.flex()
274
.items_center()
275
.justify_center()
276
.rounded(px(6.))
277
.cursor_pointer()
278
.hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
279
.tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
280
.child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))
281
.on_click(cx.listener(|this, _, window, cx| {
282
this.choose_importance(MessageImportance::Normal, window, cx)
283
})),
284
),
285
)
286
}
287
}
@@ -0,0 +1,287 @@1
use gpui_kit::component::fluent::{2
MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,3
MENU_LIST_PADDING, OPTION_CHECK_SIZE,4
};5
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};6
use gpui_kit::prelude::FluentBuilder as _;7
use gpui_kit::*;8
use store::MessageImportance;9
10
use super::{COMPOSER_BUTTON_INSET, COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};11
use crate::delivery_options::{12
DELIVERY_BUTTON_TITLE, DeliveryOption, URGENT_TOO_MANY_MEMBERS, UrgentAvailability,13
allowed_importance, delivery_options, urgent_banner,14
};15
use crate::importance::importance_label;16
use crate::theme::{self, ElevatedSurface as _};17
use crate::views::widgets::symbol;18
19
pub const COMPOSER_DELIVERY_TAG: &str = "composer/leading/delivery";20
pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";21
pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";22
pub const DELIVERY_MENU_TAG: &str = "delivery-menu";23
const MENU_WIDTH: f32 = 320.;24
const OPTION_ICON_SIZE: f32 = 20.;25
const BANNER_ICON_SIZE: f32 = 16.;26
const DISABLED_OPACITY: f32 = 0.4;27
const LABEL_SIZE: f32 = 12.;28
const LABEL_LINE_HEIGHT: f32 = 16.;29
const BANNER_HEIGHT: f32 = 36.;30
const BANNER_PADDING: f32 = 12.;31
const BANNER_TINT: f32 = 0.14;32
pub const LABEL_INSET_X: f32 =33
COMPOSER_BUTTON_INSET + (COMPOSER_BUTTON_SIZE - COMPOSER_ICON_SIZE) / 2.;34
35
impl Composer {36
fn urgent_availability(&self, cx: &App) -> UrgentAvailability {37
let conversation_id = self.conversation_id.as_deref().unwrap_or_default();38
self.app39
.read(cx)40
.urgent_availability(conversation_id, self.editing.is_some())41
}42
43
/// Teams sends edits and scheduled messages as Standard, and drops Urgent where it is no longer offered.44
pub(super) fn sendable_importance(&self, cx: &App) -> MessageImportance {45
if self.editing.is_some() {46
return MessageImportance::Normal;47
}48
allowed_importance(self.importance, self.urgent_availability(cx))49
}50
51
pub(super) fn reset_importance(&mut self) {52
self.importance = MessageImportance::Normal;53
self.delivery_menu = false;54
}55
56
fn choose_importance(57
&mut self,58
importance: MessageImportance,59
window: &mut Window,60
cx: &mut Context<Self>,61
) {62
self.importance = importance;63
self.delivery_menu = false;64
self.focus(window, cx);65
cx.notify();66
}67
68
pub(super) fn render_delivery_button(&self, cx: &mut Context<Self>) -> Option<Stateful<Div>> {69
if self.editing.is_some() {70
return None;71
}72
let open = self.delivery_menu;73
let marked = self.importance.is_marked();74
Some(75
div()76
.id("composer-delivery")77
.debug_selector(|| COMPOSER_DELIVERY_TAG.into())78
.size(px(COMPOSER_BUTTON_SIZE))79
.flex_none()80
.flex()81
.items_center()82
.justify_center()83
.rounded(px(8.))84
.cursor_pointer()85
.when(open, |button| button.bg(theme::popup_hover()))86
.hover(|button| button.bg(theme::popup_hover()))87
.tooltip(|window, cx| Tooltip::new(DELIVERY_BUTTON_TITLE).build(window, cx))88
.child(symbol(89
"fluent_important",90
COMPOSER_ICON_SIZE,91
if marked {92
theme::red()93
} else {94
theme::text_muted()95
},96
))97
.on_mouse_down(MouseButton::Left, |_, window, cx| {98
window.prevent_default();99
cx.stop_propagation();100
})101
.on_click(cx.listener(|this, _, _, cx| {102
this.delivery_menu = !this.delivery_menu;103
cx.notify();104
})),105
)106
}107
108
pub(super) fn render_delivery_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {109
if !self.delivery_menu || self.editing.is_some() {110
return None;111
}112
let selected = self.sendable_importance(cx);113
let rows = delivery_options(self.urgent_availability(cx))114
.into_iter()115
.map(|(option, enabled)| {116
self.render_option(option, enabled, option.importance == selected, cx)117
})118
.collect::<Vec<_>>();119
Some(120
v_flex()121
.id("delivery-menu")122
.debug_selector(|| DELIVERY_MENU_TAG.into())123
.absolute()124
.bottom(relative(1.))125
.left_0()126
.mb(px(6.))127
.w(px(MENU_WIDTH))128
.max_w(relative(1.))129
.p(MENU_LIST_PADDING)130
.gap(MENU_ITEM_GAP)131
.rounded(px(10.))132
.flyout_surface()133
.occlude()134
.on_mouse_down_out(cx.listener(|this, _, _, cx| {135
this.delivery_menu = false;136
cx.notify();137
}))138
.children(rows)139
.into_any_element(),140
)141
}142
143
fn render_option(144
&self,145
option: DeliveryOption,146
enabled: bool,147
selected: bool,148
cx: &mut Context<Self>,149
) -> Stateful<Div> {150
let accent = if option.importance.is_marked() {151
theme::red()152
} else {153
theme::text_soft()154
};155
let row = h_flex()156
.id(option.tag)157
.debug_selector(|| option.tag.into())158
.w_full()159
.min_h(MENU_ITEM_HEIGHT)160
.px(MENU_ITEM_PADDING_X)161
.py(MENU_ITEM_PADDING_X)162
.gap(MENU_ICON_LABEL_GAP)163
.items_center()164
.rounded(px(6.))165
.child(166
div()167
.size(MENU_ICON_SLOT)168
.flex_none()169
.flex()170
.items_center()171
.justify_center()172
.child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),173
)174
.child(175
v_flex()176
.flex_1()177
.min_w_0()178
.child(179
div()180
.text_size(px(13.))181
.font_weight(FontWeight::SEMIBOLD)182
.text_color(theme::text())183
.child(option.header),184
)185
.child(186
div()187
.text_size(px(12.))188
.text_color(theme::text_muted())189
.child(option.content),190
),191
)192
.children(193
selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),194
);195
if !enabled {196
return row197
.opacity(DISABLED_OPACITY)198
.tooltip(|window, cx| Tooltip::new(URGENT_TOO_MANY_MEMBERS).build(window, cx));199
}200
let importance = option.importance;201
row.cursor_pointer()202
.hover(|row| row.bg(theme::popup_hover()))203
.on_click(cx.listener(move |this, _, window, cx| {204
this.choose_importance(importance, window, cx)205
}))206
}207
208
pub(super) fn render_importance_label(&self, cx: &App) -> Option<Div> {209
let label = importance_label(self.sendable_importance(cx))?;210
Some(211
div()212
.pt(px(COMPOSER_BUTTON_INSET * 2.))213
.px(px(LABEL_INSET_X))214
.text_size(px(LABEL_SIZE))215
.line_height(px(LABEL_LINE_HEIGHT))216
.font_weight(FontWeight::BOLD)217
.text_color(theme::red())218
.child(219
div()220
.debug_selector(|| COMPOSER_IMPORTANCE_LABEL_TAG.into())221
.child(label),222
),223
)224
}225
226
pub(super) fn render_urgent_banner(&self, cx: &mut Context<Self>) -> Option<Div> {227
if self.sendable_importance(cx) != MessageImportance::Urgent {228
return None;229
}230
let member_count = self231
.conversation_id232
.as_deref()233
.and_then(|id| {234
self.app235
.read(cx)236
.sidebar237
.chats238
.iter()239
.find(|chat| chat.id == id)240
.map(|chat| chat.members.len())241
})242
.unwrap_or_default();243
Some(244
h_flex()245
.debug_selector(|| COMPOSER_URGENT_BANNER_TAG.into())246
.w_full()247
.h(px(BANNER_HEIGHT))248
.mb(px(8.))249
.px(px(BANNER_PADDING))250
.gap(px(8.))251
.items_center()252
.rounded(px(10.))253
.bg(theme::red().opacity(BANNER_TINT))254
.text_size(px(12.))255
.text_color(theme::red_tint())256
.child(symbol(257
"fluent_alert_urgent",258
BANNER_ICON_SIZE,259
theme::red_tint(),260
))261
.child(262
div()263
.flex_1()264
.min_w_0()265
.truncate()266
.child(urgent_banner(member_count)),267
)268
.child(269
div()270
.id("composer-urgent-banner-close")271
.size(px(24.))272
.flex_none()273
.flex()274
.items_center()275
.justify_center()276
.rounded(px(6.))277
.cursor_pointer()278
.hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))279
.tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))280
.child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))281
.on_click(cx.listener(|this, _, window, cx| {282
this.choose_importance(MessageImportance::Normal, window, cx)283
})),284
),285
)286
}287
}@@ -255,6 +255,7 @@ impl Composer {
255
255
if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {
256
256
return;
257
257
}
258
self.importance = store::MessageImportance::Normal;
258
259
let outgoing = self.compose(cx);
259
260
self.scheduling = Some(outgoing.html());
260
261
self.close_schedule(window, cx);
@@ -255,6 +255,7 @@ impl Composer {255
if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {255
if self.scheduling.is_some() || self.schedule_blocker(cx).is_some() {256
return;256
return;257
}257
}258
self.importance = store::MessageImportance::Normal;258
let outgoing = self.compose(cx);259
let outgoing = self.compose(cx);259
self.scheduling = Some(outgoing.html());260
self.scheduling = Some(outgoing.html());260
self.close_schedule(window, cx);261
self.close_schedule(window, cx);@@ -65,6 +65,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
65
65
use crate::backend::Engine;
66
66
use crate::card_state::CardScope;
67
67
use crate::channel_files::DownloadSource;
68
use crate::chat_settings_actions::shown_receipt;
68
69
use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
69
70
use crate::demo_library::DemoLibrary;
70
71
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
@@ -694,7 +695,7 @@ impl ConversationView {
694
695
| AppEvent::Call => {}
695
696
AppEvent::LiveMeeting => cx.notify(),
696
697
AppEvent::Saved => cx.notify(),
697
AppEvent::Translation => self.rebuild(false, cx),
698
AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
698
699
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
699
700
AppEvent::Typing => cx.notify(),
700
701
AppEvent::Scheduled => self.rebuild(false, cx),
@@ -744,6 +745,7 @@ impl ConversationView {
744
745
self.schedule((**outgoing).clone(), *send_at, window, cx)
745
746
}
746
747
ComposerEvent::EditLast => self.edit_last_own(window, cx),
748
ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
747
749
ComposerEvent::Typing(active) => self.send_typing(*active, cx),
748
750
}
749
751
}
@@ -1913,6 +1915,15 @@ impl ConversationView {
1913
1915
}
1914
1916
1915
1917
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1918
let settings = self.app.read(cx).account_chat_settings();
1919
let mut receipts = self.raw_receipts(records, cx);
1920
for receipt in receipts.values_mut() {
1921
*receipt = shown_receipt(&settings, *receipt);
1922
}
1923
receipts
1924
}
1925
1926
fn raw_receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1916
1927
let state = self.app.read(cx);
1917
1928
if state.mode.demo {
1918
1929
let read_ids = crate::demo::read_message_ids(records);
@@ -2017,7 +2028,10 @@ impl ConversationView {
2017
2028
return;
2018
2029
};
2019
2030
self.app.update(cx, |state, cx| match &selection {
2020
Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),
2031
Selection::Chat(chat_id) => {
2032
state.ack_urgent_messages(chat_id, cx);
2033
state.mark_chat_read(chat_id, cx)
2034
}
2021
2035
Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2022
2036
});
2023
2037
if plan.clear_divider
@@ -2773,6 +2787,7 @@ impl ConversationView {
2773
2787
images: Vec::new(),
2774
2788
files: Vec::new(),
2775
2789
link_preview: None,
2790
importance: Default::default(),
2776
2791
};
2777
2792
self.show_main_composer(cx);
2778
2793
self.composer
@@ -65,6 +65,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t65
use crate::backend::Engine;65
use crate::backend::Engine;66
use crate::card_state::CardScope;66
use crate::card_state::CardScope;67
use crate::channel_files::DownloadSource;67
use crate::channel_files::DownloadSource;68
use crate::chat_settings_actions::shown_receipt;68
use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};69
use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};69
use crate::demo_library::DemoLibrary;70
use crate::demo_library::DemoLibrary;70
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};71
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};@@ -694,7 +695,7 @@ impl ConversationView {694
| AppEvent::Call => {}695
| AppEvent::Call => {}695
AppEvent::LiveMeeting => cx.notify(),696
AppEvent::LiveMeeting => cx.notify(),696
AppEvent::Saved => cx.notify(),697
AppEvent::Saved => cx.notify(),697
AppEvent::Translation => self.rebuild(false, cx),698
AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),698
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),699
AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),699
AppEvent::Typing => cx.notify(),700
AppEvent::Typing => cx.notify(),700
AppEvent::Scheduled => self.rebuild(false, cx),701
AppEvent::Scheduled => self.rebuild(false, cx),@@ -744,6 +745,7 @@ impl ConversationView {744
self.schedule((**outgoing).clone(), *send_at, window, cx)745
self.schedule((**outgoing).clone(), *send_at, window, cx)745
}746
}746
ComposerEvent::EditLast => self.edit_last_own(window, cx),747
ComposerEvent::EditLast => self.edit_last_own(window, cx),748
ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),747
ComposerEvent::Typing(active) => self.send_typing(*active, cx),749
ComposerEvent::Typing(active) => self.send_typing(*active, cx),748
}750
}749
}751
}@@ -1913,6 +1915,15 @@ impl ConversationView {1913
}1915
}1914
1916
1915
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {1917
fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {1918
let settings = self.app.read(cx).account_chat_settings();1919
let mut receipts = self.raw_receipts(records, cx);1920
for receipt in receipts.values_mut() {1921
*receipt = shown_receipt(&settings, *receipt);1922
}1923
receipts1924
}1925
1926
fn raw_receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {1916
let state = self.app.read(cx);1927
let state = self.app.read(cx);1917
if state.mode.demo {1928
if state.mode.demo {1918
let read_ids = crate::demo::read_message_ids(records);1929
let read_ids = crate::demo::read_message_ids(records);@@ -2017,7 +2028,10 @@ impl ConversationView {2017
return;2028
return;2018
};2029
};2019
self.app.update(cx, |state, cx| match &selection {2030
self.app.update(cx, |state, cx| match &selection {2020
Selection::Chat(chat_id) => state.mark_chat_read(chat_id, cx),2031
Selection::Chat(chat_id) => {2032
state.ack_urgent_messages(chat_id, cx);2033
state.mark_chat_read(chat_id, cx)2034
}2021
Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),2035
Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),2022
});2036
});2023
if plan.clear_divider2037
if plan.clear_divider@@ -2773,6 +2787,7 @@ impl ConversationView {2773
images: Vec::new(),2787
images: Vec::new(),2774
files: Vec::new(),2788
files: Vec::new(),2775
link_preview: None,2789
link_preview: None,2790
importance: Default::default(),2776
};2791
};2777
self.show_main_composer(cx);2792
self.show_main_composer(cx);2778
self.composer2793
self.composer@@ -190,7 +190,9 @@ impl ConversationView {
190
190
let root_id = self.reply_root.clone();
191
191
self.send_typing_in(root_id, *active, cx);
192
192
}
193
ComposerEvent::Schedule { .. } | ComposerEvent::EditLast => {}
193
ComposerEvent::Schedule { .. }
194
| ComposerEvent::EditLast
195
| ComposerEvent::FocusMessages => {}
194
196
}
195
197
}
196
198
@@ -190,7 +190,9 @@ impl ConversationView {190
let root_id = self.reply_root.clone();190
let root_id = self.reply_root.clone();191
self.send_typing_in(root_id, *active, cx);191
self.send_typing_in(root_id, *active, cx);192
}192
}193
ComposerEvent::Schedule { .. } | ComposerEvent::EditLast => {}193
ComposerEvent::Schedule { .. }194
| ComposerEvent::EditLast195
| ComposerEvent::FocusMessages => {}194
}196
}195
}197
}196
198
@@ -316,6 +316,8 @@ impl RenderEnv {
316
316
call: self.call_actions(message, cx),
317
317
reaction_proposal,
318
318
undo_delete: self.undo_delete_action(message, is_real, view, cx),
319
compact: self.app.read(cx).account_chat_settings().message_density
320
== teams_core::MessageDensity::Compact,
319
321
}
320
322
}
321
323
@@ -316,6 +316,8 @@ impl RenderEnv {316
call: self.call_actions(message, cx),316
call: self.call_actions(message, cx),317
reaction_proposal,317
reaction_proposal,318
undo_delete: self.undo_delete_action(message, is_real, view, cx),318
undo_delete: self.undo_delete_action(message, is_real, view, cx),319
compact: self.app.read(cx).account_chat_settings().message_density320
== teams_core::MessageDensity::Compact,319
}321
}320
}322
}321
323
@@ -22,6 +22,7 @@ use super::widgets::{icon, symbol};
22
22
use crate::agents::{AgentRun, run_chip};
23
23
use crate::card_state::BotIdentity;
24
24
use crate::data::Directory;
25
use crate::importance::importance_label;
25
26
use crate::render::Block;
26
27
use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};
27
28
use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};
@@ -46,9 +47,14 @@ pub const BUBBLE_TAGS: [&str; 12] = [
46
47
"message-bubble/10",
47
48
"message-bubble/11",
48
49
];
50
pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";
49
51
pub(super) const AVATAR_SIZE: f32 = 28.;
50
52
pub(super) const AVATAR_GAP: f32 = 8.;
51
53
const SERIES_START_GAP: f32 = 8.;
54
const SERIES_GAP: f32 = 2.;
55
const COMPACT_SERIES_START_GAP: f32 = 4.;
56
const COMPACT_SERIES_GAP: f32 = 1.;
57
const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;
52
58
pub(super) const BODY_SIZE: f32 = 13.5;
53
59
const MAX_WIDTH_RATIO: f32 = 0.7;
54
60
const NARROW_BUBBLE_WIDTH: f32 = 300.;
@@ -58,6 +64,10 @@ const META_SIZE: f32 = 11.;
58
64
const META_CHECK_SIZE: f32 = 15.;
59
65
const SAVED_MARK_SIZE: f32 = 12.;
60
66
const FORWARDED_SIZE: f32 = 11.;
67
const IMPORTANCE_LABEL_SIZE: f32 = 12.;
68
const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
69
const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
70
pub(super) const BUBBLE_PADDING_X: f32 = 12.;
61
71
const FIGURE_SPACE_WIDTH: f32 = 7.4;
62
72
const PULSE_PERIOD: Duration = Duration::from_millis(1600);
63
73
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);
@@ -90,6 +100,24 @@ pub struct RowActions {
90
100
pub call: CallActions,
91
101
pub reaction_proposal: Option<ReactionPill>,
92
102
pub undo_delete: SharedRowAction,
103
pub compact: bool,
104
}
105
106
pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
107
match (has_previous, compact) {
108
(true, false) => SERIES_GAP,
109
(true, true) => COMPACT_SERIES_GAP,
110
(false, false) => SERIES_START_GAP,
111
(false, true) => COMPACT_SERIES_START_GAP,
112
}
113
}
114
115
pub fn bubble_padding_y(compact: bool) -> f32 {
116
if compact {
117
COMPACT_BUBBLE_PADDING_Y
118
} else {
119
BUBBLE_PADDING_Y
120
}
93
121
}
94
122
95
123
const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -190,8 +218,8 @@ fn bubble(
190
218
.rounded_tr(px(corners.top_right))
191
219
.rounded_br(px(corners.bottom_right))
192
220
.rounded_bl(px(corners.bottom_left))
193
.px(px(12.))
194
.py(px(BUBBLE_PADDING_Y))
221
.px(px(BUBBLE_PADDING_X))
222
.py(px(bubble_padding_y(extras.compact)))
195
223
})
196
224
.text_size(px(BODY_SIZE))
197
225
.line_height(relative(1.45));
@@ -227,6 +255,7 @@ fn bubble(
227
255
let has_reactions = !row.reactions.is_empty();
228
256
let saved = extras.saved;
229
257
let mut content = v_flex().gap(px(6.));
258
content = content.children(importance_header(row, extras.compact));
230
259
if row.forwarded {
231
260
content = content.child(forwarded_header());
232
261
}
@@ -301,7 +330,7 @@ fn bubble(
301
330
.child(
302
331
h_flex()
303
332
.flex_none()
304
.mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
333
.mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))
305
334
.child(bubble_meta(row, own, saved)),
306
335
),
307
336
);
@@ -350,12 +379,31 @@ struct BubbleExtras {
350
379
agent_run: Option<AgentRun>,
351
380
reaction_proposal: Option<ReactionPill>,
352
381
undo_delete: SharedRowAction,
382
compact: bool,
353
383
}
354
384
355
385
fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
356
386
run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))
357
387
}
358
388
389
/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
390
pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {
391
let label = importance_label(row.importance)?;
392
Some(
393
div()
394
.debug_selector(|| IMPORTANCE_LABEL_TAG.into())
395
.text_size(px(IMPORTANCE_LABEL_SIZE))
396
.line_height(px(if compact {
397
COMPACT_IMPORTANCE_LINE_HEIGHT
398
} else {
399
IMPORTANCE_LINE_HEIGHT
400
}))
401
.font_weight(FontWeight::BOLD)
402
.text_color(theme::red())
403
.child(label),
404
)
405
}
406
359
407
pub(super) fn forwarded_header() -> Div {
360
408
h_flex()
361
409
.gap(px(4.))
@@ -688,6 +736,7 @@ pub fn render_message_row(
688
736
pinned: _,
689
737
reaction_proposal,
690
738
undo_delete,
739
compact,
691
740
} = actions;
692
741
let extras = BubbleExtras {
693
742
hover: hovered,
@@ -703,13 +752,10 @@ pub fn render_message_row(
703
752
agent_run,
704
753
reaction_proposal,
705
754
undo_delete,
755
compact,
706
756
};
707
757
let own = row.own;
708
let spacing = if row.series.has_prev {
709
px(2.)
710
} else {
711
px(SERIES_START_GAP)
712
};
758
let spacing = px(row_spacing(row.series.has_prev, compact));
713
759
let mut container = v_flex().w_full().px(px(ROW_PADDING));
714
760
if let Some(day) = &row.day_header {
715
761
container = container.child(day_separator(day));
@@ -743,3 +789,16 @@ pub fn render_message_row(
743
789
)
744
790
.into_any_element()
745
791
}
792
793
#[cfg(test)]
794
mod density_tests {
795
use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
796
797
#[test]
798
fn compact_density_tightens_gaps_and_bubble_padding() {
799
assert!(row_spacing(false, true) < row_spacing(false, false));
800
assert!(row_spacing(true, true) < row_spacing(true, false));
801
assert!(bubble_padding_y(true) < bubble_padding_y(false));
802
assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);
803
}
804
}
@@ -22,6 +22,7 @@ use super::widgets::{icon, symbol};22
use crate::agents::{AgentRun, run_chip};22
use crate::agents::{AgentRun, run_chip};23
use crate::card_state::BotIdentity;23
use crate::card_state::BotIdentity;24
use crate::data::Directory;24
use crate::data::Directory;25
use crate::importance::importance_label;25
use crate::render::Block;26
use crate::render::Block;26
use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};27
use crate::restorable_deletes::{DELETED_TOMBSTONE, UNDO_DELETE_LABEL};27
use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};28
use crate::rows::{Delivery, MessageRow, Receipt, ScheduledState, Skeleton, bubble_corners};@@ -46,9 +47,14 @@ pub const BUBBLE_TAGS: [&str; 12] = [46
"message-bubble/10",47
"message-bubble/10",47
"message-bubble/11",48
"message-bubble/11",48
];49
];50
pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";49
pub(super) const AVATAR_SIZE: f32 = 28.;51
pub(super) const AVATAR_SIZE: f32 = 28.;50
pub(super) const AVATAR_GAP: f32 = 8.;52
pub(super) const AVATAR_GAP: f32 = 8.;51
const SERIES_START_GAP: f32 = 8.;53
const SERIES_START_GAP: f32 = 8.;54
const SERIES_GAP: f32 = 2.;55
const COMPACT_SERIES_START_GAP: f32 = 4.;56
const COMPACT_SERIES_GAP: f32 = 1.;57
const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;52
pub(super) const BODY_SIZE: f32 = 13.5;58
pub(super) const BODY_SIZE: f32 = 13.5;53
const MAX_WIDTH_RATIO: f32 = 0.7;59
const MAX_WIDTH_RATIO: f32 = 0.7;54
const NARROW_BUBBLE_WIDTH: f32 = 300.;60
const NARROW_BUBBLE_WIDTH: f32 = 300.;@@ -58,6 +64,10 @@ const META_SIZE: f32 = 11.;58
const META_CHECK_SIZE: f32 = 15.;64
const META_CHECK_SIZE: f32 = 15.;59
const SAVED_MARK_SIZE: f32 = 12.;65
const SAVED_MARK_SIZE: f32 = 12.;60
const FORWARDED_SIZE: f32 = 11.;66
const FORWARDED_SIZE: f32 = 11.;67
const IMPORTANCE_LABEL_SIZE: f32 = 12.;68
const IMPORTANCE_LINE_HEIGHT: f32 = 16.;69
const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;70
pub(super) const BUBBLE_PADDING_X: f32 = 12.;61
const FIGURE_SPACE_WIDTH: f32 = 7.4;71
const FIGURE_SPACE_WIDTH: f32 = 7.4;62
const PULSE_PERIOD: Duration = Duration::from_millis(1600);72
const PULSE_PERIOD: Duration = Duration::from_millis(1600);63
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);73
const RECEIPT_FADE_PERIOD: Duration = Duration::from_millis(600);@@ -90,6 +100,24 @@ pub struct RowActions {90
pub call: CallActions,100
pub call: CallActions,91
pub reaction_proposal: Option<ReactionPill>,101
pub reaction_proposal: Option<ReactionPill>,92
pub undo_delete: SharedRowAction,102
pub undo_delete: SharedRowAction,103
pub compact: bool,104
}105
106
pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {107
match (has_previous, compact) {108
(true, false) => SERIES_GAP,109
(true, true) => COMPACT_SERIES_GAP,110
(false, false) => SERIES_START_GAP,111
(false, true) => COMPACT_SERIES_START_GAP,112
}113
}114
115
pub fn bubble_padding_y(compact: bool) -> f32 {116
if compact {117
COMPACT_BUBBLE_PADDING_Y118
} else {119
BUBBLE_PADDING_Y120
}93
}121
}94
122
95
const TOOLBAR_RIGHT_INSET: f32 = 0.;123
const TOOLBAR_RIGHT_INSET: f32 = 0.;@@ -190,8 +218,8 @@ fn bubble(190
.rounded_tr(px(corners.top_right))218
.rounded_tr(px(corners.top_right))191
.rounded_br(px(corners.bottom_right))219
.rounded_br(px(corners.bottom_right))192
.rounded_bl(px(corners.bottom_left))220
.rounded_bl(px(corners.bottom_left))193
.px(px(12.))221
.px(px(BUBBLE_PADDING_X))194
.py(px(BUBBLE_PADDING_Y))222
.py(px(bubble_padding_y(extras.compact)))195
})223
})196
.text_size(px(BODY_SIZE))224
.text_size(px(BODY_SIZE))197
.line_height(relative(1.45));225
.line_height(relative(1.45));@@ -227,6 +255,7 @@ fn bubble(227
let has_reactions = !row.reactions.is_empty();255
let has_reactions = !row.reactions.is_empty();228
let saved = extras.saved;256
let saved = extras.saved;229
let mut content = v_flex().gap(px(6.));257
let mut content = v_flex().gap(px(6.));258
content = content.children(importance_header(row, extras.compact));230
if row.forwarded {259
if row.forwarded {231
content = content.child(forwarded_header());260
content = content.child(forwarded_header());232
}261
}@@ -301,7 +330,7 @@ fn bubble(301
.child(330
.child(302
h_flex()331
h_flex()303
.flex_none()332
.flex_none()304
.mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))333
.mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))305
.child(bubble_meta(row, own, saved)),334
.child(bubble_meta(row, own, saved)),306
),335
),307
);336
);@@ -350,12 +379,31 @@ struct BubbleExtras {350
agent_run: Option<AgentRun>,379
agent_run: Option<AgentRun>,351
reaction_proposal: Option<ReactionPill>,380
reaction_proposal: Option<ReactionPill>,352
undo_delete: SharedRowAction,381
undo_delete: SharedRowAction,382
compact: bool,353
}383
}354
384
355
fn agent_chip(run: Option<AgentRun>) -> Option<Div> {385
fn agent_chip(run: Option<AgentRun>) -> Option<Div> {356
run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))386
run.map(|run| div().py(px(2.)).child(run_chip(&run, theme::row_hover())))357
}387
}358
388
389
/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.390
pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {391
let label = importance_label(row.importance)?;392
Some(393
div()394
.debug_selector(|| IMPORTANCE_LABEL_TAG.into())395
.text_size(px(IMPORTANCE_LABEL_SIZE))396
.line_height(px(if compact {397
COMPACT_IMPORTANCE_LINE_HEIGHT398
} else {399
IMPORTANCE_LINE_HEIGHT400
}))401
.font_weight(FontWeight::BOLD)402
.text_color(theme::red())403
.child(label),404
)405
}406
359
pub(super) fn forwarded_header() -> Div {407
pub(super) fn forwarded_header() -> Div {360
h_flex()408
h_flex()361
.gap(px(4.))409
.gap(px(4.))@@ -688,6 +736,7 @@ pub fn render_message_row(688
pinned: _,736
pinned: _,689
reaction_proposal,737
reaction_proposal,690
undo_delete,738
undo_delete,739
compact,691
} = actions;740
} = actions;692
let extras = BubbleExtras {741
let extras = BubbleExtras {693
hover: hovered,742
hover: hovered,@@ -703,13 +752,10 @@ pub fn render_message_row(703
agent_run,752
agent_run,704
reaction_proposal,753
reaction_proposal,705
undo_delete,754
undo_delete,755
compact,706
};756
};707
let own = row.own;757
let own = row.own;708
let spacing = if row.series.has_prev {758
let spacing = px(row_spacing(row.series.has_prev, compact));709
px(2.)710
} else {711
px(SERIES_START_GAP)712
};713
let mut container = v_flex().w_full().px(px(ROW_PADDING));759
let mut container = v_flex().w_full().px(px(ROW_PADDING));714
if let Some(day) = &row.day_header {760
if let Some(day) = &row.day_header {715
container = container.child(day_separator(day));761
container = container.child(day_separator(day));@@ -743,3 +789,16 @@ pub fn render_message_row(743
)789
)744
.into_any_element()790
.into_any_element()745
}791
}792
793
#[cfg(test)]794
mod density_tests {795
use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};796
797
#[test]798
fn compact_density_tightens_gaps_and_bubble_padding() {799
assert!(row_spacing(false, true) < row_spacing(false, false));800
assert!(row_spacing(true, true) < row_spacing(true, false));801
assert!(bubble_padding_y(true) < bubble_padding_y(false));802
assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);803
}804
}@@ -176,7 +176,8 @@ impl Render for MeetingForm {
176
176
}),
177
177
)
178
178
})
179
});
179
})
180
.listbox();
180
181
v_flex()
181
182
.debug_selector(|| "new-meeting".into())
182
183
.gap(px(FIELD_GAP))
@@ -176,7 +176,8 @@ impl Render for MeetingForm {176
}),176
}),177
)177
)178
})178
})179
});179
})180
.listbox();180
v_flex()181
v_flex()181
.debug_selector(|| "new-meeting".into())182
.debug_selector(|| "new-meeting".into())182
.gap(px(FIELD_GAP))183
.gap(px(FIELD_GAP))@@ -10,10 +10,10 @@ use super::widgets::icon;
10
10
use crate::theme;
11
11
12
12
const BANNER_HEIGHT: f32 = 40.;
13
const BANNER_INSET: f32 = ROW_PADDING;
14
13
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
15
14
const BANNER_GAP: f32 = 8.;
16
15
const BANNER_PADDING: f32 = 12.;
16
pub const BANNER_INSET: f32 = ROW_PADDING - BANNER_PADDING;
17
17
const BUTTON_SIZE: f32 = 28.;
18
18
const FALLBACK_PREVIEW: &str = "Pinned message";
19
19
@@ -10,10 +10,10 @@ use super::widgets::icon;10
use crate::theme;10
use crate::theme;11
11
12
const BANNER_HEIGHT: f32 = 40.;12
const BANNER_HEIGHT: f32 = 40.;13
const BANNER_INSET: f32 = ROW_PADDING;14
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";13
pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";15
const BANNER_GAP: f32 = 8.;14
const BANNER_GAP: f32 = 8.;16
const BANNER_PADDING: f32 = 12.;15
const BANNER_PADDING: f32 = 12.;16
pub const BANNER_INSET: f32 = ROW_PADDING - BANNER_PADDING;17
const BUTTON_SIZE: f32 = 28.;17
const BUTTON_SIZE: f32 = 28.;18
const FALLBACK_PREVIEW: &str = "Pinned message";18
const FALLBACK_PREVIEW: &str = "Pinned message";19
19
@@ -111,6 +111,7 @@ pub fn outgoing_for(entry: &ProposalEntry, reply: Option<ReplyPreview>) -> Outgo
111
111
images,
112
112
files: Vec::new(),
113
113
link_preview: None,
114
importance: Default::default(),
114
115
}
115
116
}
116
117
@@ -111,6 +111,7 @@ pub fn outgoing_for(entry: &ProposalEntry, reply: Option<ReplyPreview>) -> Outgo111
images,111
images,112
files: Vec::new(),112
files: Vec::new(),113
link_preview: None,113
link_preview: None,114
importance: Default::default(),114
}115
}115
}116
}116
117
@@ -5,11 +5,10 @@ use gpui_kit::*;
5
5
6
6
use super::shortcuts::keys_for_label;
7
7
use super::sidebar::{SidebarTab, SidebarView};
8
use super::widgets::icon;
8
use super::widgets::{RAIL_BADGE, badge_pill, icon};
9
9
use crate::activity::ActivityCenter;
10
10
use crate::agents::{AgentRuns, runs_handle};
11
11
use crate::app_state::AppState;
12
use crate::format;
13
12
use crate::sidebar_model::{any_unread_channel, unread_chat_count};
14
13
use crate::theme;
15
14
use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
@@ -208,30 +207,20 @@ fn badge(badge: RailBadge) -> Option<Div> {
208
207
.size(px(7.))
209
208
.rounded_full()
210
209
.bg(theme::accent()),
211
RailBadge::Count(count) => div()
212
.absolute()
213
.top(px(5.))
214
.left(px(28.))
215
.min_w(px(16.))
216
.h(px(16.))
217
.px(px(4.))
218
.flex()
219
.items_center()
220
.justify_center()
221
.rounded(px(8.))
222
.bg(theme::accent())
223
.text_color(theme::on_accent())
224
.text_size(px(10.))
225
.line_height(px(16.))
226
.font_weight(FontWeight::BOLD)
227
.child(format::badge_text(count)),
210
RailBadge::Count(count) => {
211
badge_pill(count, RAIL_BADGE, theme::accent(), theme::on_accent())
212
.absolute()
213
.top(px(5.))
214
.left(px(28.))
215
}
228
216
})
229
217
}
230
218
231
219
impl Render for RailView {
232
220
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
233
221
let active = self.sidebar.read(cx).tab();
234
let activity_unread = self.activity.read(cx).feed().unread_count();
222
let activity_unread = self.activity.read(cx).feed().unread_count()
223
+ crate::agent_api::unseen_proposal_count(cx);
235
224
let (unread_chats, channel_dot) = {
236
225
let state = self.state.read(cx);
237
226
(
@@ -5,11 +5,10 @@ use gpui_kit::*;5
5
6
use super::shortcuts::keys_for_label;6
use super::shortcuts::keys_for_label;7
use super::sidebar::{SidebarTab, SidebarView};7
use super::sidebar::{SidebarTab, SidebarView};8
use super::widgets::icon;8
use super::widgets::{RAIL_BADGE, badge_pill, icon};9
use crate::activity::ActivityCenter;9
use crate::activity::ActivityCenter;10
use crate::agents::{AgentRuns, runs_handle};10
use crate::agents::{AgentRuns, runs_handle};11
use crate::app_state::AppState;11
use crate::app_state::AppState;12
use crate::format;13
use crate::sidebar_model::{any_unread_channel, unread_chat_count};12
use crate::sidebar_model::{any_unread_channel, unread_chat_count};14
use crate::theme;13
use crate::theme;15
use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};14
use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};@@ -208,30 +207,20 @@ fn badge(badge: RailBadge) -> Option<Div> {208
.size(px(7.))207
.size(px(7.))209
.rounded_full()208
.rounded_full()210
.bg(theme::accent()),209
.bg(theme::accent()),211
RailBadge::Count(count) => div()210
RailBadge::Count(count) => {212
.absolute()211
badge_pill(count, RAIL_BADGE, theme::accent(), theme::on_accent())213
.top(px(5.))212
.absolute()214
.left(px(28.))213
.top(px(5.))215
.min_w(px(16.))214
.left(px(28.))216
.h(px(16.))215
}217
.px(px(4.))218
.flex()219
.items_center()220
.justify_center()221
.rounded(px(8.))222
.bg(theme::accent())223
.text_color(theme::on_accent())224
.text_size(px(10.))225
.line_height(px(16.))226
.font_weight(FontWeight::BOLD)227
.child(format::badge_text(count)),228
})216
})229
}217
}230
218
231
impl Render for RailView {219
impl Render for RailView {232
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {220
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {233
let active = self.sidebar.read(cx).tab();221
let active = self.sidebar.read(cx).tab();234
let activity_unread = self.activity.read(cx).feed().unread_count();222
let activity_unread = self.activity.read(cx).feed().unread_count()223
+ crate::agent_api::unseen_proposal_count(cx);235
let (unread_chats, channel_dot) = {224
let (unread_chats, channel_dot) = {236
let state = self.state.read(cx);225
let state = self.state.read(cx);237
(226
(@@ -1098,6 +1098,7 @@ impl Render for AppShell {
1098
1098
.text_size(px(14.))
1099
1099
.child(crate::frame_log::probe("first"))
1100
1100
.child(user_activity::input_probe(self.user_input.clone()))
1101
.child(app_ui_kit::long_press::long_press_right_click())
1101
1102
.child(
1102
1103
v_flex()
1103
1104
.debug_selector(|| "shell".into())
@@ -1098,6 +1098,7 @@ impl Render for AppShell {1098
.text_size(px(14.))1098
.text_size(px(14.))1099
.child(crate::frame_log::probe("first"))1099
.child(crate::frame_log::probe("first"))1100
.child(user_activity::input_probe(self.user_input.clone()))1100
.child(user_activity::input_probe(self.user_input.clone()))1101
.child(app_ui_kit::long_press::long_press_right_click())1101
.child(1102
.child(1102
v_flex()1103
v_flex()1103
.debug_selector(|| "shell".into())1104
.debug_selector(|| "shell".into())@@ -7,13 +7,14 @@ use gpui_kit::assets::IconName;
7
7
use gpui_kit::component::button::{Button, ButtonVariants as _};
8
8
use gpui_kit::component::dialog::DialogFooter;
9
9
use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10
use gpui_kit::component::{Icon, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11
11
use gpui_kit::prelude::FluentBuilder as _;
12
12
use gpui_kit::*;
13
13
use store::{
14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
15
Store, TeamRecord,
15
16
};
16
use teams_core::is_notes_chat;
17
use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
17
18
18
19
use super::activity_panel::ActivityPanel;
19
20
use super::avatar::{spec_avatar, square_avatar, with_presence};
@@ -21,7 +22,7 @@ use super::calls_tab::calls_body;
21
22
use super::saved_panel::SavedPanel;
22
23
use super::scroll_edge::with_top_edge;
23
24
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24
use super::widgets::{count_badge, icon, page_header, unread_marker};
25
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
25
26
use crate::agents::AgentsPanel;
26
27
use crate::app_state::{AppEvent, AppState, Selection};
27
28
use crate::channel_menu::{
@@ -67,9 +68,9 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
67
68
const TEAM_ROW_HEIGHT: f32 = 40.;
68
69
const REVEAL_ROW_HEIGHT: f32 = 32.;
69
70
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70
const MENU_ICON_SIZE: f32 = 15.;
71
71
const NOTIFICATION_ICON_SIZE: f32 = 13.;
72
72
const MENTION_ICON_SIZE: f32 = 15.;
73
const IMPORTANCE_MARKER_SIZE: f32 = 16.;
73
74
74
75
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75
76
pub enum SidebarTab {
@@ -94,6 +95,10 @@ impl SidebarTab {
94
95
}
95
96
}
96
97
98
pub fn chat_row_selector(chat_id: &str) -> String {
99
format!("chat-row/{chat_id}")
100
}
101
97
102
#[derive(Clone)]
98
103
struct DraggedChat {
99
104
id: String,
@@ -135,10 +140,6 @@ struct MenuContext {
135
140
folders: Vec<(String, String)>,
136
141
}
137
142
138
fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
139
icon(name, MENU_ICON_SIZE, theme::text_muted())
140
}
141
142
143
fn chat_menu(
143
144
popup: PopupMenu,
144
145
window: &mut Window,
@@ -219,18 +220,18 @@ fn chat_menu(
219
220
if notes {
220
221
return popup;
221
222
}
222
popup = popup
223
.item(
224
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
225
.icon(menu_icon(if muted {
226
IconName::Bell
227
} else {
228
IconName::BellOff
229
}))
230
.on_click(move |_, _, cx| {
231
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
232
}),
233
)
223
popup = popup.item(
224
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
225
.icon(menu_icon(if muted {
226
IconName::Bell
227
} else {
228
IconName::BellOff
229
}))
230
.on_click(move |_, _, cx| {
231
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
232
}),
233
);
234
popup = chat_notifications_submenu(popup, window, cx, context, target)
234
235
.separator()
235
236
.item(
236
237
PopupMenuItem::new("Hide")
@@ -259,7 +260,7 @@ fn chat_menu(
259
260
PopupMenuItem::element(|_, _| {
260
261
div().text_color(theme::red_soft()).child("Leave chat...")
261
262
})
262
.icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
263
.icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))
263
264
.on_click(move |_, window, cx| {
264
265
confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
265
266
}),
@@ -268,6 +269,76 @@ fn chat_menu(
268
269
popup
269
270
}
270
271
272
const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [
273
("All new messages", ChatNotificationMode::AllNewMessages),
274
("Mute", ChatNotificationMode::Mute),
275
];
276
277
const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
278
(
279
"Match settings used for all chats",
280
DesktopNotifications::MatchAllChats,
281
),
282
("Don't get desktop notifications", DesktopNotifications::Off),
283
];
284
285
fn chat_notifications_submenu(
286
popup: PopupMenu,
287
window: &mut Window,
288
cx: &mut Context<PopupMenu>,
289
context: &MenuContext,
290
target: &ChatMenuTarget,
291
) -> PopupMenu {
292
let state = context.state.clone();
293
let chat_id = target.id.clone();
294
let mode = if target.muted {
295
ChatNotificationMode::Mute
296
} else {
297
ChatNotificationMode::AllNewMessages
298
};
299
let desktop = state.read(cx).chat_desktop_notifications(&chat_id);
300
popup.submenu_with_icon(
301
Some(menu_icon(IconName::Bell)),
302
"Manage notifications",
303
window,
304
cx,
305
move |submenu, _, _| {
306
let choose = |chosen_mode: ChatNotificationMode,
307
chosen_desktop: DesktopNotifications| {
308
let (state, chat_id) = (state.clone(), chat_id.clone());
309
move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
310
state.update(cx, |state, cx| {
311
state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)
312
});
313
}
314
};
315
let submenu = submenu.label("Chat notification mode");
316
let submenu =
317
CHAT_NOTIFICATION_MODES
318
.iter()
319
.fold(submenu, |submenu, (label, value)| {
320
submenu.item(
321
PopupMenuItem::new(*label)
322
.checked(*value == mode)
323
.on_click(choose(*value, desktop)),
324
)
325
});
326
let submenu = submenu
327
.separator()
328
.label("Set a desktop notification preference");
329
DESKTOP_NOTIFICATIONS
330
.iter()
331
.fold(submenu, |submenu, (label, value)| {
332
submenu.item(
333
PopupMenuItem::new(*label)
334
.checked(*value == desktop)
335
.on_click(choose(mode, *value)),
336
)
337
})
338
},
339
)
340
}
341
271
342
#[derive(Clone)]
272
343
struct SectionMenuTarget {
273
344
id: String,
@@ -410,7 +481,7 @@ fn section_menu(
410
481
PopupMenuItem::element(|_, _| {
411
482
div().text_color(theme::red_soft()).child("Delete section")
412
483
})
413
.icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
484
.icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
414
485
.disabled(target.read_only)
415
486
.on_click(move |_, window, cx| {
416
487
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
@@ -1088,6 +1159,7 @@ impl SidebarView {
1088
1159
.gap(px(8.))
1089
1160
.items_center()
1090
1161
.child(preview.unwrap_or_else(|| div().flex_1()))
1162
.children(importance_marker(item.importance))
1091
1163
.children(match proposal_agent {
1092
1164
Some(_) => Some(
1093
1165
div()
@@ -1123,6 +1195,7 @@ impl SidebarView {
1123
1195
};
1124
1196
h_flex()
1125
1197
.id(SharedString::from(format!("chat-{}", item.id)))
1198
.debug_selector(|| chat_row_selector(&item.id))
1126
1199
.mx(px(6.))
1127
1200
.h(px(ROW_HEIGHT))
1128
1201
.flex_none()
@@ -1759,6 +1832,16 @@ fn name_color(style: NameStyle) -> Hsla {
1759
1832
}
1760
1833
}
1761
1834
1835
/// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.
1836
fn importance_marker(importance: MessageImportance) -> Option<Icon> {
1837
let name = match importance {
1838
MessageImportance::Normal => return None,
1839
MessageImportance::High => "fluent_important_filled",
1840
MessageImportance::Urgent => "fluent_alert_urgent_filled",
1841
};
1842
Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))
1843
}
1844
1762
1845
fn mention_badge(badge: MentionBadge) -> AnyElement {
1763
1846
match badge {
1764
1847
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),
@@ -7,13 +7,14 @@ use gpui_kit::assets::IconName;7
use gpui_kit::component::button::{Button, ButtonVariants as _};7
use gpui_kit::component::button::{Button, ButtonVariants as _};8
use gpui_kit::component::dialog::DialogFooter;8
use gpui_kit::component::dialog::DialogFooter;9
use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};9
use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};10
use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};10
use gpui_kit::component::{Icon, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};11
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;12
use gpui_kit::*;13
use store::{13
use store::{14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,15
Store, TeamRecord,15
};16
};16
use teams_core::is_notes_chat;17
use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};17
18
18
use super::activity_panel::ActivityPanel;19
use super::activity_panel::ActivityPanel;19
use super::avatar::{spec_avatar, square_avatar, with_presence};20
use super::avatar::{spec_avatar, square_avatar, with_presence};@@ -21,7 +22,7 @@ use super::calls_tab::calls_body;21
use super::saved_panel::SavedPanel;22
use super::saved_panel::SavedPanel;22
use super::scroll_edge::with_top_edge;23
use super::scroll_edge::with_top_edge;23
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};24
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};24
use super::widgets::{count_badge, icon, page_header, unread_marker};25
use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};25
use crate::agents::AgentsPanel;26
use crate::agents::AgentsPanel;26
use crate::app_state::{AppEvent, AppState, Selection};27
use crate::app_state::{AppEvent, AppState, Selection};27
use crate::channel_menu::{28
use crate::channel_menu::{@@ -67,9 +68,9 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";67
const TEAM_ROW_HEIGHT: f32 = 40.;68
const TEAM_ROW_HEIGHT: f32 = 40.;68
const REVEAL_ROW_HEIGHT: f32 = 32.;69
const REVEAL_ROW_HEIGHT: f32 = 32.;69
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;70
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;70
const MENU_ICON_SIZE: f32 = 15.;71
const NOTIFICATION_ICON_SIZE: f32 = 13.;71
const NOTIFICATION_ICON_SIZE: f32 = 13.;72
const MENTION_ICON_SIZE: f32 = 15.;72
const MENTION_ICON_SIZE: f32 = 15.;73
const IMPORTANCE_MARKER_SIZE: f32 = 16.;73
74
74
#[derive(Debug, Clone, Copy, PartialEq, Eq)]75
#[derive(Debug, Clone, Copy, PartialEq, Eq)]75
pub enum SidebarTab {76
pub enum SidebarTab {@@ -94,6 +95,10 @@ impl SidebarTab {94
}95
}95
}96
}96
97
98
pub fn chat_row_selector(chat_id: &str) -> String {99
format!("chat-row/{chat_id}")100
}101
97
#[derive(Clone)]102
#[derive(Clone)]98
struct DraggedChat {103
struct DraggedChat {99
id: String,104
id: String,@@ -135,10 +140,6 @@ struct MenuContext {135
folders: Vec<(String, String)>,140
folders: Vec<(String, String)>,136
}141
}137
142
138
fn menu_icon(name: IconName) -> gpui_kit::component::Icon {139
icon(name, MENU_ICON_SIZE, theme::text_muted())140
}141
142
fn chat_menu(143
fn chat_menu(143
popup: PopupMenu,144
popup: PopupMenu,144
window: &mut Window,145
window: &mut Window,@@ -219,18 +220,18 @@ fn chat_menu(219
if notes {220
if notes {220
return popup;221
return popup;221
}222
}222
popup = popup223
popup = popup.item(223
.item(224
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })224
PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })225
.icon(menu_icon(if muted {225
.icon(menu_icon(if muted {226
IconName::Bell226
IconName::Bell227
} else {227
} else {228
IconName::BellOff228
IconName::BellOff229
}))229
}))230
.on_click(move |_, _, cx| {230
.on_click(move |_, _, cx| {231
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));231
mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));232
}),232
}),233
);233
)234
popup = chat_notifications_submenu(popup, window, cx, context, target)234
.separator()235
.separator()235
.item(236
.item(236
PopupMenuItem::new("Hide")237
PopupMenuItem::new("Hide")@@ -259,7 +260,7 @@ fn chat_menu(259
PopupMenuItem::element(|_, _| {260
PopupMenuItem::element(|_, _| {260
div().text_color(theme::red_soft()).child("Leave chat...")261
div().text_color(theme::red_soft()).child("Leave chat...")261
})262
})262
.icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))263
.icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))263
.on_click(move |_, window, cx| {264
.on_click(move |_, window, cx| {264
confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);265
confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);265
}),266
}),@@ -268,6 +269,76 @@ fn chat_menu(268
popup269
popup269
}270
}270
271
272
const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [273
("All new messages", ChatNotificationMode::AllNewMessages),274
("Mute", ChatNotificationMode::Mute),275
];276
277
const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [278
(279
"Match settings used for all chats",280
DesktopNotifications::MatchAllChats,281
),282
("Don't get desktop notifications", DesktopNotifications::Off),283
];284
285
fn chat_notifications_submenu(286
popup: PopupMenu,287
window: &mut Window,288
cx: &mut Context<PopupMenu>,289
context: &MenuContext,290
target: &ChatMenuTarget,291
) -> PopupMenu {292
let state = context.state.clone();293
let chat_id = target.id.clone();294
let mode = if target.muted {295
ChatNotificationMode::Mute296
} else {297
ChatNotificationMode::AllNewMessages298
};299
let desktop = state.read(cx).chat_desktop_notifications(&chat_id);300
popup.submenu_with_icon(301
Some(menu_icon(IconName::Bell)),302
"Manage notifications",303
window,304
cx,305
move |submenu, _, _| {306
let choose = |chosen_mode: ChatNotificationMode,307
chosen_desktop: DesktopNotifications| {308
let (state, chat_id) = (state.clone(), chat_id.clone());309
move |_: &ClickEvent, _: &mut Window, cx: &mut App| {310
state.update(cx, |state, cx| {311
state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)312
});313
}314
};315
let submenu = submenu.label("Chat notification mode");316
let submenu =317
CHAT_NOTIFICATION_MODES318
.iter()319
.fold(submenu, |submenu, (label, value)| {320
submenu.item(321
PopupMenuItem::new(*label)322
.checked(*value == mode)323
.on_click(choose(*value, desktop)),324
)325
});326
let submenu = submenu327
.separator()328
.label("Set a desktop notification preference");329
DESKTOP_NOTIFICATIONS330
.iter()331
.fold(submenu, |submenu, (label, value)| {332
submenu.item(333
PopupMenuItem::new(*label)334
.checked(*value == desktop)335
.on_click(choose(mode, *value)),336
)337
})338
},339
)340
}341
271
#[derive(Clone)]342
#[derive(Clone)]272
struct SectionMenuTarget {343
struct SectionMenuTarget {273
id: String,344
id: String,@@ -410,7 +481,7 @@ fn section_menu(410
PopupMenuItem::element(|_, _| {481
PopupMenuItem::element(|_, _| {411
div().text_color(theme::red_soft()).child("Delete section")482
div().text_color(theme::red_soft()).child("Delete section")412
})483
})413
.icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))484
.icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))414
.disabled(target.read_only)485
.disabled(target.read_only)415
.on_click(move |_, window, cx| {486
.on_click(move |_, window, cx| {416
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);487
confirm_delete_section(&delete_state, &folder_id, &name, window, cx);@@ -1088,6 +1159,7 @@ impl SidebarView {1088
.gap(px(8.))1159
.gap(px(8.))1089
.items_center()1160
.items_center()1090
.child(preview.unwrap_or_else(|| div().flex_1()))1161
.child(preview.unwrap_or_else(|| div().flex_1()))1162
.children(importance_marker(item.importance))1091
.children(match proposal_agent {1163
.children(match proposal_agent {1092
Some(_) => Some(1164
Some(_) => Some(1093
div()1165
div()@@ -1123,6 +1195,7 @@ impl SidebarView {1123
};1195
};1124
h_flex()1196
h_flex()1125
.id(SharedString::from(format!("chat-{}", item.id)))1197
.id(SharedString::from(format!("chat-{}", item.id)))1198
.debug_selector(|| chat_row_selector(&item.id))1126
.mx(px(6.))1199
.mx(px(6.))1127
.h(px(ROW_HEIGHT))1200
.h(px(ROW_HEIGHT))1128
.flex_none()1201
.flex_none()@@ -1759,6 +1832,16 @@ fn name_color(style: NameStyle) -> Hsla {1759
}1832
}1760
}1833
}1761
1834
1835
/// Teams chat list: red Important / AlertUrgent glyph while the last unread message is marked.1836
fn importance_marker(importance: MessageImportance) -> Option<Icon> {1837
let name = match importance {1838
MessageImportance::Normal => return None,1839
MessageImportance::High => "fluent_important_filled",1840
MessageImportance::Urgent => "fluent_alert_urgent_filled",1841
};1842
Some(symbol(name, IMPORTANCE_MARKER_SIZE, theme::red()))1843
}1844
1762
fn mention_badge(badge: MentionBadge) -> AnyElement {1845
fn mention_badge(badge: MentionBadge) -> AnyElement {1763
match badge {1846
match badge {1764
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),1847
MentionBadge::Count(count) => count_badge(count, false).into_any_element(),@@ -206,7 +206,8 @@ impl StatusMessageDialog {
206
206
}),
207
207
)
208
208
})
209
}),
209
})
210
.listbox(),
210
211
)
211
212
}
212
213
@@ -206,7 +206,8 @@ impl StatusMessageDialog {206
}),206
}),207
)207
)208
})208
})209
}),209
})210
.listbox(),210
)211
)211
}212
}212
213
@@ -0,0 +1,130 @@
1
use serde_json::{Map, Value};
2
3
pub(crate) const PROPERTY_NAME: &str = "conversationNotificationSettings";
4
const ALL_NEW_POSTS: &str = "allNewPosts";
5
const DESKTOP: &str = "dskNotif";
6
const EVERYONE: &str = "everyone";
7
const ON: &str = "On";
8
const OFF: &str = "Off";
9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11
pub enum ChatNotificationMode {
12
#[default]
13
AllNewMessages,
14
Mute,
15
}
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18
pub enum DesktopNotifications {
19
#[default]
20
MatchAllChats,
21
On,
22
Off,
23
}
24
25
#[derive(Debug, Clone, PartialEq, Eq)]
26
pub struct ChatNotificationWrite {
27
pub alerts: bool,
28
pub settings: String,
29
}
30
31
fn stored(raw: Option<&str>) -> Map<String, Value> {
32
raw.and_then(|text| serde_json::from_str::<Value>(text).ok())
33
.and_then(|value| value.as_object().cloned())
34
.unwrap_or_default()
35
}
36
37
pub fn parse_desktop(raw: Option<&str>) -> DesktopNotifications {
38
match stored(raw).get(DESKTOP).and_then(Value::as_str) {
39
Some(ON) => DesktopNotifications::On,
40
Some(OFF) => DesktopNotifications::Off,
41
_ => DesktopNotifications::MatchAllChats,
42
}
43
}
44
45
/// Teams' granular chat setting: `alerts` plus the merged `conversationNotificationSettings` text.
46
pub fn chat_notification_write(
47
raw: Option<&str>,
48
mode: ChatNotificationMode,
49
desktop: DesktopNotifications,
50
) -> ChatNotificationWrite {
51
let mut settings = stored(raw);
52
let desktop_value = match desktop {
53
DesktopNotifications::MatchAllChats => Value::Null,
54
DesktopNotifications::On => Value::String(ON.to_owned()),
55
DesktopNotifications::Off => Value::String(OFF.to_owned()),
56
};
57
settings.insert(DESKTOP.to_owned(), desktop_value);
58
let alerts = mode == ChatNotificationMode::AllNewMessages;
59
settings.insert(
60
ALL_NEW_POSTS.to_owned(),
61
Value::String(if alerts { ON } else { OFF }.to_owned()),
62
);
63
if !alerts {
64
settings.insert(EVERYONE.to_owned(), Value::String(OFF.to_owned()));
65
}
66
ChatNotificationWrite {
67
alerts,
68
settings: Value::Object(settings).to_string(),
69
}
70
}
71
72
#[cfg(test)]
73
mod tests {
74
use serde_json::json;
75
76
use super::*;
77
78
fn written(write: &ChatNotificationWrite) -> Value {
79
serde_json::from_str(&write.settings).unwrap()
80
}
81
82
#[test]
83
fn desktop_preference_is_read_from_dsk_notif() {
84
assert_eq!(parse_desktop(None), DesktopNotifications::MatchAllChats);
85
assert_eq!(
86
parse_desktop(Some(r#"{"dskNotif":"Off"}"#)),
87
DesktopNotifications::Off
88
);
89
assert_eq!(
90
parse_desktop(Some(r#"{"dskNotif":"On","allNewPosts":"On"}"#)),
91
DesktopNotifications::On
92
);
93
assert_eq!(
94
parse_desktop(Some(r#"{"dskNotif":null}"#)),
95
DesktopNotifications::MatchAllChats
96
);
97
assert_eq!(
98
parse_desktop(Some("garbage")),
99
DesktopNotifications::MatchAllChats
100
);
101
}
102
103
#[test]
104
fn all_new_messages_turns_alerts_on_and_keeps_other_fields() {
105
let write = chat_notification_write(
106
Some(r#"{"everyone":"On","future":1}"#),
107
ChatNotificationMode::AllNewMessages,
108
DesktopNotifications::MatchAllChats,
109
);
110
assert!(write.alerts);
111
assert_eq!(
112
written(&write),
113
json!({"everyone": "On", "future": 1, "dskNotif": null, "allNewPosts": "On"})
114
);
115
}
116
117
#[test]
118
fn mute_turns_alerts_and_everyone_mentions_off() {
119
let write = chat_notification_write(
120
Some(r#"{"everyone":"On"}"#),
121
ChatNotificationMode::Mute,
122
DesktopNotifications::Off,
123
);
124
assert!(!write.alerts);
125
assert_eq!(
126
written(&write),
127
json!({"everyone": "Off", "dskNotif": "Off", "allNewPosts": "Off"})
128
);
129
}
130
}
@@ -0,0 +1,130 @@1
use serde_json::{Map, Value};2
3
pub(crate) const PROPERTY_NAME: &str = "conversationNotificationSettings";4
const ALL_NEW_POSTS: &str = "allNewPosts";5
const DESKTOP: &str = "dskNotif";6
const EVERYONE: &str = "everyone";7
const ON: &str = "On";8
const OFF: &str = "Off";9
10
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]11
pub enum ChatNotificationMode {12
#[default]13
AllNewMessages,14
Mute,15
}16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]18
pub enum DesktopNotifications {19
#[default]20
MatchAllChats,21
On,22
Off,23
}24
25
#[derive(Debug, Clone, PartialEq, Eq)]26
pub struct ChatNotificationWrite {27
pub alerts: bool,28
pub settings: String,29
}30
31
fn stored(raw: Option<&str>) -> Map<String, Value> {32
raw.and_then(|text| serde_json::from_str::<Value>(text).ok())33
.and_then(|value| value.as_object().cloned())34
.unwrap_or_default()35
}36
37
pub fn parse_desktop(raw: Option<&str>) -> DesktopNotifications {38
match stored(raw).get(DESKTOP).and_then(Value::as_str) {39
Some(ON) => DesktopNotifications::On,40
Some(OFF) => DesktopNotifications::Off,41
_ => DesktopNotifications::MatchAllChats,42
}43
}44
45
/// Teams' granular chat setting: `alerts` plus the merged `conversationNotificationSettings` text.46
pub fn chat_notification_write(47
raw: Option<&str>,48
mode: ChatNotificationMode,49
desktop: DesktopNotifications,50
) -> ChatNotificationWrite {51
let mut settings = stored(raw);52
let desktop_value = match desktop {53
DesktopNotifications::MatchAllChats => Value::Null,54
DesktopNotifications::On => Value::String(ON.to_owned()),55
DesktopNotifications::Off => Value::String(OFF.to_owned()),56
};57
settings.insert(DESKTOP.to_owned(), desktop_value);58
let alerts = mode == ChatNotificationMode::AllNewMessages;59
settings.insert(60
ALL_NEW_POSTS.to_owned(),61
Value::String(if alerts { ON } else { OFF }.to_owned()),62
);63
if !alerts {64
settings.insert(EVERYONE.to_owned(), Value::String(OFF.to_owned()));65
}66
ChatNotificationWrite {67
alerts,68
settings: Value::Object(settings).to_string(),69
}70
}71
72
#[cfg(test)]73
mod tests {74
use serde_json::json;75
76
use super::*;77
78
fn written(write: &ChatNotificationWrite) -> Value {79
serde_json::from_str(&write.settings).unwrap()80
}81
82
#[test]83
fn desktop_preference_is_read_from_dsk_notif() {84
assert_eq!(parse_desktop(None), DesktopNotifications::MatchAllChats);85
assert_eq!(86
parse_desktop(Some(r#"{"dskNotif":"Off"}"#)),87
DesktopNotifications::Off88
);89
assert_eq!(90
parse_desktop(Some(r#"{"dskNotif":"On","allNewPosts":"On"}"#)),91
DesktopNotifications::On92
);93
assert_eq!(94
parse_desktop(Some(r#"{"dskNotif":null}"#)),95
DesktopNotifications::MatchAllChats96
);97
assert_eq!(98
parse_desktop(Some("garbage")),99
DesktopNotifications::MatchAllChats100
);101
}102
103
#[test]104
fn all_new_messages_turns_alerts_on_and_keeps_other_fields() {105
let write = chat_notification_write(106
Some(r#"{"everyone":"On","future":1}"#),107
ChatNotificationMode::AllNewMessages,108
DesktopNotifications::MatchAllChats,109
);110
assert!(write.alerts);111
assert_eq!(112
written(&write),113
json!({"everyone": "On", "future": 1, "dskNotif": null, "allNewPosts": "On"})114
);115
}116
117
#[test]118
fn mute_turns_alerts_and_everyone_mentions_off() {119
let write = chat_notification_write(120
Some(r#"{"everyone":"On"}"#),121
ChatNotificationMode::Mute,122
DesktopNotifications::Off,123
);124
assert!(!write.alerts);125
assert_eq!(126
written(&write),127
json!({"everyone": "Off", "dskNotif": "Off", "allNewPosts": "Off"})128
);129
}130
}@@ -0,0 +1,733 @@
1
use serde_json::{Map, Value, json};
2
use session::Session;
3
4
use crate::error::Result;
5
use crate::messages::{MessageTransport, SessionMessageTransport};
6
use crate::settings::UserSettings;
7
8
const READ_RECEIPTS_KEY: &str = "readReceiptsEnabled";
9
const MESSAGE_DENSITY_KEY: &str = "messageDensity";
10
const COMPOSE_SETTINGS_KEY: &str = "composeUserSettings";
11
const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings";
12
const ENTER_KEY_FIELD: &str = "enterKeyBehavior";
13
const MESSAGING_SETTINGS: &str = "messagingSettings";
14
const UP_ARROW_FIELD: &str = "upArrowKeyBehavior";
15
const TOAST_SETTINGS: &str = "toastSettings";
16
const ACTIVITY_SETTINGS: &str = "activityGenerationSettings";
17
const EMAIL_SETTINGS: &str = "emailSettings";
18
const CHAT_SETTINGS: &str = "chatSettings";
19
const SELECTED_PRESET_FIELD: &str = "selectedPreset";
20
const MEETING_CHAT_FIELD: &str = "meetingChatNotification";
21
const SHOW_PREVIEW_FIELD: &str = "ShowPreviewInToasts";
22
const CHAT_MESSAGES_FIELD: &str = "Chat";
23
const PERSONAL_MENTIONS_FIELD: &str = "MentionInChat_Person_v2";
24
const EVERYONE_MENTIONS_FIELD: &str = "MentionInChat_Everyone";
25
const LIKES_FIELD: &str = "LikeInChat_v2";
26
const ACCOUNT_KEYS: [&str; 4] = [
27
READ_RECEIPTS_KEY,
28
MESSAGE_DENSITY_KEY,
29
COMPOSE_SETTINGS_KEY,
30
PERSONAL_SETTINGS_KEY,
31
];
32
33
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
34
pub enum MessageDensity {
35
#[default]
36
Comfy,
37
Compact,
38
}
39
40
impl MessageDensity {
41
pub const ALL: [MessageDensity; 2] = [MessageDensity::Comfy, MessageDensity::Compact];
42
43
pub fn property_value(self) -> &'static str {
44
match self {
45
MessageDensity::Comfy => "COMFY",
46
MessageDensity::Compact => "COMPACT",
47
}
48
}
49
50
fn from_property(value: &str) -> Option<Self> {
51
MessageDensity::ALL
52
.into_iter()
53
.find(|density| density.property_value() == value)
54
}
55
}
56
57
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
58
pub enum EnterKeyBehavior {
59
#[default]
60
Send,
61
NewLine,
62
}
63
64
impl EnterKeyBehavior {
65
pub const ALL: [EnterKeyBehavior; 2] = [EnterKeyBehavior::Send, EnterKeyBehavior::NewLine];
66
67
pub fn property_value(self) -> &'static str {
68
match self {
69
EnterKeyBehavior::Send => "Default",
70
EnterKeyBehavior::NewLine => "CreateNewLine",
71
}
72
}
73
74
fn from_property(value: &str) -> Option<Self> {
75
EnterKeyBehavior::ALL
76
.into_iter()
77
.find(|behavior| behavior.property_value() == value)
78
}
79
}
80
81
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
82
pub enum UpArrowBehavior {
83
NavigateToMessages,
84
#[default]
85
EditLastMessage,
86
StayInCompose,
87
}
88
89
impl UpArrowBehavior {
90
pub const ALL: [UpArrowBehavior; 3] = [
91
UpArrowBehavior::NavigateToMessages,
92
UpArrowBehavior::EditLastMessage,
93
UpArrowBehavior::StayInCompose,
94
];
95
96
pub fn property_value(self) -> &'static str {
97
match self {
98
UpArrowBehavior::NavigateToMessages => "NAVIGATE_TO_MESSAGES",
99
UpArrowBehavior::EditLastMessage => "EDIT_LAST_MESSAGE",
100
UpArrowBehavior::StayInCompose => "STAY_IN_COMPOSE",
101
}
102
}
103
104
fn from_property(value: &str) -> Option<Self> {
105
UpArrowBehavior::ALL
106
.into_iter()
107
.find(|behavior| behavior.property_value() == value)
108
}
109
}
110
111
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
112
pub enum NotificationPreset {
113
AllActivity,
114
MentionsAndReplies,
115
#[default]
116
Customised,
117
}
118
119
impl NotificationPreset {
120
pub const ALL: [NotificationPreset; 3] = [
121
NotificationPreset::AllActivity,
122
NotificationPreset::MentionsAndReplies,
123
NotificationPreset::Customised,
124
];
125
126
pub fn property_value(self) -> i64 {
127
match self {
128
NotificationPreset::AllActivity => 1,
129
NotificationPreset::MentionsAndReplies => 2,
130
NotificationPreset::Customised => 3,
131
}
132
}
133
134
fn from_property(value: &Value) -> Option<Self> {
135
let number = value
136
.as_i64()
137
.or_else(|| value.as_str().and_then(|text| text.parse().ok()))?;
138
NotificationPreset::ALL
139
.into_iter()
140
.find(|preset| preset.property_value() == number)
141
}
142
}
143
144
/// Teams' "Show in Activity and banner" / "Show in Activity" / "Off" choice, stored as toast, email and activity flags.
145
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
146
pub enum ActivityAlert {
147
#[default]
148
BannerAndFeed,
149
OnlyFeed,
150
OnlyBanner,
151
Off,
152
}
153
154
impl ActivityAlert {
155
fn flags(self) -> (bool, bool, bool) {
156
match self {
157
ActivityAlert::Off => (false, false, false),
158
ActivityAlert::OnlyFeed => (false, false, true),
159
ActivityAlert::OnlyBanner => (true, false, true),
160
ActivityAlert::BannerAndFeed => (true, true, true),
161
}
162
}
163
164
pub fn shows_banner(self) -> bool {
165
matches!(
166
self,
167
ActivityAlert::BannerAndFeed | ActivityAlert::OnlyBanner
168
)
169
}
170
}
171
172
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
173
pub enum MeetingChatNotifications {
174
Mute,
175
Unmute,
176
#[default]
177
MuteUntilJoin,
178
}
179
180
impl MeetingChatNotifications {
181
pub const ALL: [MeetingChatNotifications; 3] = [
182
MeetingChatNotifications::Mute,
183
MeetingChatNotifications::Unmute,
184
MeetingChatNotifications::MuteUntilJoin,
185
];
186
187
pub fn property_value(self) -> &'static str {
188
match self {
189
MeetingChatNotifications::Mute => "MeetingsManuallyUnmuted",
190
MeetingChatNotifications::Unmute => "MeetingsUserIsInvitedTo",
191
MeetingChatNotifications::MuteUntilJoin => "MeetingsUserParticipatesIn",
192
}
193
}
194
195
fn from_property(value: &str) -> Option<Self> {
196
MeetingChatNotifications::ALL
197
.into_iter()
198
.find(|choice| choice.property_value() == value)
199
}
200
}
201
202
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203
pub struct NotificationAccountSettings {
204
pub preset: NotificationPreset,
205
pub chat_messages: ActivityAlert,
206
pub personal_mentions: ActivityAlert,
207
pub everyone_mentions: ActivityAlert,
208
pub likes: ActivityAlert,
209
pub show_preview: bool,
210
pub meeting_chats: MeetingChatNotifications,
211
}
212
213
impl Default for NotificationAccountSettings {
214
fn default() -> Self {
215
NotificationAccountSettings {
216
preset: NotificationPreset::default(),
217
chat_messages: ActivityAlert::OnlyBanner,
218
personal_mentions: ActivityAlert::BannerAndFeed,
219
everyone_mentions: ActivityAlert::BannerAndFeed,
220
likes: ActivityAlert::BannerAndFeed,
221
show_preview: true,
222
meeting_chats: MeetingChatNotifications::default(),
223
}
224
}
225
}
226
227
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228
pub struct ChatAccountSettings {
229
pub read_receipts: bool,
230
pub message_density: MessageDensity,
231
pub enter_key: EnterKeyBehavior,
232
pub up_arrow: UpArrowBehavior,
233
pub notifications: NotificationAccountSettings,
234
}
235
236
impl Default for ChatAccountSettings {
237
fn default() -> Self {
238
ChatAccountSettings {
239
read_receipts: true,
240
message_density: MessageDensity::default(),
241
enter_key: EnterKeyBehavior::default(),
242
up_arrow: UpArrowBehavior::default(),
243
notifications: NotificationAccountSettings::default(),
244
}
245
}
246
}
247
248
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249
pub enum ChatSettingChange {
250
ReadReceipts(bool),
251
MessageDensity(MessageDensity),
252
EnterKey(EnterKeyBehavior),
253
UpArrow(UpArrowBehavior),
254
Preset(NotificationPreset),
255
ChatMessages(ActivityAlert),
256
PersonalMentions(ActivityAlert),
257
EveryoneMentions(ActivityAlert),
258
Likes(ActivityAlert),
259
ShowPreview(bool),
260
MeetingChats(MeetingChatNotifications),
261
}
262
263
/// The account properties Teams keeps these settings in, as last read from `users/ME/properties`.
264
#[derive(Debug, Clone, PartialEq, Default)]
265
pub struct ChatSettingsDocument {
266
properties: Map<String, Value>,
267
}
268
269
impl ChatSettingsDocument {
270
pub fn from_properties(properties: &Value) -> Self {
271
let properties = ACCOUNT_KEYS
272
.iter()
273
.filter_map(|key| Some(((*key).to_owned(), properties.get(*key)?.clone())))
274
.collect();
275
ChatSettingsDocument { properties }
276
}
277
278
pub fn from_text(text: &str) -> Self {
279
serde_json::from_str::<Value>(text)
280
.map(|value| ChatSettingsDocument::from_properties(&value))
281
.unwrap_or_default()
282
}
283
284
pub fn to_text(&self) -> String {
285
Value::Object(self.properties.clone()).to_string()
286
}
287
288
pub fn settings(&self) -> ChatAccountSettings {
289
let defaults = ChatAccountSettings::default();
290
let personal = self.json_property(PERSONAL_SETTINGS_KEY);
291
let compose = self.json_property(COMPOSE_SETTINGS_KEY);
292
ChatAccountSettings {
293
read_receipts: self
294
.properties
295
.get(READ_RECEIPTS_KEY)
296
.and_then(flag)
297
.unwrap_or(defaults.read_receipts),
298
message_density: self
299
.properties
300
.get(MESSAGE_DENSITY_KEY)
301
.and_then(Value::as_str)
302
.and_then(MessageDensity::from_property)
303
.unwrap_or(defaults.message_density),
304
enter_key: text_at(&compose, &[ENTER_KEY_FIELD])
305
.and_then(EnterKeyBehavior::from_property)
306
.unwrap_or(defaults.enter_key),
307
up_arrow: text_at(&personal, &[MESSAGING_SETTINGS, UP_ARROW_FIELD])
308
.and_then(UpArrowBehavior::from_property)
309
.unwrap_or(defaults.up_arrow),
310
notifications: notification_settings(&personal),
311
}
312
}
313
314
/// Applies the change and returns the property write Teams makes for it: name and value.
315
pub fn apply(&mut self, change: ChatSettingChange) -> (&'static str, Value) {
316
let (name, value) = match change {
317
ChatSettingChange::ReadReceipts(enabled) => {
318
(READ_RECEIPTS_KEY, Value::String(enabled.to_string()))
319
}
320
ChatSettingChange::MessageDensity(density) => (
321
MESSAGE_DENSITY_KEY,
322
Value::String(density.property_value().to_owned()),
323
),
324
ChatSettingChange::EnterKey(behavior) => {
325
let mut compose = self.json_property(COMPOSE_SETTINGS_KEY);
326
compose.insert(ENTER_KEY_FIELD.to_owned(), json!(behavior.property_value()));
327
(
328
COMPOSE_SETTINGS_KEY,
329
Value::String(Value::Object(compose).to_string()),
330
)
331
}
332
personal_change => {
333
let mut personal = self.json_property(PERSONAL_SETTINGS_KEY);
334
apply_personal(&mut personal, personal_change);
335
(
336
PERSONAL_SETTINGS_KEY,
337
Value::String(Value::Object(personal).to_string()),
338
)
339
}
340
};
341
self.properties.insert(name.to_owned(), value.clone());
342
(name, value)
343
}
344
345
fn json_property(&self, key: &str) -> Map<String, Value> {
346
match self.properties.get(key) {
347
Some(Value::String(text)) => serde_json::from_str::<Value>(text)
348
.ok()
349
.and_then(|value| value.as_object().cloned())
350
.unwrap_or_default(),
351
Some(Value::Object(object)) => object.clone(),
352
_ => Map::new(),
353
}
354
}
355
}
356
357
fn flag(value: &Value) -> Option<bool> {
358
match value {
359
Value::Bool(flag) => Some(*flag),
360
Value::String(text) => Some(!text.trim().eq_ignore_ascii_case("false")),
361
_ => None,
362
}
363
}
364
365
fn value_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a Value> {
366
let (first, rest) = path.split_first()?;
367
rest.iter()
368
.try_fold(object.get(*first)?, |value, field| value.get(*field))
369
}
370
371
fn text_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a str> {
372
value_at(object, path)?.as_str()
373
}
374
375
fn flag_at(object: &Map<String, Value>, group: &str, field: &str) -> Option<bool> {
376
value_at(object, &[group, field]).and_then(flag)
377
}
378
379
fn activity_alert(
380
personal: &Map<String, Value>,
381
field: &str,
382
fallback: ActivityAlert,
383
) -> ActivityAlert {
384
let (fallback_toast, _, fallback_activity) = fallback.flags();
385
let toast = flag_at(personal, TOAST_SETTINGS, field).unwrap_or(fallback_toast);
386
let activity = flag_at(personal, ACTIVITY_SETTINGS, field).unwrap_or(fallback_activity);
387
match (activity, toast) {
388
(true, true) => ActivityAlert::BannerAndFeed,
389
(true, false) => ActivityAlert::OnlyFeed,
390
(false, true) => ActivityAlert::OnlyBanner,
391
(false, false) => ActivityAlert::Off,
392
}
393
}
394
395
fn chat_messages_alert(personal: &Map<String, Value>) -> ActivityAlert {
396
match flag_at(personal, TOAST_SETTINGS, CHAT_MESSAGES_FIELD) {
397
Some(false) => ActivityAlert::Off,
398
_ => ActivityAlert::OnlyBanner,
399
}
400
}
401
402
fn notification_settings(personal: &Map<String, Value>) -> NotificationAccountSettings {
403
let defaults = NotificationAccountSettings::default();
404
NotificationAccountSettings {
405
preset: personal
406
.get(SELECTED_PRESET_FIELD)
407
.and_then(NotificationPreset::from_property)
408
.unwrap_or(defaults.preset),
409
chat_messages: chat_messages_alert(personal),
410
personal_mentions: activity_alert(
411
personal,
412
PERSONAL_MENTIONS_FIELD,
413
defaults.personal_mentions,
414
),
415
everyone_mentions: activity_alert(
416
personal,
417
EVERYONE_MENTIONS_FIELD,
418
defaults.everyone_mentions,
419
),
420
likes: activity_alert(personal, LIKES_FIELD, defaults.likes),
421
show_preview: text_at(personal, &[TOAST_SETTINGS, SHOW_PREVIEW_FIELD])
422
.map_or(defaults.show_preview, |value| value != "Off"),
423
meeting_chats: text_at(personal, &[CHAT_SETTINGS, MEETING_CHAT_FIELD])
424
.and_then(MeetingChatNotifications::from_property)
425
.unwrap_or(defaults.meeting_chats),
426
}
427
}
428
429
fn group_mut<'a>(personal: &'a mut Map<String, Value>, group: &str) -> &'a mut Map<String, Value> {
430
let entry = personal
431
.entry(group.to_owned())
432
.or_insert_with(|| Value::Object(Map::new()));
433
if !entry.is_object() {
434
*entry = Value::Object(Map::new());
435
}
436
entry.as_object_mut().expect("group is an object")
437
}
438
439
fn set_field(personal: &mut Map<String, Value>, group: &str, field: &str, value: Value) {
440
group_mut(personal, group).insert(field.to_owned(), value);
441
}
442
443
fn set_alert(personal: &mut Map<String, Value>, field: &str, alert: ActivityAlert) {
444
let (toast, email, activity) = alert.flags();
445
set_field(personal, TOAST_SETTINGS, field, Value::Bool(toast));
446
set_field(personal, EMAIL_SETTINGS, field, Value::Bool(email));
447
set_field(personal, ACTIVITY_SETTINGS, field, Value::Bool(activity));
448
}
449
450
fn apply_personal(personal: &mut Map<String, Value>, change: ChatSettingChange) {
451
match change {
452
ChatSettingChange::UpArrow(behavior) => set_field(
453
personal,
454
MESSAGING_SETTINGS,
455
UP_ARROW_FIELD,
456
json!(behavior.property_value()),
457
),
458
ChatSettingChange::Preset(preset) => {
459
personal.insert(
460
SELECTED_PRESET_FIELD.to_owned(),
461
json!(preset.property_value()),
462
);
463
}
464
ChatSettingChange::ChatMessages(alert) => set_alert(personal, CHAT_MESSAGES_FIELD, alert),
465
ChatSettingChange::PersonalMentions(alert) => {
466
set_alert(personal, PERSONAL_MENTIONS_FIELD, alert)
467
}
468
ChatSettingChange::EveryoneMentions(alert) => {
469
set_alert(personal, EVERYONE_MENTIONS_FIELD, alert)
470
}
471
ChatSettingChange::Likes(alert) => set_alert(personal, LIKES_FIELD, alert),
472
ChatSettingChange::ShowPreview(shown) => set_field(
473
personal,
474
TOAST_SETTINGS,
475
SHOW_PREVIEW_FIELD,
476
json!(if shown { "On" } else { "Off" }),
477
),
478
ChatSettingChange::MeetingChats(choice) => set_field(
479
personal,
480
CHAT_SETTINGS,
481
MEETING_CHAT_FIELD,
482
json!(choice.property_value()),
483
),
484
ChatSettingChange::ReadReceipts(_)
485
| ChatSettingChange::MessageDensity(_)
486
| ChatSettingChange::EnterKey(_) => {}
487
}
488
}
489
490
pub struct ChatSettingsClient<T: MessageTransport = SessionMessageTransport> {
491
settings: UserSettings<T>,
492
}
493
494
impl ChatSettingsClient<SessionMessageTransport> {
495
pub fn new(session: &Session) -> Self {
496
ChatSettingsClient::with_settings(UserSettings::new(session))
497
}
498
}
499
500
impl<T: MessageTransport> ChatSettingsClient<T> {
501
pub fn with_settings(settings: UserSettings<T>) -> Self {
502
ChatSettingsClient { settings }
503
}
504
505
pub async fn read(&self) -> Result<ChatSettingsDocument> {
506
Ok(ChatSettingsDocument::from_properties(
507
&self.settings.properties().await?,
508
))
509
}
510
511
/// Reads the current properties first so fields this client does not know survive the write.
512
pub async fn write(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
513
let mut document = self.read().await?;
514
let (name, value) = document.apply(change);
515
self.settings.set_property(name, value).await?;
516
Ok(document)
517
}
518
}
519
520
#[cfg(test)]
521
mod tests {
522
use std::collections::VecDeque;
523
use std::sync::Mutex;
524
525
use session::{ApiResponse, Method, Request};
526
527
use super::*;
528
529
struct Canned {
530
answers: Mutex<VecDeque<(u16, Value)>>,
531
requests: Mutex<Vec<Request>>,
532
}
533
534
impl MessageTransport for &Canned {
535
async fn send(&self, request: Request) -> Result<ApiResponse> {
536
self.requests.lock().unwrap().push(request);
537
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");
538
Ok(ApiResponse {
539
status,
540
body,
541
retry_after: None,
542
})
543
}
544
}
545
546
fn parsed(text: &str) -> Value {
547
serde_json::from_str(text).unwrap()
548
}
549
550
#[test]
551
fn missing_properties_give_the_teams_defaults() {
552
let settings = ChatSettingsDocument::from_properties(&json!({})).settings();
553
assert_eq!(settings, ChatAccountSettings::default());
554
assert!(settings.read_receipts);
555
assert_eq!(settings.message_density, MessageDensity::Comfy);
556
assert_eq!(settings.enter_key, EnterKeyBehavior::Send);
557
assert_eq!(settings.up_arrow, UpArrowBehavior::EditLastMessage);
558
assert_eq!(
559
settings.notifications.preset,
560
NotificationPreset::Customised
561
);
562
assert_eq!(
563
settings.notifications.meeting_chats,
564
MeetingChatNotifications::MuteUntilJoin
565
);
566
}
567
568
#[test]
569
fn reads_every_setting_from_the_teams_properties() {
570
let personal = json!({
571
"messagingSettings": {"upArrowKeyBehavior": "STAY_IN_COMPOSE"},
572
"selectedPreset": 2,
573
"toastSettings": {"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true, "ShowPreviewInToasts": "Off"},
574
"activityGenerationSettings": {"MentionInChat_Person_v2": true, "LikeInChat_v2": false, "MentionInChat_Everyone": false},
575
"chatSettings": {"meetingChatNotification": "MeetingsUserIsInvitedTo"},
576
});
577
let document = ChatSettingsDocument::from_properties(&json!({
578
"readReceiptsEnabled": "false",
579
"messageDensity": "COMPACT",
580
"composeUserSettings": "{\"enterKeyBehavior\":\"CreateNewLine\"}",
581
"userPersonalSettings": personal.to_string(),
582
"unrelated": "dropped",
583
}));
584
let settings = document.settings();
585
assert!(!settings.read_receipts);
586
assert_eq!(settings.message_density, MessageDensity::Compact);
587
assert_eq!(settings.enter_key, EnterKeyBehavior::NewLine);
588
assert_eq!(settings.up_arrow, UpArrowBehavior::StayInCompose);
589
let notifications = settings.notifications;
590
assert_eq!(notifications.preset, NotificationPreset::MentionsAndReplies);
591
assert_eq!(notifications.chat_messages, ActivityAlert::Off);
592
assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed);
593
assert_eq!(notifications.likes, ActivityAlert::OnlyBanner);
594
assert_eq!(notifications.everyone_mentions, ActivityAlert::OnlyBanner);
595
assert!(!notifications.show_preview);
596
assert_eq!(
597
notifications.meeting_chats,
598
MeetingChatNotifications::Unmute
599
);
600
assert!(!document.to_text().contains("unrelated"));
601
}
602
603
#[test]
604
fn read_receipts_follow_teams_parsing() {
605
let read = |value: Value| {
606
ChatSettingsDocument::from_properties(&json!({"readReceiptsEnabled": value}))
607
.settings()
608
.read_receipts
609
};
610
assert!(read(json!("true")));
611
assert!(!read(json!(" False ")));
612
assert!(!read(json!(false)));
613
assert!(read(json!("anything")));
614
}
615
616
#[test]
617
fn plain_properties_are_written_as_teams_strings() {
618
let mut document = ChatSettingsDocument::default();
619
assert_eq!(
620
document.apply(ChatSettingChange::ReadReceipts(false)),
621
("readReceiptsEnabled", json!("false"))
622
);
623
assert_eq!(
624
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact)),
625
("messageDensity", json!("COMPACT"))
626
);
627
let settings = document.settings();
628
assert!(!settings.read_receipts);
629
assert_eq!(settings.message_density, MessageDensity::Compact);
630
}
631
632
#[test]
633
fn enter_key_keeps_other_compose_fields() {
634
let mut document = ChatSettingsDocument::from_properties(&json!({
635
"composeUserSettings": "{\"enterKeyBehavior\":\"Default\",\"future\":1}"
636
}));
637
let (name, value) = document.apply(ChatSettingChange::EnterKey(EnterKeyBehavior::NewLine));
638
assert_eq!(name, "composeUserSettings");
639
assert_eq!(
640
parsed(value.as_str().unwrap()),
641
json!({"enterKeyBehavior": "CreateNewLine", "future": 1})
642
);
643
}
644
645
#[test]
646
fn personal_settings_changes_keep_unknown_fields() {
647
let mut document = ChatSettingsDocument::from_properties(&json!({
648
"userPersonalSettings": "{\"soundsSettings\":{\"alertSound\":\"All\"},\"messagingSettings\":{\"shouldShowDiscoverApp\":true}}"
649
}));
650
document.apply(ChatSettingChange::UpArrow(
651
UpArrowBehavior::NavigateToMessages,
652
));
653
let (name, value) =
654
document.apply(ChatSettingChange::Preset(NotificationPreset::AllActivity));
655
assert_eq!(name, "userPersonalSettings");
656
assert_eq!(
657
parsed(value.as_str().unwrap()),
658
json!({
659
"soundsSettings": {"alertSound": "All"},
660
"messagingSettings": {"shouldShowDiscoverApp": true, "upArrowKeyBehavior": "NAVIGATE_TO_MESSAGES"},
661
"selectedPreset": 1,
662
})
663
);
664
}
665
666
#[test]
667
fn alerts_write_toast_email_and_activity_like_teams() {
668
let mut document = ChatSettingsDocument::default();
669
document.apply(ChatSettingChange::ChatMessages(ActivityAlert::Off));
670
document.apply(ChatSettingChange::PersonalMentions(ActivityAlert::OnlyFeed));
671
let (_, value) = document.apply(ChatSettingChange::Likes(ActivityAlert::BannerAndFeed));
672
let personal = parsed(value.as_str().unwrap());
673
assert_eq!(
674
personal["toastSettings"],
675
json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true})
676
);
677
assert_eq!(
678
personal["emailSettings"],
679
json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true})
680
);
681
assert_eq!(
682
personal["activityGenerationSettings"],
683
json!({"Chat": false, "MentionInChat_Person_v2": true, "LikeInChat_v2": true})
684
);
685
let notifications = document.settings().notifications;
686
assert_eq!(notifications.chat_messages, ActivityAlert::Off);
687
assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed);
688
assert_eq!(notifications.likes, ActivityAlert::BannerAndFeed);
689
}
690
691
#[test]
692
fn preview_and_meeting_chats_round_trip() {
693
let mut document = ChatSettingsDocument::default();
694
document.apply(ChatSettingChange::ShowPreview(false));
695
document.apply(ChatSettingChange::MeetingChats(
696
MeetingChatNotifications::Mute,
697
));
698
let restored = ChatSettingsDocument::from_text(&document.to_text());
699
let notifications = restored.settings().notifications;
700
assert!(!notifications.show_preview);
701
assert_eq!(notifications.meeting_chats, MeetingChatNotifications::Mute);
702
assert_eq!(restored, document);
703
}
704
705
#[tokio::test]
706
async fn write_reads_then_puts_the_named_property() {
707
let transport = Canned {
708
answers: Mutex::new(
709
vec![
710
(200, json!({"messageDensity": "COMFY", "other": 1})),
711
(200, Value::Null),
712
]
713
.into(),
714
),
715
requests: Mutex::new(Vec::new()),
716
};
717
let client =
718
ChatSettingsClient::with_settings(UserSettings::with_transport(&transport, "emea"));
719
let document = client
720
.write(ChatSettingChange::MessageDensity(MessageDensity::Compact))
721
.await
722
.unwrap();
723
assert_eq!(document.settings().message_density, MessageDensity::Compact);
724
let requests = transport.requests.lock().unwrap();
725
assert_eq!(requests[0].method, Method::Get);
726
assert_eq!(requests[1].method, Method::Put);
727
assert_eq!(
728
requests[1].url,
729
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=messageDensity"
730
);
731
assert_eq!(requests[1].body, Some(json!({"messageDensity": "COMPACT"})));
732
}
733
}
@@ -0,0 +1,733 @@1
use serde_json::{Map, Value, json};2
use session::Session;3
4
use crate::error::Result;5
use crate::messages::{MessageTransport, SessionMessageTransport};6
use crate::settings::UserSettings;7
8
const READ_RECEIPTS_KEY: &str = "readReceiptsEnabled";9
const MESSAGE_DENSITY_KEY: &str = "messageDensity";10
const COMPOSE_SETTINGS_KEY: &str = "composeUserSettings";11
const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings";12
const ENTER_KEY_FIELD: &str = "enterKeyBehavior";13
const MESSAGING_SETTINGS: &str = "messagingSettings";14
const UP_ARROW_FIELD: &str = "upArrowKeyBehavior";15
const TOAST_SETTINGS: &str = "toastSettings";16
const ACTIVITY_SETTINGS: &str = "activityGenerationSettings";17
const EMAIL_SETTINGS: &str = "emailSettings";18
const CHAT_SETTINGS: &str = "chatSettings";19
const SELECTED_PRESET_FIELD: &str = "selectedPreset";20
const MEETING_CHAT_FIELD: &str = "meetingChatNotification";21
const SHOW_PREVIEW_FIELD: &str = "ShowPreviewInToasts";22
const CHAT_MESSAGES_FIELD: &str = "Chat";23
const PERSONAL_MENTIONS_FIELD: &str = "MentionInChat_Person_v2";24
const EVERYONE_MENTIONS_FIELD: &str = "MentionInChat_Everyone";25
const LIKES_FIELD: &str = "LikeInChat_v2";26
const ACCOUNT_KEYS: [&str; 4] = [27
READ_RECEIPTS_KEY,28
MESSAGE_DENSITY_KEY,29
COMPOSE_SETTINGS_KEY,30
PERSONAL_SETTINGS_KEY,31
];32
33
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]34
pub enum MessageDensity {35
#[default]36
Comfy,37
Compact,38
}39
40
impl MessageDensity {41
pub const ALL: [MessageDensity; 2] = [MessageDensity::Comfy, MessageDensity::Compact];42
43
pub fn property_value(self) -> &'static str {44
match self {45
MessageDensity::Comfy => "COMFY",46
MessageDensity::Compact => "COMPACT",47
}48
}49
50
fn from_property(value: &str) -> Option<Self> {51
MessageDensity::ALL52
.into_iter()53
.find(|density| density.property_value() == value)54
}55
}56
57
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]58
pub enum EnterKeyBehavior {59
#[default]60
Send,61
NewLine,62
}63
64
impl EnterKeyBehavior {65
pub const ALL: [EnterKeyBehavior; 2] = [EnterKeyBehavior::Send, EnterKeyBehavior::NewLine];66
67
pub fn property_value(self) -> &'static str {68
match self {69
EnterKeyBehavior::Send => "Default",70
EnterKeyBehavior::NewLine => "CreateNewLine",71
}72
}73
74
fn from_property(value: &str) -> Option<Self> {75
EnterKeyBehavior::ALL76
.into_iter()77
.find(|behavior| behavior.property_value() == value)78
}79
}80
81
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]82
pub enum UpArrowBehavior {83
NavigateToMessages,84
#[default]85
EditLastMessage,86
StayInCompose,87
}88
89
impl UpArrowBehavior {90
pub const ALL: [UpArrowBehavior; 3] = [91
UpArrowBehavior::NavigateToMessages,92
UpArrowBehavior::EditLastMessage,93
UpArrowBehavior::StayInCompose,94
];95
96
pub fn property_value(self) -> &'static str {97
match self {98
UpArrowBehavior::NavigateToMessages => "NAVIGATE_TO_MESSAGES",99
UpArrowBehavior::EditLastMessage => "EDIT_LAST_MESSAGE",100
UpArrowBehavior::StayInCompose => "STAY_IN_COMPOSE",101
}102
}103
104
fn from_property(value: &str) -> Option<Self> {105
UpArrowBehavior::ALL106
.into_iter()107
.find(|behavior| behavior.property_value() == value)108
}109
}110
111
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]112
pub enum NotificationPreset {113
AllActivity,114
MentionsAndReplies,115
#[default]116
Customised,117
}118
119
impl NotificationPreset {120
pub const ALL: [NotificationPreset; 3] = [121
NotificationPreset::AllActivity,122
NotificationPreset::MentionsAndReplies,123
NotificationPreset::Customised,124
];125
126
pub fn property_value(self) -> i64 {127
match self {128
NotificationPreset::AllActivity => 1,129
NotificationPreset::MentionsAndReplies => 2,130
NotificationPreset::Customised => 3,131
}132
}133
134
fn from_property(value: &Value) -> Option<Self> {135
let number = value136
.as_i64()137
.or_else(|| value.as_str().and_then(|text| text.parse().ok()))?;138
NotificationPreset::ALL139
.into_iter()140
.find(|preset| preset.property_value() == number)141
}142
}143
144
/// Teams' "Show in Activity and banner" / "Show in Activity" / "Off" choice, stored as toast, email and activity flags.145
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]146
pub enum ActivityAlert {147
#[default]148
BannerAndFeed,149
OnlyFeed,150
OnlyBanner,151
Off,152
}153
154
impl ActivityAlert {155
fn flags(self) -> (bool, bool, bool) {156
match self {157
ActivityAlert::Off => (false, false, false),158
ActivityAlert::OnlyFeed => (false, false, true),159
ActivityAlert::OnlyBanner => (true, false, true),160
ActivityAlert::BannerAndFeed => (true, true, true),161
}162
}163
164
pub fn shows_banner(self) -> bool {165
matches!(166
self,167
ActivityAlert::BannerAndFeed | ActivityAlert::OnlyBanner168
)169
}170
}171
172
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]173
pub enum MeetingChatNotifications {174
Mute,175
Unmute,176
#[default]177
MuteUntilJoin,178
}179
180
impl MeetingChatNotifications {181
pub const ALL: [MeetingChatNotifications; 3] = [182
MeetingChatNotifications::Mute,183
MeetingChatNotifications::Unmute,184
MeetingChatNotifications::MuteUntilJoin,185
];186
187
pub fn property_value(self) -> &'static str {188
match self {189
MeetingChatNotifications::Mute => "MeetingsManuallyUnmuted",190
MeetingChatNotifications::Unmute => "MeetingsUserIsInvitedTo",191
MeetingChatNotifications::MuteUntilJoin => "MeetingsUserParticipatesIn",192
}193
}194
195
fn from_property(value: &str) -> Option<Self> {196
MeetingChatNotifications::ALL197
.into_iter()198
.find(|choice| choice.property_value() == value)199
}200
}201
202
#[derive(Debug, Clone, Copy, PartialEq, Eq)]203
pub struct NotificationAccountSettings {204
pub preset: NotificationPreset,205
pub chat_messages: ActivityAlert,206
pub personal_mentions: ActivityAlert,207
pub everyone_mentions: ActivityAlert,208
pub likes: ActivityAlert,209
pub show_preview: bool,210
pub meeting_chats: MeetingChatNotifications,211
}212
213
impl Default for NotificationAccountSettings {214
fn default() -> Self {215
NotificationAccountSettings {216
preset: NotificationPreset::default(),217
chat_messages: ActivityAlert::OnlyBanner,218
personal_mentions: ActivityAlert::BannerAndFeed,219
everyone_mentions: ActivityAlert::BannerAndFeed,220
likes: ActivityAlert::BannerAndFeed,221
show_preview: true,222
meeting_chats: MeetingChatNotifications::default(),223
}224
}225
}226
227
#[derive(Debug, Clone, Copy, PartialEq, Eq)]228
pub struct ChatAccountSettings {229
pub read_receipts: bool,230
pub message_density: MessageDensity,231
pub enter_key: EnterKeyBehavior,232
pub up_arrow: UpArrowBehavior,233
pub notifications: NotificationAccountSettings,234
}235
236
impl Default for ChatAccountSettings {237
fn default() -> Self {238
ChatAccountSettings {239
read_receipts: true,240
message_density: MessageDensity::default(),241
enter_key: EnterKeyBehavior::default(),242
up_arrow: UpArrowBehavior::default(),243
notifications: NotificationAccountSettings::default(),244
}245
}246
}247
248
#[derive(Debug, Clone, Copy, PartialEq, Eq)]249
pub enum ChatSettingChange {250
ReadReceipts(bool),251
MessageDensity(MessageDensity),252
EnterKey(EnterKeyBehavior),253
UpArrow(UpArrowBehavior),254
Preset(NotificationPreset),255
ChatMessages(ActivityAlert),256
PersonalMentions(ActivityAlert),257
EveryoneMentions(ActivityAlert),258
Likes(ActivityAlert),259
ShowPreview(bool),260
MeetingChats(MeetingChatNotifications),261
}262
263
/// The account properties Teams keeps these settings in, as last read from `users/ME/properties`.264
#[derive(Debug, Clone, PartialEq, Default)]265
pub struct ChatSettingsDocument {266
properties: Map<String, Value>,267
}268
269
impl ChatSettingsDocument {270
pub fn from_properties(properties: &Value) -> Self {271
let properties = ACCOUNT_KEYS272
.iter()273
.filter_map(|key| Some(((*key).to_owned(), properties.get(*key)?.clone())))274
.collect();275
ChatSettingsDocument { properties }276
}277
278
pub fn from_text(text: &str) -> Self {279
serde_json::from_str::<Value>(text)280
.map(|value| ChatSettingsDocument::from_properties(&value))281
.unwrap_or_default()282
}283
284
pub fn to_text(&self) -> String {285
Value::Object(self.properties.clone()).to_string()286
}287
288
pub fn settings(&self) -> ChatAccountSettings {289
let defaults = ChatAccountSettings::default();290
let personal = self.json_property(PERSONAL_SETTINGS_KEY);291
let compose = self.json_property(COMPOSE_SETTINGS_KEY);292
ChatAccountSettings {293
read_receipts: self294
.properties295
.get(READ_RECEIPTS_KEY)296
.and_then(flag)297
.unwrap_or(defaults.read_receipts),298
message_density: self299
.properties300
.get(MESSAGE_DENSITY_KEY)301
.and_then(Value::as_str)302
.and_then(MessageDensity::from_property)303
.unwrap_or(defaults.message_density),304
enter_key: text_at(&compose, &[ENTER_KEY_FIELD])305
.and_then(EnterKeyBehavior::from_property)306
.unwrap_or(defaults.enter_key),307
up_arrow: text_at(&personal, &[MESSAGING_SETTINGS, UP_ARROW_FIELD])308
.and_then(UpArrowBehavior::from_property)309
.unwrap_or(defaults.up_arrow),310
notifications: notification_settings(&personal),311
}312
}313
314
/// Applies the change and returns the property write Teams makes for it: name and value.315
pub fn apply(&mut self, change: ChatSettingChange) -> (&'static str, Value) {316
let (name, value) = match change {317
ChatSettingChange::ReadReceipts(enabled) => {318
(READ_RECEIPTS_KEY, Value::String(enabled.to_string()))319
}320
ChatSettingChange::MessageDensity(density) => (321
MESSAGE_DENSITY_KEY,322
Value::String(density.property_value().to_owned()),323
),324
ChatSettingChange::EnterKey(behavior) => {325
let mut compose = self.json_property(COMPOSE_SETTINGS_KEY);326
compose.insert(ENTER_KEY_FIELD.to_owned(), json!(behavior.property_value()));327
(328
COMPOSE_SETTINGS_KEY,329
Value::String(Value::Object(compose).to_string()),330
)331
}332
personal_change => {333
let mut personal = self.json_property(PERSONAL_SETTINGS_KEY);334
apply_personal(&mut personal, personal_change);335
(336
PERSONAL_SETTINGS_KEY,337
Value::String(Value::Object(personal).to_string()),338
)339
}340
};341
self.properties.insert(name.to_owned(), value.clone());342
(name, value)343
}344
345
fn json_property(&self, key: &str) -> Map<String, Value> {346
match self.properties.get(key) {347
Some(Value::String(text)) => serde_json::from_str::<Value>(text)348
.ok()349
.and_then(|value| value.as_object().cloned())350
.unwrap_or_default(),351
Some(Value::Object(object)) => object.clone(),352
_ => Map::new(),353
}354
}355
}356
357
fn flag(value: &Value) -> Option<bool> {358
match value {359
Value::Bool(flag) => Some(*flag),360
Value::String(text) => Some(!text.trim().eq_ignore_ascii_case("false")),361
_ => None,362
}363
}364
365
fn value_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a Value> {366
let (first, rest) = path.split_first()?;367
rest.iter()368
.try_fold(object.get(*first)?, |value, field| value.get(*field))369
}370
371
fn text_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a str> {372
value_at(object, path)?.as_str()373
}374
375
fn flag_at(object: &Map<String, Value>, group: &str, field: &str) -> Option<bool> {376
value_at(object, &[group, field]).and_then(flag)377
}378
379
fn activity_alert(380
personal: &Map<String, Value>,381
field: &str,382
fallback: ActivityAlert,383
) -> ActivityAlert {384
let (fallback_toast, _, fallback_activity) = fallback.flags();385
let toast = flag_at(personal, TOAST_SETTINGS, field).unwrap_or(fallback_toast);386
let activity = flag_at(personal, ACTIVITY_SETTINGS, field).unwrap_or(fallback_activity);387
match (activity, toast) {388
(true, true) => ActivityAlert::BannerAndFeed,389
(true, false) => ActivityAlert::OnlyFeed,390
(false, true) => ActivityAlert::OnlyBanner,391
(false, false) => ActivityAlert::Off,392
}393
}394
395
fn chat_messages_alert(personal: &Map<String, Value>) -> ActivityAlert {396
match flag_at(personal, TOAST_SETTINGS, CHAT_MESSAGES_FIELD) {397
Some(false) => ActivityAlert::Off,398
_ => ActivityAlert::OnlyBanner,399
}400
}401
402
fn notification_settings(personal: &Map<String, Value>) -> NotificationAccountSettings {403
let defaults = NotificationAccountSettings::default();404
NotificationAccountSettings {405
preset: personal406
.get(SELECTED_PRESET_FIELD)407
.and_then(NotificationPreset::from_property)408
.unwrap_or(defaults.preset),409
chat_messages: chat_messages_alert(personal),410
personal_mentions: activity_alert(411
personal,412
PERSONAL_MENTIONS_FIELD,413
defaults.personal_mentions,414
),415
everyone_mentions: activity_alert(416
personal,417
EVERYONE_MENTIONS_FIELD,418
defaults.everyone_mentions,419
),420
likes: activity_alert(personal, LIKES_FIELD, defaults.likes),421
show_preview: text_at(personal, &[TOAST_SETTINGS, SHOW_PREVIEW_FIELD])422
.map_or(defaults.show_preview, |value| value != "Off"),423
meeting_chats: text_at(personal, &[CHAT_SETTINGS, MEETING_CHAT_FIELD])424
.and_then(MeetingChatNotifications::from_property)425
.unwrap_or(defaults.meeting_chats),426
}427
}428
429
fn group_mut<'a>(personal: &'a mut Map<String, Value>, group: &str) -> &'a mut Map<String, Value> {430
let entry = personal431
.entry(group.to_owned())432
.or_insert_with(|| Value::Object(Map::new()));433
if !entry.is_object() {434
*entry = Value::Object(Map::new());435
}436
entry.as_object_mut().expect("group is an object")437
}438
439
fn set_field(personal: &mut Map<String, Value>, group: &str, field: &str, value: Value) {440
group_mut(personal, group).insert(field.to_owned(), value);441
}442
443
fn set_alert(personal: &mut Map<String, Value>, field: &str, alert: ActivityAlert) {444
let (toast, email, activity) = alert.flags();445
set_field(personal, TOAST_SETTINGS, field, Value::Bool(toast));446
set_field(personal, EMAIL_SETTINGS, field, Value::Bool(email));447
set_field(personal, ACTIVITY_SETTINGS, field, Value::Bool(activity));448
}449
450
fn apply_personal(personal: &mut Map<String, Value>, change: ChatSettingChange) {451
match change {452
ChatSettingChange::UpArrow(behavior) => set_field(453
personal,454
MESSAGING_SETTINGS,455
UP_ARROW_FIELD,456
json!(behavior.property_value()),457
),458
ChatSettingChange::Preset(preset) => {459
personal.insert(460
SELECTED_PRESET_FIELD.to_owned(),461
json!(preset.property_value()),462
);463
}464
ChatSettingChange::ChatMessages(alert) => set_alert(personal, CHAT_MESSAGES_FIELD, alert),465
ChatSettingChange::PersonalMentions(alert) => {466
set_alert(personal, PERSONAL_MENTIONS_FIELD, alert)467
}468
ChatSettingChange::EveryoneMentions(alert) => {469
set_alert(personal, EVERYONE_MENTIONS_FIELD, alert)470
}471
ChatSettingChange::Likes(alert) => set_alert(personal, LIKES_FIELD, alert),472
ChatSettingChange::ShowPreview(shown) => set_field(473
personal,474
TOAST_SETTINGS,475
SHOW_PREVIEW_FIELD,476
json!(if shown { "On" } else { "Off" }),477
),478
ChatSettingChange::MeetingChats(choice) => set_field(479
personal,480
CHAT_SETTINGS,481
MEETING_CHAT_FIELD,482
json!(choice.property_value()),483
),484
ChatSettingChange::ReadReceipts(_)485
| ChatSettingChange::MessageDensity(_)486
| ChatSettingChange::EnterKey(_) => {}487
}488
}489
490
pub struct ChatSettingsClient<T: MessageTransport = SessionMessageTransport> {491
settings: UserSettings<T>,492
}493
494
impl ChatSettingsClient<SessionMessageTransport> {495
pub fn new(session: &Session) -> Self {496
ChatSettingsClient::with_settings(UserSettings::new(session))497
}498
}499
500
impl<T: MessageTransport> ChatSettingsClient<T> {501
pub fn with_settings(settings: UserSettings<T>) -> Self {502
ChatSettingsClient { settings }503
}504
505
pub async fn read(&self) -> Result<ChatSettingsDocument> {506
Ok(ChatSettingsDocument::from_properties(507
&self.settings.properties().await?,508
))509
}510
511
/// Reads the current properties first so fields this client does not know survive the write.512
pub async fn write(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {513
let mut document = self.read().await?;514
let (name, value) = document.apply(change);515
self.settings.set_property(name, value).await?;516
Ok(document)517
}518
}519
520
#[cfg(test)]521
mod tests {522
use std::collections::VecDeque;523
use std::sync::Mutex;524
525
use session::{ApiResponse, Method, Request};526
527
use super::*;528
529
struct Canned {530
answers: Mutex<VecDeque<(u16, Value)>>,531
requests: Mutex<Vec<Request>>,532
}533
534
impl MessageTransport for &Canned {535
async fn send(&self, request: Request) -> Result<ApiResponse> {536
self.requests.lock().unwrap().push(request);537
let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted");538
Ok(ApiResponse {539
status,540
body,541
retry_after: None,542
})543
}544
}545
546
fn parsed(text: &str) -> Value {547
serde_json::from_str(text).unwrap()548
}549
550
#[test]551
fn missing_properties_give_the_teams_defaults() {552
let settings = ChatSettingsDocument::from_properties(&json!({})).settings();553
assert_eq!(settings, ChatAccountSettings::default());554
assert!(settings.read_receipts);555
assert_eq!(settings.message_density, MessageDensity::Comfy);556
assert_eq!(settings.enter_key, EnterKeyBehavior::Send);557
assert_eq!(settings.up_arrow, UpArrowBehavior::EditLastMessage);558
assert_eq!(559
settings.notifications.preset,560
NotificationPreset::Customised561
);562
assert_eq!(563
settings.notifications.meeting_chats,564
MeetingChatNotifications::MuteUntilJoin565
);566
}567
568
#[test]569
fn reads_every_setting_from_the_teams_properties() {570
let personal = json!({571
"messagingSettings": {"upArrowKeyBehavior": "STAY_IN_COMPOSE"},572
"selectedPreset": 2,573
"toastSettings": {"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true, "ShowPreviewInToasts": "Off"},574
"activityGenerationSettings": {"MentionInChat_Person_v2": true, "LikeInChat_v2": false, "MentionInChat_Everyone": false},575
"chatSettings": {"meetingChatNotification": "MeetingsUserIsInvitedTo"},576
});577
let document = ChatSettingsDocument::from_properties(&json!({578
"readReceiptsEnabled": "false",579
"messageDensity": "COMPACT",580
"composeUserSettings": "{\"enterKeyBehavior\":\"CreateNewLine\"}",581
"userPersonalSettings": personal.to_string(),582
"unrelated": "dropped",583
}));584
let settings = document.settings();585
assert!(!settings.read_receipts);586
assert_eq!(settings.message_density, MessageDensity::Compact);587
assert_eq!(settings.enter_key, EnterKeyBehavior::NewLine);588
assert_eq!(settings.up_arrow, UpArrowBehavior::StayInCompose);589
let notifications = settings.notifications;590
assert_eq!(notifications.preset, NotificationPreset::MentionsAndReplies);591
assert_eq!(notifications.chat_messages, ActivityAlert::Off);592
assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed);593
assert_eq!(notifications.likes, ActivityAlert::OnlyBanner);594
assert_eq!(notifications.everyone_mentions, ActivityAlert::OnlyBanner);595
assert!(!notifications.show_preview);596
assert_eq!(597
notifications.meeting_chats,598
MeetingChatNotifications::Unmute599
);600
assert!(!document.to_text().contains("unrelated"));601
}602
603
#[test]604
fn read_receipts_follow_teams_parsing() {605
let read = |value: Value| {606
ChatSettingsDocument::from_properties(&json!({"readReceiptsEnabled": value}))607
.settings()608
.read_receipts609
};610
assert!(read(json!("true")));611
assert!(!read(json!(" False ")));612
assert!(!read(json!(false)));613
assert!(read(json!("anything")));614
}615
616
#[test]617
fn plain_properties_are_written_as_teams_strings() {618
let mut document = ChatSettingsDocument::default();619
assert_eq!(620
document.apply(ChatSettingChange::ReadReceipts(false)),621
("readReceiptsEnabled", json!("false"))622
);623
assert_eq!(624
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact)),625
("messageDensity", json!("COMPACT"))626
);627
let settings = document.settings();628
assert!(!settings.read_receipts);629
assert_eq!(settings.message_density, MessageDensity::Compact);630
}631
632
#[test]633
fn enter_key_keeps_other_compose_fields() {634
let mut document = ChatSettingsDocument::from_properties(&json!({635
"composeUserSettings": "{\"enterKeyBehavior\":\"Default\",\"future\":1}"636
}));637
let (name, value) = document.apply(ChatSettingChange::EnterKey(EnterKeyBehavior::NewLine));638
assert_eq!(name, "composeUserSettings");639
assert_eq!(640
parsed(value.as_str().unwrap()),641
json!({"enterKeyBehavior": "CreateNewLine", "future": 1})642
);643
}644
645
#[test]646
fn personal_settings_changes_keep_unknown_fields() {647
let mut document = ChatSettingsDocument::from_properties(&json!({648
"userPersonalSettings": "{\"soundsSettings\":{\"alertSound\":\"All\"},\"messagingSettings\":{\"shouldShowDiscoverApp\":true}}"649
}));650
document.apply(ChatSettingChange::UpArrow(651
UpArrowBehavior::NavigateToMessages,652
));653
let (name, value) =654
document.apply(ChatSettingChange::Preset(NotificationPreset::AllActivity));655
assert_eq!(name, "userPersonalSettings");656
assert_eq!(657
parsed(value.as_str().unwrap()),658
json!({659
"soundsSettings": {"alertSound": "All"},660
"messagingSettings": {"shouldShowDiscoverApp": true, "upArrowKeyBehavior": "NAVIGATE_TO_MESSAGES"},661
"selectedPreset": 1,662
})663
);664
}665
666
#[test]667
fn alerts_write_toast_email_and_activity_like_teams() {668
let mut document = ChatSettingsDocument::default();669
document.apply(ChatSettingChange::ChatMessages(ActivityAlert::Off));670
document.apply(ChatSettingChange::PersonalMentions(ActivityAlert::OnlyFeed));671
let (_, value) = document.apply(ChatSettingChange::Likes(ActivityAlert::BannerAndFeed));672
let personal = parsed(value.as_str().unwrap());673
assert_eq!(674
personal["toastSettings"],675
json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true})676
);677
assert_eq!(678
personal["emailSettings"],679
json!({"Chat": false, "MentionInChat_Person_v2": false, "LikeInChat_v2": true})680
);681
assert_eq!(682
personal["activityGenerationSettings"],683
json!({"Chat": false, "MentionInChat_Person_v2": true, "LikeInChat_v2": true})684
);685
let notifications = document.settings().notifications;686
assert_eq!(notifications.chat_messages, ActivityAlert::Off);687
assert_eq!(notifications.personal_mentions, ActivityAlert::OnlyFeed);688
assert_eq!(notifications.likes, ActivityAlert::BannerAndFeed);689
}690
691
#[test]692
fn preview_and_meeting_chats_round_trip() {693
let mut document = ChatSettingsDocument::default();694
document.apply(ChatSettingChange::ShowPreview(false));695
document.apply(ChatSettingChange::MeetingChats(696
MeetingChatNotifications::Mute,697
));698
let restored = ChatSettingsDocument::from_text(&document.to_text());699
let notifications = restored.settings().notifications;700
assert!(!notifications.show_preview);701
assert_eq!(notifications.meeting_chats, MeetingChatNotifications::Mute);702
assert_eq!(restored, document);703
}704
705
#[tokio::test]706
async fn write_reads_then_puts_the_named_property() {707
let transport = Canned {708
answers: Mutex::new(709
vec![710
(200, json!({"messageDensity": "COMFY", "other": 1})),711
(200, Value::Null),712
]713
.into(),714
),715
requests: Mutex::new(Vec::new()),716
};717
let client =718
ChatSettingsClient::with_settings(UserSettings::with_transport(&transport, "emea"));719
let document = client720
.write(ChatSettingChange::MessageDensity(MessageDensity::Compact))721
.await722
.unwrap();723
assert_eq!(document.settings().message_density, MessageDensity::Compact);724
let requests = transport.requests.lock().unwrap();725
assert_eq!(requests[0].method, Method::Get);726
assert_eq!(requests[1].method, Method::Put);727
assert_eq!(728
requests[1].url,729
"https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=messageDensity"730
);731
assert_eq!(requests[1].body, Some(json!({"messageDensity": "COMPACT"})));732
}733
}@@ -2,6 +2,9 @@ use serde_json::{Value, json};
2
2
use session::{Method, Request, Session};
3
3
4
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
5
use crate::chat_notifications::{
6
self, ChatNotificationMode, ChatNotificationWrite, DesktopNotifications,
7
};
5
8
use crate::error::{Error, Result};
6
9
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7
10
use crate::pins::DEFAULT_REGION;
@@ -12,13 +15,20 @@ const MAX_PAGES: usize = 100;
12
15
const ALERTS_OFF: &str = "false";
13
16
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
14
17
15
#[derive(Debug, Clone, PartialEq, Eq)]
18
#[derive(Debug, Clone, PartialEq, Eq, Default)]
16
19
pub struct ConversationState {
17
20
pub id: String,
18
21
pub muted: bool,
19
22
pub hidden: Option<bool>,
20
23
pub read: ReadHorizon,
21
24
pub history_cleared_ms: Option<i64>,
25
pub notification_settings: Option<String>,
26
}
27
28
impl ConversationState {
29
pub fn desktop_notifications(&self) -> DesktopNotifications {
30
chat_notifications::parse_desktop(self.notification_settings.as_deref())
31
}
22
32
}
23
33
24
34
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -86,6 +96,31 @@ impl<T: MessageTransport> Conversations<T> {
86
96
ensure_success(&answer)
87
97
}
88
98
99
/// Teams writes the merged notification settings first, then `alerts`.
100
pub async fn set_chat_notifications(
101
&self,
102
conversation_id: &str,
103
current_settings: Option<&str>,
104
mode: ChatNotificationMode,
105
desktop: DesktopNotifications,
106
) -> Result<ChatNotificationWrite> {
107
let write = chat_notifications::chat_notification_write(current_settings, mode, desktop);
108
let url = format!(
109
"{}/{}/properties?name={}",
110
self.base_url,
111
encode(conversation_id),
112
chat_notifications::PROPERTY_NAME
113
);
114
let body = json!({ chat_notifications::PROPERTY_NAME: write.settings });
115
let answer = self
116
.transport
117
.send(Request::with_body(Method::Put, url, body))
118
.await?;
119
ensure_success(&answer)?;
120
self.set_alerts(conversation_id, write.alerts).await?;
121
Ok(write)
122
}
123
89
124
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.
90
125
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
91
126
let answer = self
@@ -205,6 +240,10 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
205
240
muted,
206
241
hidden: hidden_flag(conversation),
207
242
read: ReadHorizon::from_conversation(conversation),
243
notification_settings: conversation["properties"]
244
[chat_notifications::PROPERTY_NAME]
245
.as_str()
246
.map(str::to_owned),
208
247
history_cleared_ms: history_cleared_ms(conversation),
209
248
})
210
249
})
@@ -248,9 +287,7 @@ mod tests {
248
287
ConversationState {
249
288
id: id.to_owned(),
250
289
muted,
251
hidden: None,
252
read: ReadHorizon::default(),
253
history_cleared_ms: None,
290
..Default::default()
254
291
}
255
292
}
256
293
@@ -487,4 +524,49 @@ mod tests {
487
524
Some(json!({"consumptionhorizon": "9;10;0"}))
488
525
);
489
526
}
527
528
#[tokio::test]
529
async fn chat_notifications_put_the_settings_then_alerts() {
530
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);
531
let write = Conversations::with_transport(&transport, "emea")
532
.set_chat_notifications(
533
"19:a@thread.v2",
534
Some(r#"{"everyone":"On"}"#),
535
ChatNotificationMode::Mute,
536
DesktopNotifications::MatchAllChats,
537
)
538
.await
539
.unwrap();
540
assert!(!write.alerts);
541
let requests = transport.requests.lock().unwrap();
542
assert_eq!(
543
requests[0].url,
544
format!("{BASE}/19%3Aa%40thread.v2/properties?name=conversationNotificationSettings")
545
);
546
let sent = requests[0].body.as_ref().unwrap()["conversationNotificationSettings"]
547
.as_str()
548
.unwrap();
549
assert_eq!(
550
serde_json::from_str::<Value>(sent).unwrap(),
551
json!({"everyone": "Off", "dskNotif": null, "allNewPosts": "Off"})
552
);
553
assert_eq!(
554
requests[1].url,
555
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")
556
);
557
assert_eq!(requests[1].body, Some(json!({"alerts": "false"})));
558
}
559
560
#[tokio::test]
561
async fn states_carry_the_chat_notification_settings() {
562
let transport = canned(vec![(
563
200,
564
json!({"conversations": [{"id": "19:a", "properties": {"conversationNotificationSettings": "{\"dskNotif\":\"Off\"}"}}]}),
565
)]);
566
let states = Conversations::with_transport(&transport, "emea")
567
.conversation_states()
568
.await
569
.unwrap();
570
assert_eq!(states[0].desktop_notifications(), DesktopNotifications::Off);
571
}
490
572
}
@@ -2,6 +2,9 @@ use serde_json::{Value, json};2
use session::{Method, Request, Session};2
use session::{Method, Request, Session};3
3
4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};4
use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};5
use crate::chat_notifications::{6
self, ChatNotificationMode, ChatNotificationWrite, DesktopNotifications,7
};5
use crate::error::{Error, Result};8
use crate::error::{Error, Result};6
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};9
use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};7
use crate::pins::DEFAULT_REGION;10
use crate::pins::DEFAULT_REGION;@@ -12,13 +15,20 @@ const MAX_PAGES: usize = 100;12
const ALERTS_OFF: &str = "false";15
const ALERTS_OFF: &str = "false";13
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";16
const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";14
17
15
#[derive(Debug, Clone, PartialEq, Eq)]18
#[derive(Debug, Clone, PartialEq, Eq, Default)]16
pub struct ConversationState {19
pub struct ConversationState {17
pub id: String,20
pub id: String,18
pub muted: bool,21
pub muted: bool,19
pub hidden: Option<bool>,22
pub hidden: Option<bool>,20
pub read: ReadHorizon,23
pub read: ReadHorizon,21
pub history_cleared_ms: Option<i64>,24
pub history_cleared_ms: Option<i64>,25
pub notification_settings: Option<String>,26
}27
28
impl ConversationState {29
pub fn desktop_notifications(&self) -> DesktopNotifications {30
chat_notifications::parse_desktop(self.notification_settings.as_deref())31
}22
}32
}23
33
24
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {34
pub struct Conversations<T: MessageTransport = SessionMessageTransport> {@@ -86,6 +96,31 @@ impl<T: MessageTransport> Conversations<T> {86
ensure_success(&answer)96
ensure_success(&answer)87
}97
}88
98
99
/// Teams writes the merged notification settings first, then `alerts`.100
pub async fn set_chat_notifications(101
&self,102
conversation_id: &str,103
current_settings: Option<&str>,104
mode: ChatNotificationMode,105
desktop: DesktopNotifications,106
) -> Result<ChatNotificationWrite> {107
let write = chat_notifications::chat_notification_write(current_settings, mode, desktop);108
let url = format!(109
"{}/{}/properties?name={}",110
self.base_url,111
encode(conversation_id),112
chat_notifications::PROPERTY_NAME113
);114
let body = json!({ chat_notifications::PROPERTY_NAME: write.settings });115
let answer = self116
.transport117
.send(Request::with_body(Method::Put, url, body))118
.await?;119
ensure_success(&answer)?;120
self.set_alerts(conversation_id, write.alerts).await?;121
Ok(write)122
}123
89
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.124
/// Teams' "Remove chat history": everything up to this time disappears for the current user only.90
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {125
pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {91
let answer = self126
let answer = self@@ -205,6 +240,10 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {205
muted,240
muted,206
hidden: hidden_flag(conversation),241
hidden: hidden_flag(conversation),207
read: ReadHorizon::from_conversation(conversation),242
read: ReadHorizon::from_conversation(conversation),243
notification_settings: conversation["properties"]244
[chat_notifications::PROPERTY_NAME]245
.as_str()246
.map(str::to_owned),208
history_cleared_ms: history_cleared_ms(conversation),247
history_cleared_ms: history_cleared_ms(conversation),209
})248
})210
})249
})@@ -248,9 +287,7 @@ mod tests {248
ConversationState {287
ConversationState {249
id: id.to_owned(),288
id: id.to_owned(),250
muted,289
muted,251
hidden: None,290
..Default::default()252
read: ReadHorizon::default(),253
history_cleared_ms: None,254
}291
}255
}292
}256
293
@@ -487,4 +524,49 @@ mod tests {487
Some(json!({"consumptionhorizon": "9;10;0"}))524
Some(json!({"consumptionhorizon": "9;10;0"}))488
);525
);489
}526
}527
528
#[tokio::test]529
async fn chat_notifications_put_the_settings_then_alerts() {530
let transport = canned(vec![(200, Value::Null), (200, Value::Null)]);531
let write = Conversations::with_transport(&transport, "emea")532
.set_chat_notifications(533
"19:a@thread.v2",534
Some(r#"{"everyone":"On"}"#),535
ChatNotificationMode::Mute,536
DesktopNotifications::MatchAllChats,537
)538
.await539
.unwrap();540
assert!(!write.alerts);541
let requests = transport.requests.lock().unwrap();542
assert_eq!(543
requests[0].url,544
format!("{BASE}/19%3Aa%40thread.v2/properties?name=conversationNotificationSettings")545
);546
let sent = requests[0].body.as_ref().unwrap()["conversationNotificationSettings"]547
.as_str()548
.unwrap();549
assert_eq!(550
serde_json::from_str::<Value>(sent).unwrap(),551
json!({"everyone": "Off", "dskNotif": null, "allNewPosts": "Off"})552
);553
assert_eq!(554
requests[1].url,555
format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts")556
);557
assert_eq!(requests[1].body, Some(json!({"alerts": "false"})));558
}559
560
#[tokio::test]561
async fn states_carry_the_chat_notification_settings() {562
let transport = canned(vec![(563
200,564
json!({"conversations": [{"id": "19:a", "properties": {"conversationNotificationSettings": "{\"dskNotif\":\"Off\"}"}}]}),565
)]);566
let states = Conversations::with_transport(&transport, "emea")567
.conversation_states()568
.await569
.unwrap();570
assert_eq!(states[0].desktop_notifications(), DesktopNotifications::Off);571
}490
}572
}@@ -3,6 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};
3
3
4
4
use crate::error::{Error, Result};
5
5
use crate::messages::ensure_success;
6
use crate::messaging_policy::{messaging_policy_body, parse_allow_priority_messages};
6
7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
7
8
use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};
8
9
use crate::translate::language_code;
@@ -204,6 +205,20 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {
204
205
Ok(parse_recording_policy(&answer.body))
205
206
}
206
207
208
pub async fn read_allow_priority_messages(&self) -> Result<bool> {
209
let url = format!("{}/useraggregatesettings", self.base_url);
210
let answer = self
211
.transport
212
.send(with_headers(Request::with_body(
213
Method::Post,
214
url,
215
messaging_policy_body(),
216
)))
217
.await?;
218
ensure_success(&answer)?;
219
Ok(parse_allow_priority_messages(&answer.body))
220
}
221
207
222
pub async fn patch(&self, patch: Value) -> Result<()> {
208
223
let url = format!("{}/languageAccountSettings", self.base_url);
209
224
let answer = self
@@ -415,6 +430,26 @@ mod tests {
415
430
);
416
431
}
417
432
433
#[tokio::test]
434
async fn the_messaging_policy_is_read_from_the_same_route() {
435
let answer = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
436
let transport = Canned {
437
answers: Mutex::new(vec![(200, answer)].into()),
438
requests: Mutex::new(Vec::new()),
439
};
440
let allowed = LanguageSettingsClient::with_transport(&transport, "emea")
441
.read_allow_priority_messages()
442
.await
443
.unwrap();
444
assert!(!allowed);
445
let requests = transport.requests.lock().unwrap();
446
assert_eq!(
447
requests[0].url,
448
"https://teams.cloud.microsoft/api/mt/emea/beta/users/useraggregatesettings"
449
);
450
assert_eq!(requests[0].body, Some(json!({"messagingPolicy": true})));
451
}
452
418
453
#[tokio::test]
419
454
async fn an_empty_answer_is_not_settings() {
420
455
let transport = Canned {
@@ -3,6 +3,7 @@ use session::{Method, Request, SPACES, Scope, Session};3
3
4
use crate::error::{Error, Result};4
use crate::error::{Error, Result};5
use crate::messages::ensure_success;5
use crate::messages::ensure_success;6
use crate::messaging_policy::{messaging_policy_body, parse_allow_priority_messages};6
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};7
use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};8
use crate::recording_policy::{RecordingPolicy, parse_recording_policy, recording_policy_body};8
use crate::translate::language_code;9
use crate::translate::language_code;@@ -204,6 +205,20 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {204
Ok(parse_recording_policy(&answer.body))205
Ok(parse_recording_policy(&answer.body))205
}206
}206
207
208
pub async fn read_allow_priority_messages(&self) -> Result<bool> {209
let url = format!("{}/useraggregatesettings", self.base_url);210
let answer = self211
.transport212
.send(with_headers(Request::with_body(213
Method::Post,214
url,215
messaging_policy_body(),216
)))217
.await?;218
ensure_success(&answer)?;219
Ok(parse_allow_priority_messages(&answer.body))220
}221
207
pub async fn patch(&self, patch: Value) -> Result<()> {222
pub async fn patch(&self, patch: Value) -> Result<()> {208
let url = format!("{}/languageAccountSettings", self.base_url);223
let url = format!("{}/languageAccountSettings", self.base_url);209
let answer = self224
let answer = self@@ -415,6 +430,26 @@ mod tests {415
);430
);416
}431
}417
432
433
#[tokio::test]434
async fn the_messaging_policy_is_read_from_the_same_route() {435
let answer = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});436
let transport = Canned {437
answers: Mutex::new(vec![(200, answer)].into()),438
requests: Mutex::new(Vec::new()),439
};440
let allowed = LanguageSettingsClient::with_transport(&transport, "emea")441
.read_allow_priority_messages()442
.await443
.unwrap();444
assert!(!allowed);445
let requests = transport.requests.lock().unwrap();446
assert_eq!(447
requests[0].url,448
"https://teams.cloud.microsoft/api/mt/emea/beta/users/useraggregatesettings"449
);450
assert_eq!(requests[0].body, Some(json!({"messagingPolicy": true})));451
}452
418
#[tokio::test]453
#[tokio::test]419
async fn an_empty_answer_is_not_settings() {454
async fn an_empty_answer_is_not_settings() {420
let transport = Canned {455
let transport = Canned {@@ -4,6 +4,8 @@ pub mod calendar;
4
4
pub mod calllog;
5
5
pub mod cards;
6
6
pub mod channel_notifications;
7
pub mod chat_notifications;
8
pub mod chat_settings;
7
9
pub mod channel_visibility;
8
10
pub mod conversations;
9
11
pub mod drafts;
@@ -24,6 +26,7 @@ pub mod read_horizon;
24
26
pub mod realtime;
25
27
pub mod recap;
26
28
pub mod receipts;
29
pub mod messaging_policy;
27
30
pub mod recording_policy;
28
31
pub mod saved;
29
32
pub mod settings;
@@ -46,6 +49,12 @@ pub use cards::{
46
49
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
47
50
};
48
51
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
52
pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
53
pub use chat_settings::{
54
ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
55
ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
56
NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
57
};
49
58
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
50
59
pub use conversations::{ConversationState, Conversations};
51
60
pub use drafts::{ScheduledDraft, ScheduledDrafts};
@@ -4,6 +4,8 @@ pub mod calendar;4
pub mod calllog;4
pub mod calllog;5
pub mod cards;5
pub mod cards;6
pub mod channel_notifications;6
pub mod channel_notifications;7
pub mod chat_notifications;8
pub mod chat_settings;7
pub mod channel_visibility;9
pub mod channel_visibility;8
pub mod conversations;10
pub mod conversations;9
pub mod drafts;11
pub mod drafts;@@ -24,6 +26,7 @@ pub mod read_horizon;24
pub mod realtime;26
pub mod realtime;25
pub mod recap;27
pub mod recap;26
pub mod receipts;28
pub mod receipts;29
pub mod messaging_policy;27
pub mod recording_policy;30
pub mod recording_policy;28
pub mod saved;31
pub mod saved;29
pub mod settings;32
pub mod settings;@@ -46,6 +49,12 @@ pub use cards::{46
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,49
CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,47
};50
};48
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};51
pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};52
pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};53
pub use chat_settings::{54
ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,55
ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,56
NotificationAccountSettings, NotificationPreset, UpArrowBehavior,57
};49
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};58
pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};50
pub use conversations::{ConversationState, Conversations};59
pub use conversations::{ConversationState, Conversations};51
pub use drafts::{ScheduledDraft, ScheduledDrafts};60
pub use drafts::{ScheduledDraft, ScheduledDrafts};@@ -0,0 +1,31 @@
1
use serde_json::{Value, json};
2
3
pub fn messaging_policy_body() -> Value {
4
json!({"messagingPolicy": true})
5
}
6
7
/// Teams reads `messagingPolicy.allowPriorityMessages` and allows urgent messages unless it is `false`.
8
pub fn parse_allow_priority_messages(body: &Value) -> bool {
9
body.pointer("/messagingPolicy/value/allowPriorityMessages")
10
.and_then(Value::as_bool)
11
.unwrap_or(true)
12
}
13
14
#[cfg(test)]
15
mod tests {
16
use super::*;
17
18
#[test]
19
fn the_body_asks_for_the_messaging_policy() {
20
assert_eq!(messaging_policy_body(), json!({"messagingPolicy": true}));
21
}
22
23
#[test]
24
fn priority_messages_follow_the_policy_and_default_to_allowed() {
25
let denied = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});
26
let allowed = json!({"messagingPolicy": {"value": {"allowPriorityMessages": true}}});
27
assert!(!parse_allow_priority_messages(&denied));
28
assert!(parse_allow_priority_messages(&allowed));
29
assert!(parse_allow_priority_messages(&json!({})));
30
}
31
}
@@ -0,0 +1,31 @@1
use serde_json::{Value, json};2
3
pub fn messaging_policy_body() -> Value {4
json!({"messagingPolicy": true})5
}6
7
/// Teams reads `messagingPolicy.allowPriorityMessages` and allows urgent messages unless it is `false`.8
pub fn parse_allow_priority_messages(body: &Value) -> bool {9
body.pointer("/messagingPolicy/value/allowPriorityMessages")10
.and_then(Value::as_bool)11
.unwrap_or(true)12
}13
14
#[cfg(test)]15
mod tests {16
use super::*;17
18
#[test]19
fn the_body_asks_for_the_messaging_policy() {20
assert_eq!(messaging_policy_body(), json!({"messagingPolicy": true}));21
}22
23
#[test]24
fn priority_messages_follow_the_policy_and_default_to_allowed() {25
let denied = json!({"messagingPolicy": {"value": {"allowPriorityMessages": false}}});26
let allowed = json!({"messagingPolicy": {"value": {"allowPriorityMessages": true}}});27
assert!(!parse_allow_priority_messages(&denied));28
assert!(parse_allow_priority_messages(&allowed));29
assert!(parse_allow_priority_messages(&json!({})));30
}31
}@@ -580,6 +580,10 @@ impl<R: Remote> SyncEngine<R> {
580
580
self.remote.send_typing(&conversation, active).await
581
581
}
582
582
583
pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
584
self.remote.ack_urgent_message(chat_id, message_id).await
585
}
586
583
587
pub async fn set_reaction(
584
588
&self,
585
589
conversation_id: &str,
@@ -580,6 +580,10 @@ impl<R: Remote> SyncEngine<R> {580
self.remote.send_typing(&conversation, active).await580
self.remote.send_typing(&conversation, active).await581
}581
}582
582
583
pub async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {584
self.remote.ack_urgent_message(chat_id, message_id).await585
}586
583
pub async fn set_reaction(587
pub async fn set_reaction(584
&self,588
&self,585
conversation_id: &str,589
conversation_id: &str,@@ -62,6 +62,8 @@ mod tests {
62
62
last_message_from: Some("8:orgid:someone".to_owned()),
63
63
..ReadHorizon::default()
64
64
},
65
notification_settings: None,
66
history_cleared_ms: None,
65
67
}
66
68
}
67
69
@@ -62,6 +62,8 @@ mod tests {62
last_message_from: Some("8:orgid:someone".to_owned()),62
last_message_from: Some("8:orgid:someone".to_owned()),63
..ReadHorizon::default()63
..ReadHorizon::default()64
},64
},65
notification_settings: None,66
history_cleared_ms: None,65
}67
}66
}68
}67
69
@@ -0,0 +1,92 @@
1
use chatsvc::{
2
ChatNotificationMode, ChatSettingChange, ChatSettingsDocument, DesktopNotifications,
3
};
4
use store::Store;
5
6
use crate::engine::SyncEngine;
7
use crate::error::Result;
8
use crate::events::CoreEvent;
9
use crate::remote::Remote;
10
11
const META_CHAT_SETTINGS: &str = "account.chat_settings";
12
13
pub fn stored_chat_settings(store: &Store) -> ChatSettingsDocument {
14
store
15
.meta(META_CHAT_SETTINGS)
16
.ok()
17
.flatten()
18
.map(|text| ChatSettingsDocument::from_text(&text))
19
.unwrap_or_default()
20
}
21
22
pub fn store_chat_settings(store: &Store, document: &ChatSettingsDocument) -> Result<()> {
23
Ok(store.set_meta(META_CHAT_SETTINGS, &document.to_text())?)
24
}
25
26
impl<R: Remote> SyncEngine<R> {
27
pub async fn refresh_chat_settings(&self) -> Result<ChatSettingsDocument> {
28
let document = self.remote.chat_settings().await?;
29
store_chat_settings(&self.store, &document)?;
30
Ok(document)
31
}
32
33
pub async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
34
let document = self.remote.save_chat_setting(change).await?;
35
store_chat_settings(&self.store, &document)?;
36
Ok(document)
37
}
38
39
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {
40
self.chat_states
41
.lock()
42
.unwrap()
43
.get(chat_id)
44
.map(|state| state.desktop_notifications())
45
.unwrap_or_default()
46
}
47
48
pub async fn set_chat_notifications(
49
&self,
50
chat_id: &str,
51
mode: ChatNotificationMode,
52
desktop: DesktopNotifications,
53
) -> Result<()> {
54
let current = self
55
.chat_states
56
.lock()
57
.unwrap()
58
.get(chat_id)
59
.and_then(|state| state.notification_settings.clone());
60
let write = self
61
.remote
62
.set_chat_notifications(chat_id, current.as_deref(), mode, desktop)
63
.await?;
64
{
65
let mut states = self.chat_states.lock().unwrap();
66
let state = states.entry(chat_id.to_owned()).or_default();
67
state.id = chat_id.to_owned();
68
state.muted = !write.alerts;
69
state.notification_settings = Some(write.settings);
70
}
71
self.store.set_chat_muted(chat_id, !write.alerts)?;
72
let _ = self.events.send(CoreEvent::SidebarChanged);
73
Ok(())
74
}
75
}
76
77
#[cfg(test)]
78
mod tests {
79
use chatsvc::MessageDensity;
80
81
use super::*;
82
83
#[test]
84
fn the_document_survives_a_restart_in_the_store() {
85
let store = Store::open_in_memory().unwrap();
86
assert_eq!(stored_chat_settings(&store), ChatSettingsDocument::default());
87
let mut document = ChatSettingsDocument::default();
88
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact));
89
store_chat_settings(&store, &document).unwrap();
90
assert_eq!(stored_chat_settings(&store), document);
91
}
92
}
@@ -0,0 +1,92 @@1
use chatsvc::{2
ChatNotificationMode, ChatSettingChange, ChatSettingsDocument, DesktopNotifications,3
};4
use store::Store;5
6
use crate::engine::SyncEngine;7
use crate::error::Result;8
use crate::events::CoreEvent;9
use crate::remote::Remote;10
11
const META_CHAT_SETTINGS: &str = "account.chat_settings";12
13
pub fn stored_chat_settings(store: &Store) -> ChatSettingsDocument {14
store15
.meta(META_CHAT_SETTINGS)16
.ok()17
.flatten()18
.map(|text| ChatSettingsDocument::from_text(&text))19
.unwrap_or_default()20
}21
22
pub fn store_chat_settings(store: &Store, document: &ChatSettingsDocument) -> Result<()> {23
Ok(store.set_meta(META_CHAT_SETTINGS, &document.to_text())?)24
}25
26
impl<R: Remote> SyncEngine<R> {27
pub async fn refresh_chat_settings(&self) -> Result<ChatSettingsDocument> {28
let document = self.remote.chat_settings().await?;29
store_chat_settings(&self.store, &document)?;30
Ok(document)31
}32
33
pub async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {34
let document = self.remote.save_chat_setting(change).await?;35
store_chat_settings(&self.store, &document)?;36
Ok(document)37
}38
39
pub fn chat_desktop_notifications(&self, chat_id: &str) -> DesktopNotifications {40
self.chat_states41
.lock()42
.unwrap()43
.get(chat_id)44
.map(|state| state.desktop_notifications())45
.unwrap_or_default()46
}47
48
pub async fn set_chat_notifications(49
&self,50
chat_id: &str,51
mode: ChatNotificationMode,52
desktop: DesktopNotifications,53
) -> Result<()> {54
let current = self55
.chat_states56
.lock()57
.unwrap()58
.get(chat_id)59
.and_then(|state| state.notification_settings.clone());60
let write = self61
.remote62
.set_chat_notifications(chat_id, current.as_deref(), mode, desktop)63
.await?;64
{65
let mut states = self.chat_states.lock().unwrap();66
let state = states.entry(chat_id.to_owned()).or_default();67
state.id = chat_id.to_owned();68
state.muted = !write.alerts;69
state.notification_settings = Some(write.settings);70
}71
self.store.set_chat_muted(chat_id, !write.alerts)?;72
let _ = self.events.send(CoreEvent::SidebarChanged);73
Ok(())74
}75
}76
77
#[cfg(test)]78
mod tests {79
use chatsvc::MessageDensity;80
81
use super::*;82
83
#[test]84
fn the_document_survives_a_restart_in_the_store() {85
let store = Store::open_in_memory().unwrap();86
assert_eq!(stored_chat_settings(&store), ChatSettingsDocument::default());87
let mut document = ChatSettingsDocument::default();88
document.apply(ChatSettingChange::MessageDensity(MessageDensity::Compact));89
store_chat_settings(&store, &document).unwrap();90
assert_eq!(stored_chat_settings(&store), document);91
}92
}@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
5
5
use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};
6
6
use chrono::{DateTime, Duration, Utc};
7
7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};
8
use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};
8
use store::{ImageFileCache, MessageImportance, MessageRecord, Sidebar, Store, SyncState};
9
9
use tokio::sync::{OnceCell, broadcast};
10
10
11
11
use crate::chat_paging::ChatPaging;
@@ -298,6 +298,19 @@ impl<R: Remote> SyncEngine<R> {
298
298
unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))
299
299
}
300
300
301
pub fn unread_importance(&self, conversation_id: &str) -> MessageImportance {
302
let importance = || -> Result<MessageImportance> {
303
let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else {
304
return Ok(MessageImportance::Normal);
305
};
306
let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();
307
self.store
308
.unread_last_message_importance(conversation_id, chat.last_read_at, &my_user_id)
309
.map_err(Into::into)
310
};
311
importance().unwrap_or_default()
312
}
313
301
314
pub(crate) async fn my_user_id(&self) -> Result<String> {
302
315
let id = self
303
316
.my_user_id
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};5
use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};5
use chatsvc::{ChatApp, ConversationState, TrouterEndpoint};6
use chrono::{DateTime, Duration, Utc};6
use chrono::{DateTime, Duration, Utc};7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};7
use graph::{DriveFolder, Graph, MESSAGE_PAGE_SIZE, Message};8
use store::{ImageFileCache, MessageRecord, Sidebar, Store, SyncState};8
use store::{ImageFileCache, MessageImportance, MessageRecord, Sidebar, Store, SyncState};9
use tokio::sync::{OnceCell, broadcast};9
use tokio::sync::{OnceCell, broadcast};10
10
11
use crate::chat_paging::ChatPaging;11
use crate::chat_paging::ChatPaging;@@ -298,6 +298,19 @@ impl<R: Remote> SyncEngine<R> {298
unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))298
unread_count().map_or(0, |count| u32::try_from(count).unwrap_or(u32::MAX))299
}299
}300
300
301
pub fn unread_importance(&self, conversation_id: &str) -> MessageImportance {302
let importance = || -> Result<MessageImportance> {303
let Some(chat) = self.store.chat(conversation_id)?.filter(|chat| chat.unread) else {304
return Ok(MessageImportance::Normal);305
};306
let my_user_id = self.store.meta(META_USER_ID)?.unwrap_or_default();307
self.store308
.unread_last_message_importance(conversation_id, chat.last_read_at, &my_user_id)309
.map_err(Into::into)310
};311
importance().unwrap_or_default()312
}313
301
pub(crate) async fn my_user_id(&self) -> Result<String> {314
pub(crate) async fn my_user_id(&self) -> Result<String> {302
let id = self315
let id = self303
.my_user_id316
.my_user_id@@ -13,6 +13,7 @@ mod card_widgets;
13
13
mod card_width;
14
14
mod channel_mentions;
15
15
mod channel_sync;
16
mod chat_settings_sync;
16
17
mod channel_visibility;
17
18
mod chat_paging;
18
19
mod default_reactions;
@@ -103,6 +104,12 @@ pub use chatsvc::{
103
104
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
104
105
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
105
106
};
107
pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
108
pub use chatsvc::{
109
ActivityAlert, ChatAccountSettings, ChatNotificationMode, ChatSettingChange,
110
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,
111
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
112
};
106
113
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
107
114
pub use chatsvc::{
108
115
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
@@ -13,6 +13,7 @@ mod card_widgets;13
mod card_width;13
mod card_width;14
mod channel_mentions;14
mod channel_mentions;15
mod channel_sync;15
mod channel_sync;16
mod chat_settings_sync;16
mod channel_visibility;17
mod channel_visibility;17
mod chat_paging;18
mod chat_paging;18
mod default_reactions;19
mod default_reactions;@@ -103,6 +104,12 @@ pub use chatsvc::{103
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,104
ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,104
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,105
WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,105
};106
};107
pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};108
pub use chatsvc::{109
ActivityAlert, ChatAccountSettings, ChatNotificationMode, ChatSettingChange,110
ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,111
MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,112
};106
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};113
pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};107
pub use chatsvc::{114
pub use chatsvc::{108
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,115
Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,@@ -264,6 +264,7 @@ mod tests {
264
264
links_json: "[]".to_owned(),
265
265
subject: None,
266
266
call_event_json: None,
267
importance: Default::default(),
267
268
}
268
269
}
269
270
@@ -264,6 +264,7 @@ mod tests {264
links_json: "[]".to_owned(),264
links_json: "[]".to_owned(),265
subject: None,265
subject: None,266
call_event_json: None,266
call_event_json: None,267
importance: Default::default(),267
}268
}268
}269
}269
270
@@ -1,6 +1,8 @@
1
1
use chrono::{DateTime, Utc};
2
2
use graph::{Attachment, Chat, Mention, Message, Reaction};
3
use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
3
use store::{
4
ChannelRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord, TeamRecord,
5
};
4
6
5
7
use crate::adaptive_card::card_content_text;
6
8
use crate::call_event::CallEvent;
@@ -182,6 +184,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
182
184
.as_ref()
183
185
.map(CallEvent::to_json)
184
186
.or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),
187
importance: message
188
.importance
189
.as_deref()
190
.map_or(MessageImportance::Normal, MessageImportance::from_graph),
185
191
})
186
192
}
187
193
@@ -382,6 +388,25 @@ mod tests {
382
388
message_record("c", &message).unwrap().subject
383
389
}
384
390
391
#[test]
392
fn importance_is_read_from_graph() {
393
let importance = |value: serde_json::Value| {
394
let message: Message = serde_json::from_value(json!({
395
"id": "m1",
396
"messageType": "message",
397
"createdDateTime": "2026-10-17T10:00:00Z",
398
"importance": value,
399
"body": {"contentType": "html", "content": "<p>hi</p>"},
400
}))
401
.unwrap();
402
message_record("c", &message).unwrap().importance
403
};
404
assert_eq!(importance(json!("high")), MessageImportance::High);
405
assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);
406
assert_eq!(importance(json!("normal")), MessageImportance::Normal);
407
assert_eq!(importance(json!(null)), MessageImportance::Normal);
408
}
409
385
410
#[test]
386
411
fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {
387
412
assert_eq!(
@@ -1,6 +1,8 @@1
use chrono::{DateTime, Utc};1
use chrono::{DateTime, Utc};2
use graph::{Attachment, Chat, Mention, Message, Reaction};2
use graph::{Attachment, Chat, Mention, Message, Reaction};3
use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};3
use store::{4
ChannelRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord, TeamRecord,5
};4
6
5
use crate::adaptive_card::card_content_text;7
use crate::adaptive_card::card_content_text;6
use crate::call_event::CallEvent;8
use crate::call_event::CallEvent;@@ -182,6 +184,10 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag182
.as_ref()184
.as_ref()183
.map(CallEvent::to_json)185
.map(CallEvent::to_json)184
.or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),186
.or_else(|| roster_event.as_ref().map(RosterEvent::to_json)),187
importance: message188
.importance189
.as_deref()190
.map_or(MessageImportance::Normal, MessageImportance::from_graph),185
})191
})186
}192
}187
193
@@ -382,6 +388,25 @@ mod tests {382
message_record("c", &message).unwrap().subject388
message_record("c", &message).unwrap().subject383
}389
}384
390
391
#[test]392
fn importance_is_read_from_graph() {393
let importance = |value: serde_json::Value| {394
let message: Message = serde_json::from_value(json!({395
"id": "m1",396
"messageType": "message",397
"createdDateTime": "2026-10-17T10:00:00Z",398
"importance": value,399
"body": {"contentType": "html", "content": "<p>hi</p>"},400
}))401
.unwrap();402
message_record("c", &message).unwrap().importance403
};404
assert_eq!(importance(json!("high")), MessageImportance::High);405
assert_eq!(importance(json!("urgent")), MessageImportance::Urgent);406
assert_eq!(importance(json!("normal")), MessageImportance::Normal);407
assert_eq!(importance(json!(null)), MessageImportance::Normal);408
}409
385
#[test]410
#[test]386
fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {411
fn subject_is_kept_trimmed_and_blank_ones_are_dropped() {387
assert_eq!(412
assert_eq!(@@ -116,6 +116,7 @@ mod tests {
116
116
last_message_from: Some(format!("8:orgid:{from}")),
117
117
..ReadHorizon::default()
118
118
},
119
notification_settings: None,
119
120
history_cleared_ms: None,
120
121
}
121
122
}
@@ -116,6 +116,7 @@ mod tests {116
last_message_from: Some(format!("8:orgid:{from}")),116
last_message_from: Some(format!("8:orgid:{from}")),117
..ReadHorizon::default()117
..ReadHorizon::default()118
},118
},119
notification_settings: None,119
history_cleared_ms: None,120
history_cleared_ms: None,120
}121
}121
}122
}@@ -9,6 +9,10 @@ impl<R: Remote> SyncEngine<R> {
9
9
self.remote.recording_policy().await
10
10
}
11
11
12
pub async fn allow_priority_messages(&self) -> Result<bool> {
13
self.remote.allow_priority_messages().await
14
}
15
12
16
pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {
13
17
self.my_tenant_id(chat_id).await
14
18
}
@@ -9,6 +9,10 @@ impl<R: Remote> SyncEngine<R> {9
self.remote.recording_policy().await9
self.remote.recording_policy().await10
}10
}11
11
12
pub async fn allow_priority_messages(&self) -> Result<bool> {13
self.remote.allow_priority_messages().await14
}15
12
pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {16
pub async fn own_tenant_id(&self, chat_id: &str) -> Result<String> {13
self.my_tenant_id(chat_id).await17
self.my_tenant_id(chat_id).await14
}18
}@@ -3,8 +3,9 @@ use chatsvc::substrate_search::{
3
3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4
4
};
5
5
use chatsvc::{
6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,
7
parse_app_consumption_horizon,
6
ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,
7
ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,
8
MentionActivity, UserSettings, parse_app_consumption_horizon,
8
9
};
9
10
use chatsvc::{
10
11
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -26,6 +27,7 @@ use crate::error::{Error, Result};
26
27
use crate::profile::PersonProfile;
27
28
28
29
pub const CHATSVC_CHAT_WRITES: bool = false;
30
const URGENT_ACK_EMOTION: &str = "acks";
29
31
30
32
#[derive(Debug, Clone)]
31
33
pub struct RemotePage {
@@ -472,10 +474,36 @@ pub trait Remote {
472
474
Err(Error::Unsupported("recording policy"))
473
475
}
474
476
477
async fn allow_priority_messages(&self) -> Result<bool> {
478
Err(Error::Unsupported("messaging policy"))
479
}
480
481
async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {
482
Err(Error::Unsupported("urgent message acknowledgement"))
483
}
484
475
485
async fn sound_settings(&self) -> Result<SoundSettings> {
476
486
Err(Error::Unsupported("sound settings"))
477
487
}
478
488
489
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
490
Err(Error::Unsupported("chat settings"))
491
}
492
493
async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
494
Err(Error::Unsupported("chat settings"))
495
}
496
497
async fn set_chat_notifications(
498
&self,
499
_chat_id: &str,
500
_current_settings: Option<&str>,
501
_mode: ChatNotificationMode,
502
_desktop: DesktopNotifications,
503
) -> Result<ChatNotificationWrite> {
504
Err(Error::Unsupported("chat notifications"))
505
}
506
479
507
async fn save_sound_settings(
480
508
&self,
481
509
_user_mri: &str,
@@ -783,6 +811,17 @@ impl Remote for Graph {
783
811
.await?)
784
812
}
785
813
814
/// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.
815
async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {
816
Ok(Messages::new(self.session())
817
.set_emotion(
818
&ConversationRef::chat(chat_id),
819
message_id,
820
URGENT_ACK_EMOTION,
821
)
822
.await?)
823
}
824
786
825
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {
787
826
if let Some(key) = chatsvc::reaction_key(reaction_type) {
788
827
return Ok(Messages::new(self.session())
@@ -1231,6 +1270,12 @@ impl Remote for Graph {
1231
1270
.await?)
1232
1271
}
1233
1272
1273
async fn allow_priority_messages(&self) -> Result<bool> {
1274
Ok(LanguageSettingsClient::new(self.session())
1275
.read_allow_priority_messages()
1276
.await?)
1277
}
1278
1234
1279
async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {
1235
1280
Ok(LanguageSettingsClient::new(self.session())
1236
1281
.patch(patch)
@@ -1241,6 +1286,26 @@ impl Remote for Graph {
1241
1286
Ok(SoundSettingsClient::new(self.session()).read().await?)
1242
1287
}
1243
1288
1289
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1290
Ok(ChatSettingsClient::new(self.session()).read().await?)
1291
}
1292
1293
async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1294
Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1295
}
1296
1297
async fn set_chat_notifications(
1298
&self,
1299
chat_id: &str,
1300
current_settings: Option<&str>,
1301
mode: ChatNotificationMode,
1302
desktop: DesktopNotifications,
1303
) -> Result<ChatNotificationWrite> {
1304
Ok(Conversations::new(self.session())
1305
.set_chat_notifications(chat_id, current_settings, mode, desktop)
1306
.await?)
1307
}
1308
1244
1309
async fn save_sound_settings(
1245
1310
&self,
1246
1311
user_mri: &str,
@@ -3,8 +3,9 @@ use chatsvc::substrate_search::{3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,3
QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,4
};4
};5
use chatsvc::{5
use chatsvc::{6
ActivityFeed, AppConsumptionHorizon, MentionActivity, UserSettings,6
ActivityFeed, AppConsumptionHorizon, ChatNotificationMode, ChatNotificationWrite,7
parse_app_consumption_horizon,7
ChatSettingChange, ChatSettingsClient, ChatSettingsDocument, DesktopNotifications,8
MentionActivity, UserSettings, parse_app_consumption_horizon,8
};9
};9
use chatsvc::{10
use chatsvc::{10
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,11
BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,@@ -26,6 +27,7 @@ use crate::error::{Error, Result};26
use crate::profile::PersonProfile;27
use crate::profile::PersonProfile;27
28
28
pub const CHATSVC_CHAT_WRITES: bool = false;29
pub const CHATSVC_CHAT_WRITES: bool = false;30
const URGENT_ACK_EMOTION: &str = "acks";29
31
30
#[derive(Debug, Clone)]32
#[derive(Debug, Clone)]31
pub struct RemotePage {33
pub struct RemotePage {@@ -472,10 +474,36 @@ pub trait Remote {472
Err(Error::Unsupported("recording policy"))474
Err(Error::Unsupported("recording policy"))473
}475
}474
476
477
async fn allow_priority_messages(&self) -> Result<bool> {478
Err(Error::Unsupported("messaging policy"))479
}480
481
async fn ack_urgent_message(&self, _chat_id: &str, _message_id: &str) -> Result<()> {482
Err(Error::Unsupported("urgent message acknowledgement"))483
}484
475
async fn sound_settings(&self) -> Result<SoundSettings> {485
async fn sound_settings(&self) -> Result<SoundSettings> {476
Err(Error::Unsupported("sound settings"))486
Err(Error::Unsupported("sound settings"))477
}487
}478
488
489
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {490
Err(Error::Unsupported("chat settings"))491
}492
493
async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {494
Err(Error::Unsupported("chat settings"))495
}496
497
async fn set_chat_notifications(498
&self,499
_chat_id: &str,500
_current_settings: Option<&str>,501
_mode: ChatNotificationMode,502
_desktop: DesktopNotifications,503
) -> Result<ChatNotificationWrite> {504
Err(Error::Unsupported("chat notifications"))505
}506
479
async fn save_sound_settings(507
async fn save_sound_settings(480
&self,508
&self,481
_user_mri: &str,509
_user_mri: &str,@@ -783,6 +811,17 @@ impl Remote for Graph {783
.await?)811
.await?)784
}812
}785
813
814
/// Teams `ackUrgentMessage`: the emotion `acks` on the message stops the urgent repeat notifications.815
async fn ack_urgent_message(&self, chat_id: &str, message_id: &str) -> Result<()> {816
Ok(Messages::new(self.session())817
.set_emotion(818
&ConversationRef::chat(chat_id),819
message_id,820
URGENT_ACK_EMOTION,821
)822
.await?)823
}824
786
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {825
async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> {787
if let Some(key) = chatsvc::reaction_key(reaction_type) {826
if let Some(key) = chatsvc::reaction_key(reaction_type) {788
return Ok(Messages::new(self.session())827
return Ok(Messages::new(self.session())@@ -1231,6 +1270,12 @@ impl Remote for Graph {1231
.await?)1270
.await?)1232
}1271
}1233
1272
1273
async fn allow_priority_messages(&self) -> Result<bool> {1274
Ok(LanguageSettingsClient::new(self.session())1275
.read_allow_priority_messages()1276
.await?)1277
}1278
1234
async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {1279
async fn patch_language_settings(&self, patch: serde_json::Value) -> Result<()> {1235
Ok(LanguageSettingsClient::new(self.session())1280
Ok(LanguageSettingsClient::new(self.session())1236
.patch(patch)1281
.patch(patch)@@ -1241,6 +1286,26 @@ impl Remote for Graph {1241
Ok(SoundSettingsClient::new(self.session()).read().await?)1286
Ok(SoundSettingsClient::new(self.session()).read().await?)1242
}1287
}1243
1288
1289
async fn chat_settings(&self) -> Result<ChatSettingsDocument> {1290
Ok(ChatSettingsClient::new(self.session()).read().await?)1291
}1292
1293
async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {1294
Ok(ChatSettingsClient::new(self.session()).write(change).await?)1295
}1296
1297
async fn set_chat_notifications(1298
&self,1299
chat_id: &str,1300
current_settings: Option<&str>,1301
mode: ChatNotificationMode,1302
desktop: DesktopNotifications,1303
) -> Result<ChatNotificationWrite> {1304
Ok(Conversations::new(self.session())1305
.set_chat_notifications(chat_id, current_settings, mode, desktop)1306
.await?)1307
}1308
1244
async fn save_sound_settings(1309
async fn save_sound_settings(1245
&self,1310
&self,1246
user_mri: &str,1311
user_mri: &str,@@ -810,6 +810,7 @@ mod tests {
810
810
reactions_json: "[]".to_owned(),
811
811
mentions_json: "[]".to_owned(),
812
812
call_event_json: None,
813
importance: Default::default(),
813
814
}
814
815
}
815
816
@@ -810,6 +810,7 @@ mod tests {810
reactions_json: "[]".to_owned(),810
reactions_json: "[]".to_owned(),811
mentions_json: "[]".to_owned(),811
mentions_json: "[]".to_owned(),812
call_event_json: None,812
call_event_json: None,813
importance: Default::default(),813
}814
}814
}815
}815
816
@@ -584,6 +584,7 @@ impl Remote for Handle {
584
584
muted,
585
585
hidden: None,
586
586
read: chatsvc::ReadHorizon::default(),
587
notification_settings: None,
587
588
history_cleared_ms: None,
588
589
})
589
590
.collect();
@@ -595,6 +596,7 @@ impl Remote for Handle {
595
596
muted: false,
596
597
hidden: Some(hidden),
597
598
read: chatsvc::ReadHorizon::default(),
599
notification_settings: None,
598
600
history_cleared_ms: None,
599
601
}),
600
602
);
@@ -606,6 +608,7 @@ impl Remote for Handle {
606
608
muted: false,
607
609
hidden: None,
608
610
read,
611
notification_settings: None,
609
612
history_cleared_ms: None,
610
613
}),
611
614
);
@@ -2329,6 +2332,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {
2329
2332
bytes: Arc::new(vec![9]),
2330
2333
}],
2331
2334
files: Vec::new(),
2335
importance: None,
2332
2336
};
2333
2337
2334
2338
let sent = engine
@@ -2402,6 +2406,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {
2402
2406
bytes: Arc::new(vec![9]),
2403
2407
}],
2404
2408
files: Vec::new(),
2409
importance: None,
2405
2410
};
2406
2411
2407
2412
engine
@@ -2432,6 +2437,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {
2432
2437
bytes: Arc::new(vec![9, 8, 7]),
2433
2438
}],
2434
2439
files: Vec::new(),
2440
importance: None,
2435
2441
};
2436
2442
let mut events = engine.subscribe();
2437
2443
@@ -584,6 +584,7 @@ impl Remote for Handle {584
muted,584
muted,585
hidden: None,585
hidden: None,586
read: chatsvc::ReadHorizon::default(),586
read: chatsvc::ReadHorizon::default(),587
notification_settings: None,587
history_cleared_ms: None,588
history_cleared_ms: None,588
})589
})589
.collect();590
.collect();@@ -595,6 +596,7 @@ impl Remote for Handle {595
muted: false,596
muted: false,596
hidden: Some(hidden),597
hidden: Some(hidden),597
read: chatsvc::ReadHorizon::default(),598
read: chatsvc::ReadHorizon::default(),599
notification_settings: None,598
history_cleared_ms: None,600
history_cleared_ms: None,599
}),601
}),600
);602
);@@ -606,6 +608,7 @@ impl Remote for Handle {606
muted: false,608
muted: false,607
hidden: None,609
hidden: None,608
read,610
read,611
notification_settings: None,609
history_cleared_ms: None,612
history_cleared_ms: None,610
}),613
}),611
);614
);@@ -2329,6 +2332,7 @@ async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() {2329
bytes: Arc::new(vec![9]),2332
bytes: Arc::new(vec![9]),2330
}],2333
}],2331
files: Vec::new(),2334
files: Vec::new(),2335
importance: None,2332
};2336
};2333
2337
2334
let sent = engine2338
let sent = engine@@ -2402,6 +2406,7 @@ async fn send_with_extras_hands_images_and_files_to_the_remote() {2402
bytes: Arc::new(vec![9]),2406
bytes: Arc::new(vec![9]),2403
}],2407
}],2404
files: Vec::new(),2408
files: Vec::new(),2409
importance: None,2405
};2410
};2406
2411
2407
engine2412
engine@@ -2432,6 +2437,7 @@ async fn a_sent_image_is_cached_under_the_server_url_without_a_download() {2432
bytes: Arc::new(vec![9, 8, 7]),2437
bytes: Arc::new(vec![9, 8, 7]),2433
}],2438
}],2434
files: Vec::new(),2439
files: Vec::new(),2440
importance: None,2435
};2441
};2436
let mut events = engine.subscribe();2442
let mut events = engine.subscribe();2437
2443
@@ -374,6 +374,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
374
374
reactions_json: "[]".to_owned(),
375
375
mentions_json: "[]".to_owned(),
376
376
call_event_json: None,
377
importance: Default::default(),
377
378
}
378
379
}
379
380
@@ -374,6 +374,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {374
reactions_json: "[]".to_owned(),374
reactions_json: "[]".to_owned(),375
mentions_json: "[]".to_owned(),375
mentions_json: "[]".to_owned(),376
call_event_json: None,376
call_event_json: None,377
importance: Default::default(),377
}378
}378
}379
}379
380
@@ -125,6 +125,7 @@ pub struct Message {
125
125
pub is_deleted: Option<bool>,
126
126
pub reply_to_id: Option<String>,
127
127
pub subject: Option<String>,
128
pub importance: Option<String>,
128
129
pub from: Option<Sender>,
129
130
pub body: Option<Body>,
130
131
pub event_detail: Option<serde_json::Value>,
@@ -125,6 +125,7 @@ pub struct Message {125
pub is_deleted: Option<bool>,125
pub is_deleted: Option<bool>,126
pub reply_to_id: Option<String>,126
pub reply_to_id: Option<String>,127
pub subject: Option<String>,127
pub subject: Option<String>,128
pub importance: Option<String>,128
pub from: Option<Sender>,129
pub from: Option<Sender>,129
pub body: Option<Body>,130
pub body: Option<Body>,130
pub event_detail: Option<serde_json::Value>,131
pub event_detail: Option<serde_json::Value>,@@ -66,6 +66,8 @@ pub struct MessageExtras {
66
66
pub images: Vec<HostedImage>,
67
67
pub files: Vec<FileReference>,
68
68
pub kept: Vec<KeptAttachment>,
69
/// Graph `importance`: `"high"` or `"urgent"`, absent for a standard message.
70
pub importance: Option<&'static str>,
69
71
}
70
72
71
73
impl MessageExtras {
@@ -167,6 +169,9 @@ pub(crate) fn message_body(
167
169
});
168
170
body["attachments"] = Value::Array(kept.chain(files).collect());
169
171
}
172
if let Some(importance) = extras.importance {
173
body["importance"] = json!(importance);
174
}
170
175
body
171
176
}
172
177
@@ -256,6 +261,23 @@ mod tests {
256
261
}
257
262
}
258
263
264
#[test]
265
fn importance_is_sent_like_teams() {
266
let extras = MessageExtras {
267
importance: Some("urgent"),
268
..MessageExtras::default()
269
};
270
assert_eq!(
271
message_body("<p>x</p>", &[], &extras),
272
json!({"body": {"contentType": "html", "content": "<p>x</p>"}, "importance": "urgent"})
273
);
274
assert!(
275
message_body("<p>x</p>", &[], &MessageExtras::default())
276
.get("importance")
277
.is_none()
278
);
279
}
280
259
281
#[test]
260
282
fn plain_body_has_no_hosted_contents_or_attachments() {
261
283
let body = message_body("<p>x</p>", &[], &MessageExtras::default());
@@ -271,6 +293,7 @@ mod tests {
271
293
kept: Vec::new(),
272
294
images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],
273
295
files: Vec::new(),
296
importance: None,
274
297
};
275
298
let body = message_body("<p>hi</p>", &[], &extras);
276
299
assert_eq!(
@@ -297,6 +320,7 @@ mod tests {
297
320
image("image/png", &[3]),
298
321
],
299
322
files: Vec::new(),
323
importance: None,
300
324
};
301
325
let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";
302
326
assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);
@@ -309,6 +333,7 @@ mod tests {
309
333
kept: Vec::new(),
310
334
images: vec![image("image/png", &[1]), image("image/png", &[2])],
311
335
files: Vec::new(),
336
importance: None,
312
337
};
313
338
let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);
314
339
assert_eq!(
@@ -328,6 +353,7 @@ mod tests {
328
353
content_url: "https://x/a.pdf".into(),
329
354
name: "a.pdf".into(),
330
355
}],
356
importance: None,
331
357
};
332
358
let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";
333
359
let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);
@@ -351,6 +377,7 @@ mod tests {
351
377
content_url: None,
352
378
name: None,
353
379
}],
380
importance: None,
354
381
};
355
382
let body = message_body("<p>new</p>", &[], &extras);
356
383
assert_eq!(
@@ -371,6 +398,7 @@ mod tests {
371
398
content_url: "https://contoso.sharepoint.com/Plan.docx".into(),
372
399
name: "Plan.docx".into(),
373
400
}],
401
importance: None,
374
402
};
375
403
let body = message_body("", &[], &extras);
376
404
assert_eq!(
@@ -66,6 +66,8 @@ pub struct MessageExtras {66
pub images: Vec<HostedImage>,66
pub images: Vec<HostedImage>,67
pub files: Vec<FileReference>,67
pub files: Vec<FileReference>,68
pub kept: Vec<KeptAttachment>,68
pub kept: Vec<KeptAttachment>,69
/// Graph `importance`: `"high"` or `"urgent"`, absent for a standard message.70
pub importance: Option<&'static str>,69
}71
}70
72
71
impl MessageExtras {73
impl MessageExtras {@@ -167,6 +169,9 @@ pub(crate) fn message_body(167
});169
});168
body["attachments"] = Value::Array(kept.chain(files).collect());170
body["attachments"] = Value::Array(kept.chain(files).collect());169
}171
}172
if let Some(importance) = extras.importance {173
body["importance"] = json!(importance);174
}170
body175
body171
}176
}172
177
@@ -256,6 +261,23 @@ mod tests {256
}261
}257
}262
}258
263
264
#[test]265
fn importance_is_sent_like_teams() {266
let extras = MessageExtras {267
importance: Some("urgent"),268
..MessageExtras::default()269
};270
assert_eq!(271
message_body("<p>x</p>", &[], &extras),272
json!({"body": {"contentType": "html", "content": "<p>x</p>"}, "importance": "urgent"})273
);274
assert!(275
message_body("<p>x</p>", &[], &MessageExtras::default())276
.get("importance")277
.is_none()278
);279
}280
259
#[test]281
#[test]260
fn plain_body_has_no_hosted_contents_or_attachments() {282
fn plain_body_has_no_hosted_contents_or_attachments() {261
let body = message_body("<p>x</p>", &[], &MessageExtras::default());283
let body = message_body("<p>x</p>", &[], &MessageExtras::default());@@ -271,6 +293,7 @@ mod tests {271
kept: Vec::new(),293
kept: Vec::new(),272
images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],294
images: vec![image("image/png", &[1, 2, 3]), image("image/jpeg", &[4])],273
files: Vec::new(),295
files: Vec::new(),296
importance: None,274
};297
};275
let body = message_body("<p>hi</p>", &[], &extras);298
let body = message_body("<p>hi</p>", &[], &extras);276
assert_eq!(299
assert_eq!(@@ -297,6 +320,7 @@ mod tests {297
image("image/png", &[3]),320
image("image/png", &[3]),298
],321
],299
files: Vec::new(),322
files: Vec::new(),323
importance: None,300
};324
};301
let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";325
let html = "a <img src=\"../hostedContents/3/$value\"> <img src=\"https://giphy.com/x.gif\"> <img src=\"../hostedContents/1/$value\">";302
assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);326
assert_eq!(hosted_image_order(html, &extras), vec![2, 0, 1]);@@ -309,6 +333,7 @@ mod tests {309
kept: Vec::new(),333
kept: Vec::new(),310
images: vec![image("image/png", &[1]), image("image/png", &[2])],334
images: vec![image("image/png", &[1]), image("image/png", &[2])],311
files: Vec::new(),335
files: Vec::new(),336
importance: None,312
};337
};313
let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);338
let body = message_body("a <img src=\"../hostedContents/2/$value\"> b", &[], &extras);314
assert_eq!(339
assert_eq!(@@ -328,6 +353,7 @@ mod tests {328
content_url: "https://x/a.pdf".into(),353
content_url: "https://x/a.pdf".into(),329
name: "a.pdf".into(),354
name: "a.pdf".into(),330
}],355
}],356
importance: None,331
};357
};332
let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";358
let original_image = "<img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\">";333
let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);359
let body = message_body(&format!("<p>new</p>{original_image}"), &[], &extras);@@ -351,6 +377,7 @@ mod tests {351
content_url: None,377
content_url: None,352
name: None,378
name: None,353
}],379
}],380
importance: None,354
};381
};355
let body = message_body("<p>new</p>", &[], &extras);382
let body = message_body("<p>new</p>", &[], &extras);356
assert_eq!(383
assert_eq!(@@ -371,6 +398,7 @@ mod tests {371
content_url: "https://contoso.sharepoint.com/Plan.docx".into(),398
content_url: "https://contoso.sharepoint.com/Plan.docx".into(),372
name: "Plan.docx".into(),399
name: "Plan.docx".into(),373
}],400
}],401
importance: None,374
};402
};375
let body = message_body("", &[], &extras);403
let body = message_body("", &[], &extras);376
assert_eq!(404
assert_eq!(@@ -27,11 +27,12 @@ pub use error::{Error, Result};
27
27
pub use image_files::ImageFileCache;
28
28
pub use models::{
29
29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,
32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,
33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,
34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,
30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions,
31
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,
32
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,
33
MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,
34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,
35
UNKNOWN_USER_NAME, is_bot_id,
35
36
};
36
37
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};
37
38
pub use store::{DATA_DIR_NAME, Store, default_database_path};
@@ -27,11 +27,12 @@ pub use error::{Error, Result};27
pub use image_files::ImageFileCache;27
pub use image_files::ImageFileCache;28
pub use models::{28
pub use models::{29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,29
ActivityRecord, AgentProposalMention, AgentProposalRecord, AgentReactionRecord,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,30
AttachmentImage, AvatarRecord, BOT_MRI_PREFIX, ChannelLayoutRecord, ChannelMentions,31
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord,31
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview,32
ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord, MessageRecord,32
ChatRecord, ConversationHit, DraftRecord, FolderRecord, ImageRecord, MemberRecord,33
OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord, RecentScope, SearchHit, Sidebar,33
MessageImportance, MessageRecord, OutboxRecord, OutboxState, OutboxTarget, ReadHorizonRecord,34
SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME, is_bot_id,34
RecentScope, SearchHit, Sidebar, SidebarTeam, SyncState, TeamLayoutRecord, TeamRecord,35
UNKNOWN_USER_NAME, is_bot_id,35
};36
};36
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};37
pub use search::{HIGHLIGHT_END, HIGHLIGHT_START};37
pub use store::{DATA_DIR_NAME, Store, default_database_path};38
pub use store::{DATA_DIR_NAME, Store, default_database_path};@@ -4,13 +4,13 @@ use chrono::{DateTime, Utc};
4
4
use rusqlite::{OptionalExtension, Row, params, params_from_iter};
5
5
6
6
use crate::error::Result;
7
use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};
7
use crate::models::{MessageImportance, MessageRecord, RecentScope, UNKNOWN_USER_NAME};
8
8
use crate::search::index_message;
9
9
use crate::store::Store;
10
10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json";
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json, importance";
14
14
15
15
impl Store {
16
16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,7 +19,7 @@ impl Store {
19
19
{
20
20
let mut upsert = transaction.prepare_cached(&format!(
21
21
"INSERT INTO messages ({MESSAGE_COLUMNS})
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
23
23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24
24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25
25
sender_name = excluded.sender_name, created_at = excluded.created_at,
@@ -28,6 +28,7 @@ impl Store {
28
28
mentions_json = excluded.mentions_json,
29
29
sender_application_id = excluded.sender_application_id,
30
30
subject = COALESCE(excluded.subject, messages.subject),
31
importance = COALESCE(excluded.importance, messages.importance),
31
32
call_event_json = excluded.call_event_json,
32
33
links_json = CASE WHEN excluded.links_json IN ('', '[]')
33
34
THEN messages.links_json ELSE excluded.links_json END"
@@ -50,6 +51,7 @@ impl Store {
50
51
message.links_json,
51
52
message.subject,
52
53
message.call_event_json,
54
message.importance.stored(),
53
55
])?;
54
56
index_message(&transaction, message)?;
55
57
}
@@ -94,6 +96,35 @@ impl Store {
94
96
Ok(count as usize)
95
97
}
96
98
99
/// Teams marks a chat in the list by the importance of its last message while it is unread and from someone else.
100
pub fn unread_last_message_importance(
101
&self,
102
conversation_id: &str,
103
after: Option<DateTime<Utc>>,
104
not_from_user_id: &str,
105
) -> Result<MessageImportance> {
106
let connection = self.lock()?;
107
let last: Option<(Option<String>, Option<String>, i64)> = connection
108
.query_row(
109
"SELECT importance, sender_id, created_at FROM messages
110
WHERE conversation_id = ?1 AND deleted = 0 AND call_event_json IS NULL
111
ORDER BY created_at DESC, message_id DESC LIMIT 1",
112
params![conversation_id],
113
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
114
)
115
.optional()?;
116
let Some((importance, sender_id, created_at)) = last else {
117
return Ok(MessageImportance::Normal);
118
};
119
let unread = created_at > optional_to_millis(after).unwrap_or(i64::MIN);
120
let from_others = sender_id.as_deref() != Some(not_from_user_id);
121
Ok(if unread && from_others {
122
MessageImportance::from_stored(importance.as_deref())
123
} else {
124
MessageImportance::Normal
125
})
126
}
127
97
128
pub fn first_message_after_from_others(
98
129
&self,
99
130
conversation_id: &str,
@@ -435,5 +466,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
435
466
links_json: row.get(13)?,
436
467
subject: row.get(14)?,
437
468
call_event_json: row.get(15)?,
469
importance: MessageImportance::from_stored(row.get::<_, Option<String>>(16)?.as_deref()),
438
470
})
439
471
}
@@ -4,13 +4,13 @@ use chrono::{DateTime, Utc};4
use rusqlite::{OptionalExtension, Row, params, params_from_iter};4
use rusqlite::{OptionalExtension, Row, params, params_from_iter};5
5
6
use crate::error::Result;6
use crate::error::Result;7
use crate::models::{MessageRecord, RecentScope, UNKNOWN_USER_NAME};7
use crate::models::{MessageImportance, MessageRecord, RecentScope, UNKNOWN_USER_NAME};8
use crate::search::index_message;8
use crate::search::index_message;9
use crate::store::Store;9
use crate::store::Store;10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};11
11
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json";13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json, subject, call_event_json, importance";14
14
15
impl Store {15
impl Store {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {@@ -19,7 +19,7 @@ impl Store {19
{19
{20
let mut upsert = transaction.prepare_cached(&format!(20
let mut upsert = transaction.prepare_cached(&format!(21
"INSERT INTO messages ({MESSAGE_COLUMNS})21
"INSERT INTO messages ({MESSAGE_COLUMNS})22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16)22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,25
sender_name = excluded.sender_name, created_at = excluded.created_at,25
sender_name = excluded.sender_name, created_at = excluded.created_at,@@ -28,6 +28,7 @@ impl Store {28
mentions_json = excluded.mentions_json,28
mentions_json = excluded.mentions_json,29
sender_application_id = excluded.sender_application_id,29
sender_application_id = excluded.sender_application_id,30
subject = COALESCE(excluded.subject, messages.subject),30
subject = COALESCE(excluded.subject, messages.subject),31
importance = COALESCE(excluded.importance, messages.importance),31
call_event_json = excluded.call_event_json,32
call_event_json = excluded.call_event_json,32
links_json = CASE WHEN excluded.links_json IN ('', '[]')33
links_json = CASE WHEN excluded.links_json IN ('', '[]')33
THEN messages.links_json ELSE excluded.links_json END"34
THEN messages.links_json ELSE excluded.links_json END"@@ -50,6 +51,7 @@ impl Store {50
message.links_json,51
message.links_json,51
message.subject,52
message.subject,52
message.call_event_json,53
message.call_event_json,54
message.importance.stored(),53
])?;55
])?;54
index_message(&transaction, message)?;56
index_message(&transaction, message)?;55
}57
}@@ -94,6 +96,35 @@ impl Store {94
Ok(count as usize)96
Ok(count as usize)95
}97
}96
98
99
/// Teams marks a chat in the list by the importance of its last message while it is unread and from someone else.100
pub fn unread_last_message_importance(101
&self,102
conversation_id: &str,103
after: Option<DateTime<Utc>>,104
not_from_user_id: &str,105
) -> Result<MessageImportance> {106
let connection = self.lock()?;107
let last: Option<(Option<String>, Option<String>, i64)> = connection108
.query_row(109
"SELECT importance, sender_id, created_at FROM messages110
WHERE conversation_id = ?1 AND deleted = 0 AND call_event_json IS NULL111
ORDER BY created_at DESC, message_id DESC LIMIT 1",112
params![conversation_id],113
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),114
)115
.optional()?;116
let Some((importance, sender_id, created_at)) = last else {117
return Ok(MessageImportance::Normal);118
};119
let unread = created_at > optional_to_millis(after).unwrap_or(i64::MIN);120
let from_others = sender_id.as_deref() != Some(not_from_user_id);121
Ok(if unread && from_others {122
MessageImportance::from_stored(importance.as_deref())123
} else {124
MessageImportance::Normal125
})126
}127
97
pub fn first_message_after_from_others(128
pub fn first_message_after_from_others(98
&self,129
&self,99
conversation_id: &str,130
conversation_id: &str,@@ -435,5 +466,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {435
links_json: row.get(13)?,466
links_json: row.get(13)?,436
subject: row.get(14)?,467
subject: row.get(14)?,437
call_event_json: row.get(15)?,468
call_event_json: row.get(15)?,469
importance: MessageImportance::from_stored(row.get::<_, Option<String>>(16)?.as_deref()),438
})470
})439
}471
}@@ -101,6 +101,10 @@ const MIGRATIONS: &[Migration] = &[
101
101
script: include_str!("migrations/0023_channel_mentions.sql"),
102
102
after: None,
103
103
},
104
Migration {
105
script: include_str!("migrations/0024_message_importance.sql"),
106
after: None,
107
},
104
108
];
105
109
106
110
pub fn latest_version() -> i64 {
@@ -101,6 +101,10 @@ const MIGRATIONS: &[Migration] = &[101
script: include_str!("migrations/0023_channel_mentions.sql"),101
script: include_str!("migrations/0023_channel_mentions.sql"),102
after: None,102
after: None,103
},103
},104
Migration {105
script: include_str!("migrations/0024_message_importance.sql"),106
after: None,107
},104
];108
];105
109
106
pub fn latest_version() -> i64 {110
pub fn latest_version() -> i64 {@@ -0,0 +1 @@
1
ALTER TABLE messages ADD COLUMN importance TEXT;
@@ -0,0 +1 @@1
ALTER TABLE messages ADD COLUMN importance TEXT;@@ -103,6 +103,46 @@ pub struct MessageRecord {
103
103
pub links_json: String,
104
104
pub subject: Option<String>,
105
105
pub call_event_json: Option<String>,
106
pub importance: MessageImportance,
107
}
108
109
/// Graph `chatMessage.importance`; chatsvc keeps the same value in the message property `importance`.
110
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
111
pub enum MessageImportance {
112
#[default]
113
Normal,
114
High,
115
Urgent,
116
}
117
118
impl MessageImportance {
119
pub fn from_graph(value: &str) -> MessageImportance {
120
match value.trim().to_ascii_lowercase().as_str() {
121
"high" => MessageImportance::High,
122
"urgent" => MessageImportance::Urgent,
123
_ => MessageImportance::Normal,
124
}
125
}
126
127
pub fn graph_value(self) -> &'static str {
128
match self {
129
MessageImportance::Normal => "normal",
130
MessageImportance::High => "high",
131
MessageImportance::Urgent => "urgent",
132
}
133
}
134
135
pub fn stored(self) -> Option<&'static str> {
136
(self != MessageImportance::Normal).then(|| self.graph_value())
137
}
138
139
pub fn from_stored(value: Option<&str>) -> MessageImportance {
140
value.map_or(MessageImportance::Normal, MessageImportance::from_graph)
141
}
142
143
pub fn is_marked(self) -> bool {
144
self != MessageImportance::Normal
145
}
106
146
}
107
147
108
148
#[derive(Debug, Clone, PartialEq)]
@@ -103,6 +103,46 @@ pub struct MessageRecord {103
pub links_json: String,103
pub links_json: String,104
pub subject: Option<String>,104
pub subject: Option<String>,105
pub call_event_json: Option<String>,105
pub call_event_json: Option<String>,106
pub importance: MessageImportance,107
}108
109
/// Graph `chatMessage.importance`; chatsvc keeps the same value in the message property `importance`.110
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]111
pub enum MessageImportance {112
#[default]113
Normal,114
High,115
Urgent,116
}117
118
impl MessageImportance {119
pub fn from_graph(value: &str) -> MessageImportance {120
match value.trim().to_ascii_lowercase().as_str() {121
"high" => MessageImportance::High,122
"urgent" => MessageImportance::Urgent,123
_ => MessageImportance::Normal,124
}125
}126
127
pub fn graph_value(self) -> &'static str {128
match self {129
MessageImportance::Normal => "normal",130
MessageImportance::High => "high",131
MessageImportance::Urgent => "urgent",132
}133
}134
135
pub fn stored(self) -> Option<&'static str> {136
(self != MessageImportance::Normal).then(|| self.graph_value())137
}138
139
pub fn from_stored(value: Option<&str>) -> MessageImportance {140
value.map_or(MessageImportance::Normal, MessageImportance::from_graph)141
}142
143
pub fn is_marked(self) -> bool {144
self != MessageImportance::Normal145
}106
}146
}107
147
108
#[derive(Debug, Clone, PartialEq)]148
#[derive(Debug, Clone, PartialEq)]@@ -3,8 +3,8 @@ use rusqlite::Connection;
3
3
use store::{
4
4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,
5
5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,
6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,
7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
6
MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,
7
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,
8
8
};
9
9
10
10
#[test]
@@ -105,9 +105,52 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
105
105
links_json: "[]".to_owned(),
106
106
subject: None,
107
107
call_event_json: None,
108
importance: MessageImportance::Normal,
108
109
}
109
110
}
110
111
112
#[test]
113
fn importance_round_trips_and_survives_an_upsert_without_one() {
114
let store = Store::open_in_memory().unwrap();
115
let urgent = MessageRecord {
116
importance: MessageImportance::Urgent,
117
..message("c1", "m1", 1)
118
};
119
store
120
.upsert_messages(std::slice::from_ref(&urgent))
121
.unwrap();
122
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
123
assert_eq!(found["m1"].importance, MessageImportance::Urgent);
124
125
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
126
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
127
assert_eq!(found["m1"].importance, MessageImportance::Urgent);
128
}
129
130
#[test]
131
fn unread_marker_follows_the_last_message_from_others() {
132
let store = Store::open_in_memory().unwrap();
133
let important = MessageRecord {
134
importance: MessageImportance::High,
135
..message("c1", "m2", 2)
136
};
137
store
138
.upsert_messages(&[message("c1", "m1", 1), important])
139
.unwrap();
140
let marker = |after: Option<u32>, me: &str| {
141
store
142
.unread_last_message_importance("c1", after.map(at), me)
143
.unwrap()
144
};
145
assert_eq!(marker(None, "me"), MessageImportance::High);
146
assert_eq!(marker(Some(1), "me"), MessageImportance::High);
147
assert_eq!(marker(Some(2), "me"), MessageImportance::Normal);
148
assert_eq!(marker(None, "user-ada"), MessageImportance::Normal);
149
150
store.upsert_messages(&[message("c1", "m3", 3)]).unwrap();
151
assert_eq!(marker(None, "me"), MessageImportance::Normal);
152
}
153
111
154
#[test]
112
155
fn subject_round_trips_and_survives_an_upsert_without_one() {
113
156
let store = Store::open_in_memory().unwrap();
@@ -546,11 +589,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
546
589
let path = directory.path().join("nested").join("cache.sqlite3");
547
590
{
548
591
let store = Store::open(&path).unwrap();
549
assert_eq!(store.schema_version().unwrap(), 23);
592
assert_eq!(store.schema_version().unwrap(), 24);
550
593
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
551
594
}
552
595
let reopened = Store::open(&path).unwrap();
553
assert_eq!(reopened.schema_version().unwrap(), 23);
596
assert_eq!(reopened.schema_version().unwrap(), 24);
554
597
assert_eq!(reopened.message_count("c").unwrap(), 1);
555
598
drop(reopened);
556
599
let mode: String = rusqlite_open(&path)
@@ -582,7 +625,7 @@ fn old_schema_is_upgraded_in_place() {
582
625
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
583
626
drop(connection);
584
627
let store = Store::open(&path).unwrap();
585
assert_eq!(store.schema_version().unwrap(), 23);
628
assert_eq!(store.schema_version().unwrap(), 24);
586
629
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
587
630
}
588
631
@@ -648,7 +691,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
648
691
let store = Store::open(&path).unwrap();
649
692
let state = store.sync_state("c").unwrap().unwrap();
650
693
assert_eq!(state.delta_link, None);
651
assert_eq!(store.schema_version().unwrap(), 23);
694
assert_eq!(store.schema_version().unwrap(), 24);
652
695
}
653
696
654
697
#[test]
@@ -666,6 +709,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {
666
709
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');
667
710
ALTER TABLE messages DROP COLUMN subject;
668
711
ALTER TABLE messages DROP COLUMN call_event_json;
712
ALTER TABLE messages DROP COLUMN importance;
669
713
ALTER TABLE folders DROP COLUMN expanded;
670
714
DROP TABLE channel_tabs;
671
715
DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;
@@ -952,6 +996,7 @@ fn migration_indexes_rows_that_predate_search() {
952
996
ALTER TABLE messages DROP COLUMN links_json;
953
997
ALTER TABLE messages DROP COLUMN subject;
954
998
ALTER TABLE messages DROP COLUMN call_event_json;
999
ALTER TABLE messages DROP COLUMN importance;
955
1000
ALTER TABLE chats DROP COLUMN muted;
956
1001
ALTER TABLE folders DROP COLUMN expanded;
957
1002
PRAGMA user_version = 3;",
@@ -1517,12 +1562,12 @@ fn migration_to_v20_adds_the_call_event_column() {
1517
1562
Connection::open(&path)
1518
1563
.unwrap()
1519
1564
.execute_batch(
1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",
1565
"ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",
1521
1566
)
1522
1567
.unwrap();
1523
1568
}
1524
1569
let store = Store::open(&path).unwrap();
1525
assert_eq!(store.schema_version().unwrap(), 23);
1570
assert_eq!(store.schema_version().unwrap(), 24);
1526
1571
let old = store.messages("c", None, 10).unwrap();
1527
1572
assert_eq!(old[0].call_event_json, None);
1528
1573
assert!(store.sync_state("c").unwrap().is_none());
@@ -1568,11 +1613,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {
1568
1613
drop(store);
1569
1614
Connection::open(&path)
1570
1615
.unwrap()
1571
.execute_batch("PRAGMA user_version = 20")
1616
.execute_batch("ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")
1572
1617
.unwrap();
1573
1618
}
1574
1619
let store = Store::open(&path).unwrap();
1575
assert_eq!(store.schema_version().unwrap(), 23);
1620
assert_eq!(store.schema_version().unwrap(), 24);
1576
1621
assert!(store.sync_state("c").unwrap().is_none());
1577
1622
assert!(store.sync_state("channel").unwrap().is_none());
1578
1623
assert!(store.sync_state("other").unwrap().is_some());
@@ -1598,11 +1643,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {
1598
1643
drop(store);
1599
1644
Connection::open(&path)
1600
1645
.unwrap()
1601
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")
1646
.execute_batch("DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")
1602
1647
.unwrap();
1603
1648
}
1604
1649
let store = Store::open(&path).unwrap();
1605
assert_eq!(store.schema_version().unwrap(), 23);
1650
assert_eq!(store.schema_version().unwrap(), 24);
1606
1651
assert!(store.read_horizons("c").unwrap().is_empty());
1607
1652
let horizons = [
1608
1653
horizon("8:orgid:ada", 3, Some(4)),
@@ -3,8 +3,8 @@ use rusqlite::Connection;3
use store::{3
use store::{4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,4
AvatarRecord, ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel,5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,5
ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatPreview, ChatRecord, FolderRecord,6
MemberRecord, MessageRecord, ReadHorizonRecord, RecentScope, Store, SyncState,6
MemberRecord, MessageImportance, MessageRecord, ReadHorizonRecord, RecentScope, Store,7
TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,7
SyncState, TeamLayoutRecord, TeamRecord, UNKNOWN_USER_NAME,8
};8
};9
9
10
#[test]10
#[test]@@ -105,9 +105,52 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor105
links_json: "[]".to_owned(),105
links_json: "[]".to_owned(),106
subject: None,106
subject: None,107
call_event_json: None,107
call_event_json: None,108
importance: MessageImportance::Normal,108
}109
}109
}110
}110
111
112
#[test]113
fn importance_round_trips_and_survives_an_upsert_without_one() {114
let store = Store::open_in_memory().unwrap();115
let urgent = MessageRecord {116
importance: MessageImportance::Urgent,117
..message("c1", "m1", 1)118
};119
store120
.upsert_messages(std::slice::from_ref(&urgent))121
.unwrap();122
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();123
assert_eq!(found["m1"].importance, MessageImportance::Urgent);124
125
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();126
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();127
assert_eq!(found["m1"].importance, MessageImportance::Urgent);128
}129
130
#[test]131
fn unread_marker_follows_the_last_message_from_others() {132
let store = Store::open_in_memory().unwrap();133
let important = MessageRecord {134
importance: MessageImportance::High,135
..message("c1", "m2", 2)136
};137
store138
.upsert_messages(&[message("c1", "m1", 1), important])139
.unwrap();140
let marker = |after: Option<u32>, me: &str| {141
store142
.unread_last_message_importance("c1", after.map(at), me)143
.unwrap()144
};145
assert_eq!(marker(None, "me"), MessageImportance::High);146
assert_eq!(marker(Some(1), "me"), MessageImportance::High);147
assert_eq!(marker(Some(2), "me"), MessageImportance::Normal);148
assert_eq!(marker(None, "user-ada"), MessageImportance::Normal);149
150
store.upsert_messages(&[message("c1", "m3", 3)]).unwrap();151
assert_eq!(marker(None, "me"), MessageImportance::Normal);152
}153
111
#[test]154
#[test]112
fn subject_round_trips_and_survives_an_upsert_without_one() {155
fn subject_round_trips_and_survives_an_upsert_without_one() {113
let store = Store::open_in_memory().unwrap();156
let store = Store::open_in_memory().unwrap();@@ -546,11 +589,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {546
let path = directory.path().join("nested").join("cache.sqlite3");589
let path = directory.path().join("nested").join("cache.sqlite3");547
{590
{548
let store = Store::open(&path).unwrap();591
let store = Store::open(&path).unwrap();549
assert_eq!(store.schema_version().unwrap(), 23);592
assert_eq!(store.schema_version().unwrap(), 24);550
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();593
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();551
}594
}552
let reopened = Store::open(&path).unwrap();595
let reopened = Store::open(&path).unwrap();553
assert_eq!(reopened.schema_version().unwrap(), 23);596
assert_eq!(reopened.schema_version().unwrap(), 24);554
assert_eq!(reopened.message_count("c").unwrap(), 1);597
assert_eq!(reopened.message_count("c").unwrap(), 1);555
drop(reopened);598
drop(reopened);556
let mode: String = rusqlite_open(&path)599
let mode: String = rusqlite_open(&path)@@ -582,7 +625,7 @@ fn old_schema_is_upgraded_in_place() {582
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();625
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();583
drop(connection);626
drop(connection);584
let store = Store::open(&path).unwrap();627
let store = Store::open(&path).unwrap();585
assert_eq!(store.schema_version().unwrap(), 23);628
assert_eq!(store.schema_version().unwrap(), 24);586
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();629
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();587
}630
}588
631
@@ -648,7 +691,7 @@ fn migration_to_v2_keeps_existing_sync_state() {648
let store = Store::open(&path).unwrap();691
let store = Store::open(&path).unwrap();649
let state = store.sync_state("c").unwrap().unwrap();692
let state = store.sync_state("c").unwrap().unwrap();650
assert_eq!(state.delta_link, None);693
assert_eq!(state.delta_link, None);651
assert_eq!(store.schema_version().unwrap(), 23);694
assert_eq!(store.schema_version().unwrap(), 24);652
}695
}653
696
654
#[test]697
#[test]@@ -666,6 +709,7 @@ fn migration_to_v13_clears_channel_delta_links_only() {666
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');709
INSERT INTO sync_state (conversation_id, delta_link) VALUES ('ch', 'link'), ('chat', 'link');667
ALTER TABLE messages DROP COLUMN subject;710
ALTER TABLE messages DROP COLUMN subject;668
ALTER TABLE messages DROP COLUMN call_event_json;711
ALTER TABLE messages DROP COLUMN call_event_json;712
ALTER TABLE messages DROP COLUMN importance;669
ALTER TABLE folders DROP COLUMN expanded;713
ALTER TABLE folders DROP COLUMN expanded;670
DROP TABLE channel_tabs;714
DROP TABLE channel_tabs;671
DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;715
DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals;@@ -952,6 +996,7 @@ fn migration_indexes_rows_that_predate_search() {952
ALTER TABLE messages DROP COLUMN links_json;996
ALTER TABLE messages DROP COLUMN links_json;953
ALTER TABLE messages DROP COLUMN subject;997
ALTER TABLE messages DROP COLUMN subject;954
ALTER TABLE messages DROP COLUMN call_event_json;998
ALTER TABLE messages DROP COLUMN call_event_json;999
ALTER TABLE messages DROP COLUMN importance;955
ALTER TABLE chats DROP COLUMN muted;1000
ALTER TABLE chats DROP COLUMN muted;956
ALTER TABLE folders DROP COLUMN expanded;1001
ALTER TABLE folders DROP COLUMN expanded;957
PRAGMA user_version = 3;",1002
PRAGMA user_version = 3;",@@ -1517,12 +1562,12 @@ fn migration_to_v20_adds_the_call_event_column() {1517
Connection::open(&path)1562
Connection::open(&path)1518
.unwrap()1563
.unwrap()1519
.execute_batch(1564
.execute_batch(1520
"ALTER TABLE messages DROP COLUMN call_event_json; PRAGMA user_version = 19",1565
"ALTER TABLE messages DROP COLUMN call_event_json; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 19",1521
)1566
)1522
.unwrap();1567
.unwrap();1523
}1568
}1524
let store = Store::open(&path).unwrap();1569
let store = Store::open(&path).unwrap();1525
assert_eq!(store.schema_version().unwrap(), 23);1570
assert_eq!(store.schema_version().unwrap(), 24);1526
let old = store.messages("c", None, 10).unwrap();1571
let old = store.messages("c", None, 10).unwrap();1527
assert_eq!(old[0].call_event_json, None);1572
assert_eq!(old[0].call_event_json, None);1528
assert!(store.sync_state("c").unwrap().is_none());1573
assert!(store.sync_state("c").unwrap().is_none());@@ -1568,11 +1613,11 @@ fn migration_to_v21_refetches_chats_and_channels_for_recordings() {1568
drop(store);1613
drop(store);1569
Connection::open(&path)1614
Connection::open(&path)1570
.unwrap()1615
.unwrap()1571
.execute_batch("PRAGMA user_version = 20")1616
.execute_batch("ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 20")1572
.unwrap();1617
.unwrap();1573
}1618
}1574
let store = Store::open(&path).unwrap();1619
let store = Store::open(&path).unwrap();1575
assert_eq!(store.schema_version().unwrap(), 23);1620
assert_eq!(store.schema_version().unwrap(), 24);1576
assert!(store.sync_state("c").unwrap().is_none());1621
assert!(store.sync_state("c").unwrap().is_none());1577
assert!(store.sync_state("channel").unwrap().is_none());1622
assert!(store.sync_state("channel").unwrap().is_none());1578
assert!(store.sync_state("other").unwrap().is_some());1623
assert!(store.sync_state("other").unwrap().is_some());@@ -1598,11 +1643,11 @@ fn migration_to_v22_adds_read_horizons_that_survive_a_reopen() {1598
drop(store);1643
drop(store);1599
Connection::open(&path)1644
Connection::open(&path)1600
.unwrap()1645
.unwrap()1601
.execute_batch("DROP TABLE read_horizons; PRAGMA user_version = 21")1646
.execute_batch("DROP TABLE read_horizons; ALTER TABLE messages DROP COLUMN importance; PRAGMA user_version = 21")1602
.unwrap();1647
.unwrap();1603
}1648
}1604
let store = Store::open(&path).unwrap();1649
let store = Store::open(&path).unwrap();1605
assert_eq!(store.schema_version().unwrap(), 23);1650
assert_eq!(store.schema_version().unwrap(), 24);1606
assert!(store.read_horizons("c").unwrap().is_empty());1651
assert!(store.read_horizons("c").unwrap().is_empty());1607
let horizons = [1652
let horizons = [1608
horizon("8:orgid:ada", 3, Some(4)),1653
horizon("8:orgid:ada", 3, Some(4)),@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse
37
37
text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
38
38
open(path, 'w').write(text)
39
39
PY
40
for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do
41
patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"
42
done
40
43
# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
41
44
if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
42
45
rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse37
text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)37
text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)38
open(path, 'w').write(text)38
open(path, 'w').write(text)39
PY39
PY40
for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do41
patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"42
done40
# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.43
# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.41
if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then44
if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then42
rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"45
rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"@@ -0,0 +1,177 @@
1
diff -ruN a/src/events.rs b/src/events.rs
2
--- a/src/events.rs
3
+++ b/src/events.rs
4
@@ -10,7 +10,7 @@
5
UI::{
6
Controls::*,
7
HiDpi::*,
8
- Input::{Ime::*, KeyboardAndMouse::*},
9
+ Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},
10
WindowsAndMessaging::*,
11
},
12
},
13
@@ -31,6 +31,7 @@
14
pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;
15
16
const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
17
+const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;
18
19
/// Coordinates window draws on the UI thread. Owned by the platform and
20
/// shared with every window (like `WindowsPlatformState::cursor_visible`),
21
@@ -149,6 +150,10 @@
22
}
23
WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
24
WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
25
+ WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),
26
+ WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),
27
+ WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),
28
+ WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),
29
WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
30
WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
31
WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),
32
@@ -647,6 +652,62 @@
33
if handled { Some(0) } else { Some(1) }
34
}
35
36
+ fn handle_touch_pointer_msg(
37
+ &self,
38
+ handle: HWND,
39
+ wparam: WPARAM,
40
+ lparam: LPARAM,
41
+ phase: TouchPhase,
42
+ ) -> Option<isize> {
43
+ let pointer_id = wparam.loword() as u32;
44
+ let mut pointer_type = POINTER_INPUT_TYPE::default();
45
+ unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;
46
+ if pointer_type != PT_TOUCH {
47
+ return None;
48
+ }
49
+ let phase = if phase == TouchPhase::Ended
50
+ && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 0
51
+ {
52
+ TouchPhase::Cancelled
53
+ } else {
54
+ phase
55
+ };
56
+ let mut cursor_point = POINT {
57
+ x: lparam.signed_loword().into(),
58
+ y: lparam.signed_hiword().into(),
59
+ };
60
+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
61
+ let position = logical_point(
62
+ cursor_point.x as f32,
63
+ cursor_point.y as f32,
64
+ self.state.scale_factor.get(),
65
+ );
66
+ if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {
67
+ self.dispatch_touch(touch_id, phase, position);
68
+ }
69
+ Some(0)
70
+ }
71
+
72
+ fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {
73
+ let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;
74
+ self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);
75
+ Some(0)
76
+ }
77
+
78
+ fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {
79
+ let Some(mut func) = self.state.callbacks.input.take() else {
80
+ return;
81
+ };
82
+ func(PlatformInput::Touch(TouchEvent {
83
+ id: touch_id,
84
+ phase,
85
+ position,
86
+ predicted_position: None,
87
+ force: None,
88
+ }));
89
+ self.state.callbacks.input.set(Some(func));
90
+ }
91
+
92
fn retrieve_caret_position(&self) -> Option<POINT> {
93
self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
94
let caret_range = input_handler.selected_text_range(false)?;
95
diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs
96
--- a/src/gpui_windows.rs
97
+++ b/src/gpui_windows.rs
98
@@ -15,6 +15,7 @@
99
mod platform;
100
mod system_notifications;
101
mod system_settings;
102
+mod touch;
103
mod util;
104
mod vsync;
105
mod window;
106
@@ -33,6 +34,7 @@
107
pub(crate) use platform::*;
108
pub(crate) use system_notifications::*;
109
pub(crate) use system_settings::*;
110
+pub(crate) use touch::*;
111
pub(crate) use util::*;
112
pub(crate) use vsync::*;
113
pub(crate) use window::*;
114
diff -ruN a/src/touch.rs b/src/touch.rs
115
--- a/src/touch.rs
116
+++ b/src/touch.rs
117
@@ -0,0 +1,41 @@
118
+use std::cell::{Cell, RefCell};
119
+use std::collections::HashMap;
120
+
121
+use gpui::{Pixels, Point, TouchId, TouchPhase};
122
+
123
+#[derive(Default)]
124
+pub(crate) struct TouchPointers {
125
+ next_touch_id: Cell<u64>,
126
+ active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,
127
+}
128
+
129
+impl TouchPointers {
130
+ pub(crate) fn track(
131
+ &self,
132
+ pointer_id: u32,
133
+ phase: TouchPhase,
134
+ position: Point<Pixels>,
135
+ ) -> Option<TouchId> {
136
+ let mut active = self.active.borrow_mut();
137
+ match phase {
138
+ TouchPhase::Started => {
139
+ let touch_id = TouchId(self.next_touch_id.get());
140
+ self.next_touch_id.set(self.next_touch_id.get() + 1);
141
+ active.insert(pointer_id, (touch_id, position));
142
+ Some(touch_id)
143
+ }
144
+ TouchPhase::Moved => {
145
+ let entry = active.get_mut(&pointer_id)?;
146
+ entry.1 = position;
147
+ Some(entry.0)
148
+ }
149
+ TouchPhase::Ended | TouchPhase::Cancelled => {
150
+ active.remove(&pointer_id).map(|(touch_id, _)| touch_id)
151
+ }
152
+ }
153
+ }
154
+
155
+ pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {
156
+ self.active.borrow_mut().remove(&pointer_id)
157
+ }
158
+}
159
diff -ruN a/src/window.rs b/src/window.rs
160
--- a/src/window.rs
161
+++ b/src/window.rs
162
@@ -63,6 +63,7 @@
163
pub hovered: Cell<bool>,
164
pub last_visibility: Cell<Option<WindowVisibility>>,
165
pub direct_manipulation: DirectManipulationHandler,
166
+ pub touch_pointers: TouchPointers,
167
168
pub renderer: RefCell<DirectXRenderer>,
169
/// Set when the next `draw_window` call must be treated as a forced
170
@@ -190,6 +191,7 @@
171
invalidate_devices,
172
draw_coordinator,
173
direct_manipulation,
174
+ touch_pointers: TouchPointers::default(),
175
a11y: RefCell::new(None),
176
})
177
}
@@ -0,0 +1,177 @@1
diff -ruN a/src/events.rs b/src/events.rs2
--- a/src/events.rs3
+++ b/src/events.rs4
@@ -10,7 +10,7 @@5
UI::{6
Controls::*,7
HiDpi::*,8
- Input::{Ime::*, KeyboardAndMouse::*},9
+ Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},10
WindowsAndMessaging::*,11
},12
},13
@@ -31,6 +31,7 @@14
pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;15
16
const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;17
+const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;18
19
/// Coordinates window draws on the UI thread. Owned by the platform and20
/// shared with every window (like `WindowsPlatformState::cursor_visible`),21
@@ -149,6 +150,10 @@22
}23
WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),24
WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),25
+ WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),26
+ WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),27
+ WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),28
+ WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),29
WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),30
WM_KEYUP => self.handle_keyup_msg(wparam, lparam),31
WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),32
@@ -647,6 +652,62 @@33
if handled { Some(0) } else { Some(1) }34
}35
36
+ fn handle_touch_pointer_msg(37
+ &self,38
+ handle: HWND,39
+ wparam: WPARAM,40
+ lparam: LPARAM,41
+ phase: TouchPhase,42
+ ) -> Option<isize> {43
+ let pointer_id = wparam.loword() as u32;44
+ let mut pointer_type = POINTER_INPUT_TYPE::default();45
+ unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;46
+ if pointer_type != PT_TOUCH {47
+ return None;48
+ }49
+ let phase = if phase == TouchPhase::Ended50
+ && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 051
+ {52
+ TouchPhase::Cancelled53
+ } else {54
+ phase55
+ };56
+ let mut cursor_point = POINT {57
+ x: lparam.signed_loword().into(),58
+ y: lparam.signed_hiword().into(),59
+ };60
+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };61
+ let position = logical_point(62
+ cursor_point.x as f32,63
+ cursor_point.y as f32,64
+ self.state.scale_factor.get(),65
+ );66
+ if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {67
+ self.dispatch_touch(touch_id, phase, position);68
+ }69
+ Some(0)70
+ }71
+72
+ fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {73
+ let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;74
+ self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);75
+ Some(0)76
+ }77
+78
+ fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {79
+ let Some(mut func) = self.state.callbacks.input.take() else {80
+ return;81
+ };82
+ func(PlatformInput::Touch(TouchEvent {83
+ id: touch_id,84
+ phase,85
+ position,86
+ predicted_position: None,87
+ force: None,88
+ }));89
+ self.state.callbacks.input.set(Some(func));90
+ }91
+92
fn retrieve_caret_position(&self) -> Option<POINT> {93
self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {94
let caret_range = input_handler.selected_text_range(false)?;95
diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs96
--- a/src/gpui_windows.rs97
+++ b/src/gpui_windows.rs98
@@ -15,6 +15,7 @@99
mod platform;100
mod system_notifications;101
mod system_settings;102
+mod touch;103
mod util;104
mod vsync;105
mod window;106
@@ -33,6 +34,7 @@107
pub(crate) use platform::*;108
pub(crate) use system_notifications::*;109
pub(crate) use system_settings::*;110
+pub(crate) use touch::*;111
pub(crate) use util::*;112
pub(crate) use vsync::*;113
pub(crate) use window::*;114
diff -ruN a/src/touch.rs b/src/touch.rs115
--- a/src/touch.rs116
+++ b/src/touch.rs117
@@ -0,0 +1,41 @@118
+use std::cell::{Cell, RefCell};119
+use std::collections::HashMap;120
+121
+use gpui::{Pixels, Point, TouchId, TouchPhase};122
+123
+#[derive(Default)]124
+pub(crate) struct TouchPointers {125
+ next_touch_id: Cell<u64>,126
+ active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,127
+}128
+129
+impl TouchPointers {130
+ pub(crate) fn track(131
+ &self,132
+ pointer_id: u32,133
+ phase: TouchPhase,134
+ position: Point<Pixels>,135
+ ) -> Option<TouchId> {136
+ let mut active = self.active.borrow_mut();137
+ match phase {138
+ TouchPhase::Started => {139
+ let touch_id = TouchId(self.next_touch_id.get());140
+ self.next_touch_id.set(self.next_touch_id.get() + 1);141
+ active.insert(pointer_id, (touch_id, position));142
+ Some(touch_id)143
+ }144
+ TouchPhase::Moved => {145
+ let entry = active.get_mut(&pointer_id)?;146
+ entry.1 = position;147
+ Some(entry.0)148
+ }149
+ TouchPhase::Ended | TouchPhase::Cancelled => {150
+ active.remove(&pointer_id).map(|(touch_id, _)| touch_id)151
+ }152
+ }153
+ }154
+155
+ pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {156
+ self.active.borrow_mut().remove(&pointer_id)157
+ }158
+}159
diff -ruN a/src/window.rs b/src/window.rs160
--- a/src/window.rs161
+++ b/src/window.rs162
@@ -63,6 +63,7 @@163
pub hovered: Cell<bool>,164
pub last_visibility: Cell<Option<WindowVisibility>>,165
pub direct_manipulation: DirectManipulationHandler,166
+ pub touch_pointers: TouchPointers,167
168
pub renderer: RefCell<DirectXRenderer>,169
/// Set when the next `draw_window` call must be treated as a forced170
@@ -190,6 +191,7 @@171
invalidate_devices,172
draw_coordinator,173
direct_manipulation,174
+ touch_pointers: TouchPointers::default(),175
a11y: RefCell::new(None),176
})177
}@@ -745,9 +745,8 @@ impl RenderOnce for Button {
745
745
.justify_center()
746
746
.button_text_size(self.size)
747
747
.map(|this| match self.size {
748
Size::XSmall => this.gap_1(),
749
Size::Small => this.gap_1(),
750
_ => this.gap_2(),
748
Size::XSmall | Size::Small => this.gap(crate::fluent::BUTTON_ICON_GAP_SMALL),
749
_ => this.gap(crate::fluent::BUTTON_ICON_GAP),
751
750
})
752
751
.refine_style(&self.content_style)
753
752
.when_some(self.icon, |this, icon| {
@@ -745,9 +745,8 @@ impl RenderOnce for Button {745
.justify_center()745
.justify_center()746
.button_text_size(self.size)746
.button_text_size(self.size)747
.map(|this| match self.size {747
.map(|this| match self.size {748
Size::XSmall => this.gap_1(),748
Size::XSmall | Size::Small => this.gap(crate::fluent::BUTTON_ICON_GAP_SMALL),749
Size::Small => this.gap_1(),749
_ => this.gap(crate::fluent::BUTTON_ICON_GAP),750
_ => this.gap_2(),751
})750
})752
.refine_style(&self.content_style)751
.refine_style(&self.content_style)753
.when_some(self.icon, |this, icon| {752
.when_some(self.icon, |this, icon| {@@ -0,0 +1,29 @@
1
//! Fluent UI v9 metrics as shipped in the Teams web bundle.
2
3
use gpui::{Pixels, px};
4
5
pub const MENU_ITEM_HEIGHT: Pixels = px(32.);
6
pub const MENU_ITEM_PADDING_X: Pixels = px(6.);
7
pub const MENU_ICON_SLOT: Pixels = px(20.);
8
// A Lucide glyph at 18 px covers what a Fluent 20 px regular icon covers.
9
pub const MENU_ICON_GLYPH: Pixels = px(18.);
10
pub const MENU_ICON_GAP: Pixels = px(4.);
11
pub const MENU_LABEL_INSET: Pixels = px(2.);
12
pub const MENU_ICON_LABEL_GAP: Pixels = px(6.);
13
pub const MENU_LIST_PADDING: Pixels = px(4.);
14
pub const MENU_ITEM_GAP: Pixels = px(2.);
15
pub const MENU_DIVIDER_MARGIN_Y: Pixels = px(4.);
16
17
pub const OPTION_CHECK_INSET: Pixels = px(6.);
18
pub const OPTION_PADDING_RIGHT: Pixels = px(8.);
19
pub const OPTION_CHECK_SIZE: Pixels = px(16.);
20
pub const OPTION_CHECK_GAP: Pixels = px(6.);
21
pub const LISTBOX_MIN_WIDTH: Pixels = px(160.);
22
pub const DROPDOWN_OFFSET: Pixels = px(2.);
23
24
pub const BUTTON_ICON_GAP: Pixels = px(6.);
25
pub const BUTTON_ICON_GAP_SMALL: Pixels = px(4.);
26
27
pub const TOAST_ICON_SIZE: Pixels = px(16.);
28
pub const TOAST_ICON_GAP: Pixels = px(8.);
29
pub const TOAST_LINE_HEIGHT: Pixels = px(20.);
@@ -0,0 +1,29 @@1
//! Fluent UI v9 metrics as shipped in the Teams web bundle.2
3
use gpui::{Pixels, px};4
5
pub const MENU_ITEM_HEIGHT: Pixels = px(32.);6
pub const MENU_ITEM_PADDING_X: Pixels = px(6.);7
pub const MENU_ICON_SLOT: Pixels = px(20.);8
// A Lucide glyph at 18 px covers what a Fluent 20 px regular icon covers.9
pub const MENU_ICON_GLYPH: Pixels = px(18.);10
pub const MENU_ICON_GAP: Pixels = px(4.);11
pub const MENU_LABEL_INSET: Pixels = px(2.);12
pub const MENU_ICON_LABEL_GAP: Pixels = px(6.);13
pub const MENU_LIST_PADDING: Pixels = px(4.);14
pub const MENU_ITEM_GAP: Pixels = px(2.);15
pub const MENU_DIVIDER_MARGIN_Y: Pixels = px(4.);16
17
pub const OPTION_CHECK_INSET: Pixels = px(6.);18
pub const OPTION_PADDING_RIGHT: Pixels = px(8.);19
pub const OPTION_CHECK_SIZE: Pixels = px(16.);20
pub const OPTION_CHECK_GAP: Pixels = px(6.);21
pub const LISTBOX_MIN_WIDTH: Pixels = px(160.);22
pub const DROPDOWN_OFFSET: Pixels = px(2.);23
24
pub const BUTTON_ICON_GAP: Pixels = px(6.);25
pub const BUTTON_ICON_GAP_SMALL: Pixels = px(4.);26
27
pub const TOAST_ICON_SIZE: Pixels = px(16.);28
pub const TOAST_ICON_GAP: Pixels = px(8.);29
pub const TOAST_LINE_HEIGHT: Pixels = px(20.);@@ -164,6 +164,10 @@ impl Icon {
164
164
Self::default()
165
165
}
166
166
167
pub(crate) fn has_explicit_size(&self) -> bool {
168
self.size.is_some() || self.style.size.width.is_some() || self.style.size.height.is_some()
169
}
170
167
171
/// Rotate the icon by the given angle
168
172
///
169
173
/// Replaces any previous transformation or rotation.
@@ -164,6 +164,10 @@ impl Icon {164
Self::default()164
Self::default()165
}165
}166
166
167
pub(crate) fn has_explicit_size(&self) -> bool {168
self.size.is_some() || self.style.size.width.is_some() || self.style.size.height.is_some()169
}170
167
/// Rotate the icon by the given angle171
/// Rotate the icon by the given angle168
///172
///169
/// Replaces any previous transformation or rotation.173
/// Replaces any previous transformation or rotation.@@ -44,6 +44,7 @@ pub mod dialog;
44
44
pub mod dock;
45
45
pub mod elevation;
46
46
pub mod empty;
47
pub mod fluent;
47
48
pub mod form;
48
49
pub mod group_box;
49
50
pub mod highlighter;
@@ -44,6 +44,7 @@ pub mod dialog;44
pub mod dock;44
pub mod dock;45
pub mod elevation;45
pub mod elevation;46
pub mod empty;46
pub mod empty;47
pub mod fluent;47
pub mod form;48
pub mod form;48
pub mod group_box;49
pub mod group_box;49
pub mod highlighter;50
pub mod highlighter;@@ -19,6 +19,7 @@ use gpui_base::{
19
19
ToastTransitionStatus,
20
20
};
21
21
22
use crate::fluent::{TOAST_ICON_GAP, TOAST_ICON_SIZE, TOAST_LINE_HEIGHT};
22
23
use crate::{
23
24
ActiveTheme as _, Edges, Icon, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT,
24
25
animation::cubic_bezier,
@@ -30,6 +31,8 @@ const NOTIFICATION_TRANSITION_DURATION: Duration = Duration::from_millis(400);
30
31
const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);
31
32
const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);
32
33
const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);
34
const TOAST_PADDING_X: Pixels = px(16.);
35
const TOAST_PADDING_Y: Pixels = px(14.);
33
36
const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);
34
37
struct DismissRequest;
35
38
@@ -432,18 +435,28 @@ impl Render for Notification {
432
435
.bg(toast_elevation.fill)
433
436
.rounded(cx.theme().radius_lg)
434
437
.shadow(resting_shadow)
435
.py_3p5()
436
.px_4()
438
.py(TOAST_PADDING_Y)
439
.px(TOAST_PADDING_X)
437
440
.gap_3()
438
441
.refine_style(&self.style)
439
442
.when_some(icon, |this, icon| {
440
this.child(div().absolute().top(px(18.)).left_4().child(icon))
443
this.child(
444
div()
445
.absolute()
446
.top(TOAST_PADDING_Y)
447
.left(TOAST_PADDING_X)
448
.h(TOAST_LINE_HEIGHT)
449
.flex()
450
.items_center()
451
.child(icon.with_size(TOAST_ICON_SIZE)),
452
)
441
453
})
442
454
.child(
443
455
v_flex()
444
456
.flex_1()
445
457
.overflow_hidden()
446
.when(has_icon, |this| this.pl_6())
458
.line_height(TOAST_LINE_HEIGHT)
459
.when(has_icon, |this| this.pl(TOAST_ICON_SIZE + TOAST_ICON_GAP))
447
460
.when_some(self.title.clone(), |this, title| {
448
461
this.child(div().text_sm().font_semibold().child(title))
449
462
})
@@ -19,6 +19,7 @@ use gpui_base::{19
ToastTransitionStatus,19
ToastTransitionStatus,20
};20
};21
21
22
use crate::fluent::{TOAST_ICON_GAP, TOAST_ICON_SIZE, TOAST_LINE_HEIGHT};22
use crate::{23
use crate::{23
ActiveTheme as _, Edges, Icon, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT,24
ActiveTheme as _, Edges, Icon, IconName, Sizable as _, StyledExt, TITLE_BAR_HEIGHT,24
animation::cubic_bezier,25
animation::cubic_bezier,@@ -30,6 +31,8 @@ const NOTIFICATION_TRANSITION_DURATION: Duration = Duration::from_millis(400);30
const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);31
const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);31
const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);32
const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);32
const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);33
const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);34
const TOAST_PADDING_X: Pixels = px(16.);35
const TOAST_PADDING_Y: Pixels = px(14.);33
const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);36
const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);34
struct DismissRequest;37
struct DismissRequest;35
38
@@ -432,18 +435,28 @@ impl Render for Notification {432
.bg(toast_elevation.fill)435
.bg(toast_elevation.fill)433
.rounded(cx.theme().radius_lg)436
.rounded(cx.theme().radius_lg)434
.shadow(resting_shadow)437
.shadow(resting_shadow)435
.py_3p5()438
.py(TOAST_PADDING_Y)436
.px_4()439
.px(TOAST_PADDING_X)437
.gap_3()440
.gap_3()438
.refine_style(&self.style)441
.refine_style(&self.style)439
.when_some(icon, |this, icon| {442
.when_some(icon, |this, icon| {440
this.child(div().absolute().top(px(18.)).left_4().child(icon))443
this.child(444
div()445
.absolute()446
.top(TOAST_PADDING_Y)447
.left(TOAST_PADDING_X)448
.h(TOAST_LINE_HEIGHT)449
.flex()450
.items_center()451
.child(icon.with_size(TOAST_ICON_SIZE)),452
)441
})453
})442
.child(454
.child(443
v_flex()455
v_flex()444
.flex_1()456
.flex_1()445
.overflow_hidden()457
.overflow_hidden()446
.when(has_icon, |this| this.pl_6())458
.line_height(TOAST_LINE_HEIGHT)459
.when(has_icon, |this| this.pl(TOAST_ICON_SIZE + TOAST_ICON_GAP))447
.when_some(self.title.clone(), |this, title| {460
.when_some(self.title.clone(), |this, title| {448
this.child(div().text_sm().font_semibold().child(title))461
this.child(div().text_sm().font_semibold().child(title))449
})462
})@@ -36,7 +36,7 @@ fn dropdown_positioner(bounds: Bounds<Pixels>) -> gpui_base::Positioner {
36
36
gpui_base::Positioner::side(bounds)
37
37
.placement(gpui_base::Placement::Bottom)
38
38
.align(gpui_base::Align::Start)
39
.offset(px(6.))
39
.offset(crate::fluent::DROPDOWN_OFFSET)
40
40
.margin(px(8.))
41
41
}
42
42
@@ -36,7 +36,7 @@ fn dropdown_positioner(bounds: Bounds<Pixels>) -> gpui_base::Positioner {36
gpui_base::Positioner::side(bounds)36
gpui_base::Positioner::side(bounds)37
.placement(gpui_base::Placement::Bottom)37
.placement(gpui_base::Placement::Bottom)38
.align(gpui_base::Align::Start)38
.align(gpui_base::Align::Start)39
.offset(px(6.))39
.offset(crate::fluent::DROPDOWN_OFFSET)40
.margin(px(8.))40
.margin(px(8.))41
}41
}42
42