BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/touch-scroll

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
494570f9e4d3b225a9735b9d9324c0a523f5b59e
57 files changed +2813 −293
crates/app-state/src/activity/feed.rs +1 −0
@@ -575,6 +575,7 @@ 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),
579 580 }
580 581 }
@@ -575,6 +575,7 @@ 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),
579 }
580 }
580 }
581 }
crates/app-state/src/app_state.rs +10 −0
@@ -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)]
@@ -140,6 +141,9 @@ pub struct AppState {
140 141 pub call_share_sound: bool,
141 142 pub recording_policy: teams_core::RecordingPolicy,
142 143 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
144 pub chat_settings: teams_core::ChatSettingsDocument,
145 pub markdown_mode: bool,
146 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
143 147 pub own_tenant: Option<String>,
144 148 pub call_share_motion: bool,
145 149 pub call_share_standout: bool,
@@ -231,6 +235,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
231 235 impl AppState {
232 236 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
233 237 let sidebar = store.sidebar().unwrap_or_default();
238 let chat_settings = teams_core::stored_chat_settings(&store);
239 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
234 240 let mut state = AppState {
235 241 store,
236 242 engine: None,
@@ -293,6 +299,9 @@ impl AppState {
293 299 call_share_sound: false,
294 300 recording_policy: teams_core::RecordingPolicy::default(),
295 301 account_sounds: None,
302 chat_settings,
303 markdown_mode,
304 demo_chat_desktop: HashMap::new(),
296 305 own_tenant: None,
297 306 call_share_motion: false,
298 307 call_share_standout: false,
@@ -994,6 +1003,7 @@ impl AppState {
994 1003 self.refresh_translation_settings(cx);
995 1004 self.refresh_recording_policy(cx);
996 1005 self.refresh_sound_settings(cx);
1006 self.refresh_chat_settings(cx);
997 1007 let waiting = self.directory.waiting_presence_ids();
998 1008 self.request_presence(waiting, cx);
999 1009 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)]
@@ -140,6 +141,9 @@ pub struct AppState {
140 pub call_share_sound: bool,
141 pub call_share_sound: bool,
141 pub recording_policy: teams_core::RecordingPolicy,
142 pub recording_policy: teams_core::RecordingPolicy,
142 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
143 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
144 pub chat_settings: teams_core::ChatSettingsDocument,
145 pub markdown_mode: bool,
146 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
143 pub own_tenant: Option<String>,
147 pub own_tenant: Option<String>,
144 pub call_share_motion: bool,
148 pub call_share_motion: bool,
145 pub call_share_standout: bool,
149 pub call_share_standout: bool,
@@ -231,6 +235,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
231impl AppState {
235impl AppState {
232 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
236 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
233 let sidebar = store.sidebar().unwrap_or_default();
237 let sidebar = store.sidebar().unwrap_or_default();
238 let chat_settings = teams_core::stored_chat_settings(&store);
239 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
234 let mut state = AppState {
240 let mut state = AppState {
235 store,
241 store,
236 engine: None,
242 engine: None,
@@ -293,6 +299,9 @@ impl AppState {
293 call_share_sound: false,
299 call_share_sound: false,
294 recording_policy: teams_core::RecordingPolicy::default(),
300 recording_policy: teams_core::RecordingPolicy::default(),
295 account_sounds: None,
301 account_sounds: None,
302 chat_settings,
303 markdown_mode,
304 demo_chat_desktop: HashMap::new(),
296 own_tenant: None,
305 own_tenant: None,
297 call_share_motion: false,
306 call_share_motion: false,
298 call_share_standout: false,
307 call_share_standout: false,
@@ -994,6 +1003,7 @@ impl AppState {
994 self.refresh_translation_settings(cx);
1003 self.refresh_translation_settings(cx);
995 self.refresh_recording_policy(cx);
1004 self.refresh_recording_policy(cx);
996 self.refresh_sound_settings(cx);
1005 self.refresh_sound_settings(cx);
1006 self.refresh_chat_settings(cx);
997 let waiting = self.directory.waiting_presence_ids();
1007 let waiting = self.directory.waiting_presence_ids();
998 self.request_presence(waiting, cx);
1008 self.request_presence(waiting, cx);
999 self.refresh_own_status(cx);
1009 self.refresh_own_status(cx);
crates/app-state/src/chat_actions.rs +1 −1
@@ -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.sidebar
394 self.sidebar
395 .chats
395 .chats
396 .iter()
396 .iter()
crates/app-state/src/chat_settings_actions.rs added +162 −0
@@ -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 @@
1use gpui_kit::Context;
2use store::Store;
3use teams_core::{
4 ChatAccountSettings, ChatNotificationMode, ChatSettingChange, ChatSettingsDocument,
5 DesktopNotifications,
6};
7
8use crate::app_state::{AppEvent, AppState};
9use crate::rows::Receipt;
10use crate::runtime;
11
12const META_MARKDOWN_MODE: &str = "compose.markdown_mode";
13
14pub 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.
19pub fn shown_receipt(settings: &ChatAccountSettings, receipt: Receipt) -> Receipt {
20 if settings.read_receipts {
21 receipt
22 } else {
23 Receipt::Hidden
24 }
25}
26
27impl 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)]
142mod 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}
crates/app-state/src/lib.rs +1 −0
@@ -14,6 +14,7 @@ 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;
@@ -14,6 +14,7 @@ pub mod chat_actions;
14pub mod chat_filter;
14pub mod chat_filter;
15pub mod find_in_chat;
15pub mod find_in_chat;
16pub mod chat_members;
16pub mod chat_members;
17pub mod chat_settings_actions;
17pub mod connection_banner;
18pub mod connection_banner;
18pub mod data;
19pub mod data;
19pub mod default_reactions;
20pub mod default_reactions;
crates/app-state/src/notify/incoming.rs +45 −1
@@ -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,32 @@ 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,
175 177 })
176 178 }
177 179
180 fn chat_signals(
181 store: &Store,
182 sidebar: &Sidebar,
183 conversation_id: &str,
184 my_user_id: Option<&str>,
185 ) -> ChatSignals {
186 let meeting = sidebar
187 .chats
188 .iter()
189 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));
190 let participated = meeting
191 && store
192 .messages(conversation_id, None, RECENT_WINDOW)
193 .is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));
194 ChatSignals {
195 meeting,
196 participated,
197 ..ChatSignals::default()
198 }
199 }
200
178 201 fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
179 202 sidebar
180 203 .chats
@@ -388,6 +411,27 @@ mod tests {
388 411 assert!(!build(&sidebar()).muted);
389 412 }
390 413
414 #[test]
415 fn meeting_chats_know_whether_i_took_part() {
416 let mut with_meeting = sidebar();
417 with_meeting.chats[1].kind = "meeting".into();
418 let store = Store::open_in_memory().unwrap();
419 let message = record("group", "u1", Utc::now(), "hi");
420 let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
421 assert!(first.chat.meeting);
422 assert!(!first.chat.participated);
423 let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");
424 store.upsert_messages(&[own]).unwrap();
425 let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
426 assert!(later.chat.participated);
427 assert!(
428 !build_incoming(&message, &store, &sidebar(), Some("me"))
429 .unwrap()
430 .chat
431 .meeting
432 );
433 }
434
391 435 #[test]
392 436 fn history_before_start_is_ignored() {
393 437 let start = Utc::now();
@@ -3,7 +3,7 @@ use std::collections::{HashMap, HashSet, VecDeque};
3use chrono::{DateTime, Utc};
3use chrono::{DateTime, Utc};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
4use store::{ChannelNotifications, MessageRecord, Sidebar, Store};
5
5
6use super::rules::{ChannelSignals, ChatKind, Incoming, Preview};
6use super::rules::{ChannelSignals, ChatKind, ChatSignals, Incoming, Preview};
7use crate::app_state::chat_title;
7use crate::app_state::chat_title;
8
8
9const RECENT_WINDOW: usize = 20;
9const 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,32 @@ 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,
175 })
177 })
176}
178}
177
179
180fn chat_signals(
181 store: &Store,
182 sidebar: &Sidebar,
183 conversation_id: &str,
184 my_user_id: Option<&str>,
185) -> ChatSignals {
186 let meeting = sidebar
187 .chats
188 .iter()
189 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));
190 let participated = meeting
191 && store
192 .messages(conversation_id, None, RECENT_WINDOW)
193 .is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));
194 ChatSignals {
195 meeting,
196 participated,
197 ..ChatSignals::default()
198 }
199}
200
178fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
201fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
179 sidebar
202 sidebar
180 .chats
203 .chats
@@ -388,6 +411,27 @@ mod tests {
388 assert!(!build(&sidebar()).muted);
411 assert!(!build(&sidebar()).muted);
389 }
412 }
390
413
414 #[test]
415 fn meeting_chats_know_whether_i_took_part() {
416 let mut with_meeting = sidebar();
417 with_meeting.chats[1].kind = "meeting".into();
418 let store = Store::open_in_memory().unwrap();
419 let message = record("group", "u1", Utc::now(), "hi");
420 let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
421 assert!(first.chat.meeting);
422 assert!(!first.chat.participated);
423 let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");
424 store.upsert_messages(&[own]).unwrap();
425 let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
426 assert!(later.chat.participated);
427 assert!(
428 !build_incoming(&message, &store, &sidebar(), Some("me"))
429 .unwrap()
430 .chat
431 .meeting
432 );
433 }
434
391 #[test]
435 #[test]
392 fn history_before_start_is_ignored() {
436 fn history_before_start_is_ignored() {
393 let start = Utc::now();
437 let start = Utc::now();
crates/app-state/src/notify/rules.rs +123 −22
@@ -4,6 +4,9 @@ use std::time::{Duration, Instant};
4 4 use calling::Progress;
5 5 use chrono::{DateTime, Utc};
6 6 use store::{ChannelNotificationLevel, ChannelNotifications};
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,6 +136,7 @@ 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>,
132 141 }
133 142
@@ -201,6 +210,36 @@ fn channel_toasts(incoming: &Incoming) -> bool {
201 210 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
202 211 }
203 212
213 fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {
214 if matches!(incoming.kind, ChatKind::Channel { .. }) {
215 return if incoming.mentions_me {
216 account.personal_mentions.shows_banner()
217 } else {
218 account.preset != NotificationPreset::MentionsAndReplies
219 || incoming.signals.in_my_thread
220 };
221 }
222 let chat = incoming.chat;
223 if chat.desktop == DesktopNotifications::Off {
224 return false;
225 }
226 if incoming.mentions_me {
227 return account.personal_mentions.shows_banner();
228 }
229 let meeting_muted = chat.meeting
230 && match account.meeting_chats {
231 MeetingChatNotifications::Mute => true,
232 MeetingChatNotifications::MuteUntilJoin => !chat.participated,
233 MeetingChatNotifications::Unmute => false,
234 };
235 !meeting_muted
236 && (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())
237 }
238
239 pub fn shows_preview(settings: &Settings) -> bool {
240 settings.account.show_preview
241 }
242
204 243 const SILENT: Decision = Decision {
205 244 toast: false,
206 245 sound: false,
@@ -214,7 +253,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
214 253 || environment.own_do_not_disturb
215 254 || settings.do_not_disturb
216 255 || (settings.mute_in_calls && environment.in_call)
217 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());
256 || !account_toasts(&settings.account, incoming);
218 257 if suppressed {
219 258 return SILENT;
220 259 }
@@ -267,6 +306,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)
267 306 #[cfg(test)]
268 307 mod tests {
269 308 use calling::{CallState, EndReason};
309 use teams_core::ActivityAlert;
270 310
271 311 use super::*;
272 312
@@ -282,6 +322,7 @@ mod tests {
282 322 mentions_me: false,
283 323 muted: false,
284 324 signals: ChannelSignals::default(),
325 chat: ChatSignals::default(),
285 326 created_at: Utc::now(),
286 327 }
287 328 }
@@ -489,24 +530,84 @@ mod tests {
489 530 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
490 531 }
491 532
533 fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {
534 let mut settings = Settings::default();
535 change(&mut settings.account);
536 settings
537 }
538
539 fn toasts(settings: &Settings, incoming: &Incoming) -> bool {
540 decide(settings, incoming, Environment::default()).toast
541 }
542
543 fn mention(mut incoming: Incoming) -> Incoming {
544 incoming.mentions_me = true;
545 incoming
546 }
547
492 548 #[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);
549 fn chat_message_notifications_off_keeps_personal_mentions() {
550 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
551 assert!(!toasts(&settings, &group()));
552 assert!(!toasts(&settings, &incoming(ChatKind::Direct)));
553 assert!(toasts(&settings, &mention(group())));
554 }
555
556 #[test]
557 fn personal_mentions_only_in_activity_give_no_banner() {
558 let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);
559 assert!(!toasts(&settings, &mention(group())));
560 assert!(!toasts(&settings, &mention(channel())));
561 assert!(toasts(&settings, &group()));
562 }
563
564 #[test]
565 fn mentions_and_replies_preset_drops_plain_channel_posts() {
566 let settings =
567 with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);
568 let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
569 assert!(!toasts(&settings, &post));
570 post.signals.in_my_thread = true;
571 assert!(toasts(&settings, &post));
572 assert!(toasts(&settings, &mention(channel())));
573 assert!(toasts(&settings, &group()));
574 }
575
576 fn meeting_chat(participated: bool) -> Incoming {
577 let mut message = group();
578 message.chat.meeting = true;
579 message.chat.participated = participated;
580 message
581 }
582
583 #[test]
584 fn meeting_chats_stay_quiet_until_i_take_part() {
585 let settings = Settings::default();
586 assert!(!toasts(&settings, &meeting_chat(false)));
587 assert!(toasts(&settings, &meeting_chat(true)));
588 assert!(toasts(&settings, &mention(meeting_chat(false))));
589 }
590
591 #[test]
592 fn meeting_chat_mute_and_unmute() {
593 let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);
594 assert!(!toasts(&muted, &meeting_chat(true)));
595 assert!(toasts(&muted, &mention(meeting_chat(true))));
596 let unmuted =
597 with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);
598 assert!(toasts(&unmuted, &meeting_chat(false)));
599 }
600
601 #[test]
602 fn per_chat_desktop_preference_overrides_the_account() {
603 let mut silenced = group();
604 silenced.chat.desktop = DesktopNotifications::Off;
605 assert!(!toasts(&Settings::default(), &silenced));
606 assert!(!toasts(&Settings::default(), &mention(silenced)));
607 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
608 let mut selected = group();
609 selected.chat.desktop = DesktopNotifications::On;
610 assert!(toasts(&settings, &selected));
510 611 }
511 612
512 613 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
@@ -4,6 +4,9 @@ use std::time::{Duration, Instant};
4use calling::Progress;
4use calling::Progress;
5use chrono::{DateTime, Utc};
5use chrono::{DateTime, Utc};
6use store::{ChannelNotificationLevel, ChannelNotifications};
6use store::{ChannelNotificationLevel, ChannelNotifications};
7use teams_core::{
8 DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
9};
7
10
8use super::sound_settings::SoundSettings;
11use super::sound_settings::SoundSettings;
9use super::sounds::Ringtone;
12use super::sounds::Ringtone;
@@ -69,8 +72,7 @@ impl Corner {
69
72
70#[derive(Debug, Clone, PartialEq, Eq)]
73#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Settings {
74pub 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 {
82impl Default for Settings {
84impl 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)]
121pub 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)]
120pub struct Incoming {
128pub struct Incoming {
121 pub conversation_id: String,
129 pub conversation_id: String,
@@ -128,6 +136,7 @@ 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>,
132}
141}
133
142
@@ -201,6 +210,36 @@ fn channel_toasts(incoming: &Incoming) -> bool {
201 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
210 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
202}
211}
203
212
213fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {
214 if matches!(incoming.kind, ChatKind::Channel { .. }) {
215 return if incoming.mentions_me {
216 account.personal_mentions.shows_banner()
217 } else {
218 account.preset != NotificationPreset::MentionsAndReplies
219 || incoming.signals.in_my_thread
220 };
221 }
222 let chat = incoming.chat;
223 if chat.desktop == DesktopNotifications::Off {
224 return false;
225 }
226 if incoming.mentions_me {
227 return account.personal_mentions.shows_banner();
228 }
229 let meeting_muted = chat.meeting
230 && match account.meeting_chats {
231 MeetingChatNotifications::Mute => true,
232 MeetingChatNotifications::MuteUntilJoin => !chat.participated,
233 MeetingChatNotifications::Unmute => false,
234 };
235 !meeting_muted
236 && (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())
237}
238
239pub fn shows_preview(settings: &Settings) -> bool {
240 settings.account.show_preview
241}
242
204const SILENT: Decision = Decision {
243const SILENT: Decision = Decision {
205 toast: false,
244 toast: false,
206 sound: false,
245 sound: false,
@@ -214,7 +253,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
214 || environment.own_do_not_disturb
253 || environment.own_do_not_disturb
215 || settings.do_not_disturb
254 || settings.do_not_disturb
216 || (settings.mute_in_calls && environment.in_call)
255 || (settings.mute_in_calls && environment.in_call)
217 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct());
256 || !account_toasts(&settings.account, incoming);
218 if suppressed {
257 if suppressed {
219 return SILENT;
258 return SILENT;
220 }
259 }
@@ -267,6 +306,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)
267#[cfg(test)]
306#[cfg(test)]
268mod tests {
307mod tests {
269 use calling::{CallState, EndReason};
308 use calling::{CallState, EndReason};
309 use teams_core::ActivityAlert;
270
310
271 use super::*;
311 use super::*;
272
312
@@ -282,6 +322,7 @@ mod tests {
282 mentions_me: false,
322 mentions_me: false,
283 muted: false,
323 muted: false,
284 signals: ChannelSignals::default(),
324 signals: ChannelSignals::default(),
325 chat: ChatSignals::default(),
285 created_at: Utc::now(),
326 created_at: Utc::now(),
286 }
327 }
287 }
328 }
@@ -489,24 +530,84 @@ mod tests {
489 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
530 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
490 }
531 }
491
532
533 fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {
534 let mut settings = Settings::default();
535 change(&mut settings.account);
536 settings
537 }
538
539 fn toasts(settings: &Settings, incoming: &Incoming) -> bool {
540 decide(settings, incoming, Environment::default()).toast
541 }
542
543 fn mention(mut incoming: Incoming) -> Incoming {
544 incoming.mentions_me = true;
545 incoming
546 }
547
492 #[test]
548 #[test]
493 fn mentions_only_keeps_direct_and_mentions() {
549 fn chat_message_notifications_off_keeps_personal_mentions() {
494 let settings = Settings {
550 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
495 mentions_only: true,
551 assert!(!toasts(&settings, &group()));
496 ..Default::default()
552 assert!(!toasts(&settings, &incoming(ChatKind::Direct)));
497 };
553 assert!(toasts(&settings, &mention(group())));
498 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
554 }
499 assert!(
555
500 decide(
556 #[test]
501 &settings,
557 fn personal_mentions_only_in_activity_give_no_banner() {
502 &incoming(ChatKind::Direct),
558 let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);
503 Environment::default()
559 assert!(!toasts(&settings, &mention(group())));
504 )
560 assert!(!toasts(&settings, &mention(channel())));
505 .toast
561 assert!(toasts(&settings, &group()));
506 );
562 }
507 let mut mention = group();
563
508 mention.mentions_me = true;
564 #[test]
509 assert!(decide(&settings, &mention, Environment::default()).toast);
565 fn mentions_and_replies_preset_drops_plain_channel_posts() {
566 let settings =
567 with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);
568 let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
569 assert!(!toasts(&settings, &post));
570 post.signals.in_my_thread = true;
571 assert!(toasts(&settings, &post));
572 assert!(toasts(&settings, &mention(channel())));
573 assert!(toasts(&settings, &group()));
574 }
575
576 fn meeting_chat(participated: bool) -> Incoming {
577 let mut message = group();
578 message.chat.meeting = true;
579 message.chat.participated = participated;
580 message
581 }
582
583 #[test]
584 fn meeting_chats_stay_quiet_until_i_take_part() {
585 let settings = Settings::default();
586 assert!(!toasts(&settings, &meeting_chat(false)));
587 assert!(toasts(&settings, &meeting_chat(true)));
588 assert!(toasts(&settings, &mention(meeting_chat(false))));
589 }
590
591 #[test]
592 fn meeting_chat_mute_and_unmute() {
593 let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);
594 assert!(!toasts(&muted, &meeting_chat(true)));
595 assert!(toasts(&muted, &mention(meeting_chat(true))));
596 let unmuted =
597 with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);
598 assert!(toasts(&unmuted, &meeting_chat(false)));
599 }
600
601 #[test]
602 fn per_chat_desktop_preference_overrides_the_account() {
603 let mut silenced = group();
604 silenced.chat.desktop = DesktopNotifications::Off;
605 assert!(!toasts(&Settings::default(), &silenced));
606 assert!(!toasts(&Settings::default(), &mention(silenced)));
607 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
608 let mut selected = group();
609 selected.chat.desktop = DesktopNotifications::On;
610 assert!(toasts(&settings, &selected));
510 }
611 }
511
612
512 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
613 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
crates/app-state/src/notify/settings.rs +34 −14
@@ -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 @@
1use store::Store;
1use store::Store;
2
2
3use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
4use super::rules::{Corner, Settings};
3use super::rules::{Corner, Settings};
4use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
5
5
6const META_KEY: &str = "notifications.settings";
6const META_KEY: &str = "notifications.settings";
7const RINGTONE_PREFIX: &str = "ringtone.";
7const 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]
crates/app-state/src/notify/stack.rs +1 −0
@@ -422,6 +422,7 @@ mod tests {
422 422 mentions_me: mention,
423 423 muted: false,
424 424 signals: Default::default(),
425 chat: Default::default(),
425 426 created_at: chrono::Utc::now(),
426 427 }
427 428 }
@@ -422,6 +422,7 @@ mod tests {
422 mentions_me: mention,
422 mentions_me: mention,
423 muted: false,
423 muted: false,
424 signals: Default::default(),
424 signals: Default::default(),
425 chat: Default::default(),
425 created_at: chrono::Utc::now(),
426 created_at: chrono::Utc::now(),
426 }
427 }
427 }
428 }
crates/app-ui-kit/src/settings_controls.rs +1 −0
@@ -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>) -> imp
132 )
132 )
133 })
133 })
134 })
134 })
135 .listbox()
135}
136}
136
137
137pub fn link_dropdown(
138pub fn link_dropdown(
crates/app-ui-kit/src/widgets.rs +103 −13
@@ -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
26pub fn menu_icon(name: IconName) -> Icon {
27 Icon::new(name)
28}
29
26pub fn symbol(name: &str, size: f32, color: Hsla) -> Icon {
30pub 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
47pub fn count_badge(count: u32, muted: bool) -> Div {
51#[derive(Clone, Copy)]
48 let (background, foreground) = if muted {
52pub 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
58pub const COUNT_BADGE: BadgeMetrics = BadgeMetrics {
59 height: 18.,
60 padding_x: 5.,
61 font_size: 11.,
62};
63
64pub const RAIL_BADGE: BadgeMetrics = BadgeMetrics {
65 height: 16.,
66 padding_x: 4.,
67 font_size: 10.,
68};
69
70pub fn badge_selector(text: &str) -> String {
71 format!("count-badge/{text}")
72}
73
74pub fn badge_text_selector(text: &str) -> String {
75 format!("count-badge/{text}/text")
76}
77
78pub 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)]
103struct BadgeText {
104 text: String,
105 font_size: f32,
106 line_height: f32,
107}
108
109impl 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
123pub 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
151pub 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
70pub fn page_header(title: &str) -> Div {
160pub fn page_header(title: &str) -> Div {
crates/app/src/layout_guard.rs +358 −5
@@ -171,6 +171,7 @@ 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;
@@ -189,7 +190,7 @@ mod frames {
189 190 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 191 };
191 192 use crate::views::message_row::BUBBLE_TAGS;
192 use crate::views::pin_banner::PIN_BANNER_TAG;
193 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
193 194 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
194 195 use crate::views::reaction_proposal_pill::REACTION_PILL;
195 196 use crate::views::recap_tab::RECAP_REGION;
@@ -201,10 +202,24 @@ mod frames {
201 202 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
202 203 };
203 204 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
205 use crate::views::sidebar::chat_row_selector;
204 206 use crate::views::sidebar::chat_filter_bar::{
205 207 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
206 208 };
207 209 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
210 use crate::views::widgets::{
211 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
212 count_badge,
213 };
214 use gpui_kit::MouseButton;
215 use gpui_kit::component::fluent::{
216 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
217 OPTION_CHECK_INSET,
218 };
219 use gpui_kit::component::menu::selectors::{
220 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
221 label_selector as menu_label_selector,
222 };
208 223
209 224 const GUARDED: &[&str] = &[
210 225 "shell",
@@ -1481,6 +1496,343 @@ mod frames {
1481 1496 }
1482 1497 }
1483 1498
1499 const MENU_ITEMS_SCANNED: usize = 40;
1500 const MENU_CHAT: &str = "demo-chat-release";
1501 const THEME_SELECT: &str = "settings-theme";
1502
1503 struct MenuRow {
1504 index: usize,
1505 item: Bounds<Pixels>,
1506 icon: Option<Bounds<Pixels>>,
1507 label: Option<Bounds<Pixels>>,
1508 }
1509
1510 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1511 (0..MENU_ITEMS_SCANNED)
1512 .filter_map(|index| {
1513 let item =
1514 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1515 Some(MenuRow {
1516 index,
1517 item,
1518 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1519 label: visual
1520 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1521 })
1522 })
1523 .collect()
1524 }
1525
1526 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1527 let mut found = Vec::new();
1528 for row in rows {
1529 let Some(icon) = row.icon else {
1530 continue;
1531 };
1532 let key = format!("{MENU}/item-{}", row.index);
1533 if let Some(label) = row.label {
1534 let gap = f32::from(label.left() - icon.right());
1535 if (gap - expected_gap).abs() > TOLERANCE {
1536 found.push((
1537 format!("{key}:icon-gap"),
1538 format!(
1539 "icon {} to label {} is {gap} px, expected {expected_gap}",
1540 describe(icon),
1541 describe(label)
1542 ),
1543 ));
1544 }
1545 }
1546 let offset = f32::from(icon.center().y - row.item.center().y);
1547 if offset.abs() > TOLERANCE {
1548 found.push((
1549 format!("{key}:icon-off-centre"),
1550 format!(
1551 "icon {} sits {offset} px off the centre of item {}",
1552 describe(icon),
1553 describe(row.item)
1554 ),
1555 ));
1556 }
1557 }
1558 found
1559 }
1560
1561 fn listbox_violations(
1562 trigger: Bounds<Pixels>,
1563 menu: Bounds<Pixels>,
1564 items: Bounds<Pixels>,
1565 rows: &[MenuRow],
1566 ) -> Vec<(String, String)> {
1567 let mut found = Vec::new();
1568 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1569 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1570 found.push((
1571 format!("{MENU}:not-aligned-to-trigger"),
1572 format!(
1573 "list {} must start at the trigger's left edge {}",
1574 describe(menu),
1575 describe(trigger)
1576 ),
1577 ));
1578 }
1579 if !near(
1580 f32::from(menu.top() - trigger.bottom()),
1581 f32::from(DROPDOWN_OFFSET),
1582 ) {
1583 found.push((
1584 format!("{MENU}:trigger-offset"),
1585 format!(
1586 "list {} must open {} px below the trigger {}",
1587 describe(menu),
1588 f32::from(DROPDOWN_OFFSET),
1589 describe(trigger)
1590 ),
1591 ));
1592 }
1593 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1594 found.push((
1595 format!("{MENU}:narrower-than-trigger"),
1596 format!(
1597 "list {} is narrower than the trigger {}",
1598 describe(menu),
1599 describe(trigger)
1600 ),
1601 ));
1602 }
1603 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1604 let top = f32::from(first.item.top() - items.top());
1605 let bottom = f32::from(items.bottom() - last.item.bottom());
1606 let padding = f32::from(MENU_LIST_PADDING);
1607 if !near(top, padding) || !near(bottom, padding) {
1608 found.push((
1609 format!("{MENU}:uneven-padding"),
1610 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1611 ));
1612 }
1613 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1614 match first.icon {
1615 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1616 check => found.push((
1617 format!("{MENU}:check-inset"),
1618 format!(
1619 "check column {check:?} must start {expected_inset} px inside the list {}",
1620 describe(menu)
1621 ),
1622 )),
1623 }
1624 }
1625 found
1626 }
1627
1628 #[test]
1629 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1630 let row =
1631 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1632 index,
1633 item: rectangle(4., item_top, 120., 32.),
1634 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1635 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1636 };
1637 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1638 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1639 .into_iter()
1640 .map(|(key, _)| key)
1641 .collect();
1642 assert_eq!(
1643 keys,
1644 [
1645 "popup-menu/item-1:icon-gap",
1646 "popup-menu/item-1:icon-off-centre"
1647 ]
1648 );
1649
1650 let trigger = rectangle(100., 50., 216., 32.);
1651 let option = |index: usize, top: f32| MenuRow {
1652 index,
1653 item: rectangle(104., top, 208., 32.),
1654 icon: Some(rectangle(110., top + 8., 16., 16.)),
1655 label: Some(rectangle(132., top + 6., 80., 20.)),
1656 };
1657 let aligned = [option(0, 88.), option(1, 122.)];
1658 let menu = rectangle(100., 84., 216., 74.);
1659 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1660 let shifted = rectangle(96., 90., 200., 80.);
1661 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1662 .into_iter()
1663 .map(|(key, _)| key)
1664 .collect();
1665 assert_eq!(
1666 keys,
1667 [
1668 "popup-menu:not-aligned-to-trigger",
1669 "popup-menu:trigger-offset",
1670 "popup-menu:narrower-than-trigger",
1671 "popup-menu:uneven-padding",
1672 "popup-menu:check-inset",
1673 ]
1674 );
1675 }
1676
1677 #[gpui_kit::test]
1678 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1679 let (handle, _) = mount(cx);
1680 let mut visual = VisualTestContext::from_window(handle, cx);
1681 visual.simulate_resize(size(px(1280.), px(800.)));
1682 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1683 collect(&mut visual, Some(chat_row));
1684 let mut found = Vec::new();
1685 let own_status = visual
1686 .debug_bounds(OWN_STATUS)
1687 .expect("own status button rendered");
1688 visual.simulate_click(own_status.center(), Default::default());
1689 collect(&mut visual, Some(MENU));
1690 let status_rows = menu_rows(&mut visual);
1691 assert!(
1692 status_rows.iter().any(|row| row.icon.is_some()),
1693 "status menu shows icons"
1694 );
1695 found.extend(menu_row_violations(
1696 &status_rows,
1697 f32::from(MENU_ICON_LABEL_GAP),
1698 ));
1699 visual.simulate_keystrokes("escape");
1700 collect(&mut visual, None);
1701 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1702 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1703 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1704 collect(&mut visual, Some(MENU));
1705 let chat_rows = menu_rows(&mut visual);
1706 assert!(
1707 chat_rows.iter().any(|row| row.icon.is_some()),
1708 "chat menu shows icons"
1709 );
1710 found.extend(menu_row_violations(
1711 &chat_rows,
1712 f32::from(MENU_ICON_LABEL_GAP),
1713 ));
1714 let found: Vec<String> = found
1715 .into_iter()
1716 .map(|(key, message)| format!("{key}: {message}"))
1717 .collect();
1718 assert!(found.is_empty(), "{}", found.join("\n"));
1719 }
1720
1721 #[gpui_kit::test]
1722 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1723 let (handle, state) = mount(cx);
1724 let mut visual = VisualTestContext::from_window(handle, cx);
1725 visual.simulate_resize(size(px(1280.), px(800.)));
1726 visual.update(|_, cx| {
1727 state.update(cx, |state, cx| {
1728 state.open_settings(SettingsSection::Appearance, cx)
1729 })
1730 });
1731 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1732 collect(&mut visual, Some(select));
1733 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1734 visual.simulate_click(trigger.center(), Default::default());
1735 collect(&mut visual, Some(MENU));
1736 let menu = visual.debug_bounds(MENU).expect("list rendered");
1737 let items = visual
1738 .debug_bounds(ITEMS_SELECTOR)
1739 .expect("list items rendered");
1740 let rows = menu_rows(&mut visual);
1741 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1742 .into_iter()
1743 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1744 .map(|(key, message)| format!("{key}: {message}"))
1745 .collect();
1746 assert!(found.is_empty(), "{}", found.join("\n"));
1747 }
1748
1749 const BADGE_SAMPLES: [(u32, bool); 5] =
1750 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1751
1752 struct BadgeSamples;
1753
1754 impl gpui_kit::Render for BadgeSamples {
1755 fn render(
1756 &mut self,
1757 _: &mut gpui_kit::Window,
1758 _: &mut gpui_kit::Context<Self>,
1759 ) -> impl gpui_kit::IntoElement {
1760 use gpui_kit::{ParentElement as _, Styled as _};
1761 gpui_kit::div()
1762 .flex()
1763 .gap(px(12.))
1764 .p(px(12.))
1765 .children(BADGE_SAMPLES.map(|(count, rail)| {
1766 if rail {
1767 badge_pill(
1768 count,
1769 RAIL_BADGE,
1770 crate::theme::accent(),
1771 crate::theme::on_accent(),
1772 )
1773 } else {
1774 count_badge(count, false)
1775 }
1776 }))
1777 }
1778 }
1779
1780 fn badge_violation(
1781 text: &str,
1782 pill: Bounds<Pixels>,
1783 label: Bounds<Pixels>,
1784 ink_offset: (f32, f32),
1785 ) -> Option<(String, String)> {
1786 let ink_x = f32::from(label.center().x) + ink_offset.0;
1787 let ink_y = f32::from(label.center().y) + ink_offset.1;
1788 let off_x = ink_x - f32::from(pill.center().x);
1789 let off_y = ink_y - f32::from(pill.center().y);
1790 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1791 (
1792 format!("count-badge/{text}:off-centre"),
1793 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1794 )
1795 })
1796 }
1797
1798 #[test]
1799 fn badge_rule_flags_off_centre_text() {
1800 let pill = rectangle(0., 0., 18., 18.);
1801 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1802 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1803 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1804 }
1805
1806 #[gpui_kit::test]
1807 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1808 cx.update(gpui_kit::init);
1809 cx.update(crate::theme::apply);
1810 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1811 collect(visual, None);
1812 let mut found = Vec::new();
1813 for (count, rail) in BADGE_SAMPLES {
1814 let text = crate::format::badge_text(count);
1815 let pill = visual
1816 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1817 .expect("badge rendered");
1818 let label = visual
1819 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1820 .expect("badge text rendered");
1821 let font_size = if rail {
1822 RAIL_BADGE.font_size
1823 } else {
1824 COUNT_BADGE.font_size
1825 };
1826 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1827 found.extend(badge_violation(&text, pill, label, offset));
1828 }
1829 let found: Vec<String> = found
1830 .into_iter()
1831 .map(|(key, message)| format!("{key}: {message}"))
1832 .collect();
1833 assert!(found.is_empty(), "{}", found.join("\n"));
1834 }
1835
1484 1836 const PINNED_CHAT: &str = "demo-chat-release";
1485 1837 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1486 1838
@@ -1507,12 +1859,13 @@ mod frames {
1507 1859 ("below divider", f32::from(banner.top() - divider.bottom())),
1508 1860 ];
1509 1861 let side = gaps[1].1;
1510 if gaps
1511 .iter()
1512 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1862 if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1863 || gaps
1864 .iter()
1865 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1513 1866 {
1514 1867 found.push(format!(
1515 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1868 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1516 1869 ));
1517 1870 }
1518 1871 }
@@ -171,6 +171,7 @@ 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;
@@ -189,7 +190,7 @@ mod frames {
189 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 };
191 };
191 use crate::views::message_row::BUBBLE_TAGS;
192 use crate::views::message_row::BUBBLE_TAGS;
192 use crate::views::pin_banner::PIN_BANNER_TAG;
193 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
193 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
194 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
194 use crate::views::reaction_proposal_pill::REACTION_PILL;
195 use crate::views::reaction_proposal_pill::REACTION_PILL;
195 use crate::views::recap_tab::RECAP_REGION;
196 use crate::views::recap_tab::RECAP_REGION;
@@ -201,10 +202,24 @@ mod frames {
201 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
202 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
202 };
203 };
203 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
204 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
205 use crate::views::sidebar::chat_row_selector;
204 use crate::views::sidebar::chat_filter_bar::{
206 use crate::views::sidebar::chat_filter_bar::{
205 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
207 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
206 };
208 };
207 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
209 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
210 use crate::views::widgets::{
211 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
212 count_badge,
213 };
214 use gpui_kit::MouseButton;
215 use gpui_kit::component::fluent::{
216 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
217 OPTION_CHECK_INSET,
218 };
219 use gpui_kit::component::menu::selectors::{
220 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
221 label_selector as menu_label_selector,
222 };
208
223
209 const GUARDED: &[&str] = &[
224 const GUARDED: &[&str] = &[
210 "shell",
225 "shell",
@@ -1481,6 +1496,343 @@ mod frames {
1481 }
1496 }
1482 }
1497 }
1483
1498
1499 const MENU_ITEMS_SCANNED: usize = 40;
1500 const MENU_CHAT: &str = "demo-chat-release";
1501 const THEME_SELECT: &str = "settings-theme";
1502
1503 struct MenuRow {
1504 index: usize,
1505 item: Bounds<Pixels>,
1506 icon: Option<Bounds<Pixels>>,
1507 label: Option<Bounds<Pixels>>,
1508 }
1509
1510 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1511 (0..MENU_ITEMS_SCANNED)
1512 .filter_map(|index| {
1513 let item =
1514 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1515 Some(MenuRow {
1516 index,
1517 item,
1518 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1519 label: visual
1520 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1521 })
1522 })
1523 .collect()
1524 }
1525
1526 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1527 let mut found = Vec::new();
1528 for row in rows {
1529 let Some(icon) = row.icon else {
1530 continue;
1531 };
1532 let key = format!("{MENU}/item-{}", row.index);
1533 if let Some(label) = row.label {
1534 let gap = f32::from(label.left() - icon.right());
1535 if (gap - expected_gap).abs() > TOLERANCE {
1536 found.push((
1537 format!("{key}:icon-gap"),
1538 format!(
1539 "icon {} to label {} is {gap} px, expected {expected_gap}",
1540 describe(icon),
1541 describe(label)
1542 ),
1543 ));
1544 }
1545 }
1546 let offset = f32::from(icon.center().y - row.item.center().y);
1547 if offset.abs() > TOLERANCE {
1548 found.push((
1549 format!("{key}:icon-off-centre"),
1550 format!(
1551 "icon {} sits {offset} px off the centre of item {}",
1552 describe(icon),
1553 describe(row.item)
1554 ),
1555 ));
1556 }
1557 }
1558 found
1559 }
1560
1561 fn listbox_violations(
1562 trigger: Bounds<Pixels>,
1563 menu: Bounds<Pixels>,
1564 items: Bounds<Pixels>,
1565 rows: &[MenuRow],
1566 ) -> Vec<(String, String)> {
1567 let mut found = Vec::new();
1568 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1569 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1570 found.push((
1571 format!("{MENU}:not-aligned-to-trigger"),
1572 format!(
1573 "list {} must start at the trigger's left edge {}",
1574 describe(menu),
1575 describe(trigger)
1576 ),
1577 ));
1578 }
1579 if !near(
1580 f32::from(menu.top() - trigger.bottom()),
1581 f32::from(DROPDOWN_OFFSET),
1582 ) {
1583 found.push((
1584 format!("{MENU}:trigger-offset"),
1585 format!(
1586 "list {} must open {} px below the trigger {}",
1587 describe(menu),
1588 f32::from(DROPDOWN_OFFSET),
1589 describe(trigger)
1590 ),
1591 ));
1592 }
1593 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1594 found.push((
1595 format!("{MENU}:narrower-than-trigger"),
1596 format!(
1597 "list {} is narrower than the trigger {}",
1598 describe(menu),
1599 describe(trigger)
1600 ),
1601 ));
1602 }
1603 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1604 let top = f32::from(first.item.top() - items.top());
1605 let bottom = f32::from(items.bottom() - last.item.bottom());
1606 let padding = f32::from(MENU_LIST_PADDING);
1607 if !near(top, padding) || !near(bottom, padding) {
1608 found.push((
1609 format!("{MENU}:uneven-padding"),
1610 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1611 ));
1612 }
1613 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1614 match first.icon {
1615 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1616 check => found.push((
1617 format!("{MENU}:check-inset"),
1618 format!(
1619 "check column {check:?} must start {expected_inset} px inside the list {}",
1620 describe(menu)
1621 ),
1622 )),
1623 }
1624 }
1625 found
1626 }
1627
1628 #[test]
1629 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1630 let row =
1631 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1632 index,
1633 item: rectangle(4., item_top, 120., 32.),
1634 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1635 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1636 };
1637 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1638 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1639 .into_iter()
1640 .map(|(key, _)| key)
1641 .collect();
1642 assert_eq!(
1643 keys,
1644 [
1645 "popup-menu/item-1:icon-gap",
1646 "popup-menu/item-1:icon-off-centre"
1647 ]
1648 );
1649
1650 let trigger = rectangle(100., 50., 216., 32.);
1651 let option = |index: usize, top: f32| MenuRow {
1652 index,
1653 item: rectangle(104., top, 208., 32.),
1654 icon: Some(rectangle(110., top + 8., 16., 16.)),
1655 label: Some(rectangle(132., top + 6., 80., 20.)),
1656 };
1657 let aligned = [option(0, 88.), option(1, 122.)];
1658 let menu = rectangle(100., 84., 216., 74.);
1659 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1660 let shifted = rectangle(96., 90., 200., 80.);
1661 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1662 .into_iter()
1663 .map(|(key, _)| key)
1664 .collect();
1665 assert_eq!(
1666 keys,
1667 [
1668 "popup-menu:not-aligned-to-trigger",
1669 "popup-menu:trigger-offset",
1670 "popup-menu:narrower-than-trigger",
1671 "popup-menu:uneven-padding",
1672 "popup-menu:check-inset",
1673 ]
1674 );
1675 }
1676
1677 #[gpui_kit::test]
1678 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1679 let (handle, _) = mount(cx);
1680 let mut visual = VisualTestContext::from_window(handle, cx);
1681 visual.simulate_resize(size(px(1280.), px(800.)));
1682 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1683 collect(&mut visual, Some(chat_row));
1684 let mut found = Vec::new();
1685 let own_status = visual
1686 .debug_bounds(OWN_STATUS)
1687 .expect("own status button rendered");
1688 visual.simulate_click(own_status.center(), Default::default());
1689 collect(&mut visual, Some(MENU));
1690 let status_rows = menu_rows(&mut visual);
1691 assert!(
1692 status_rows.iter().any(|row| row.icon.is_some()),
1693 "status menu shows icons"
1694 );
1695 found.extend(menu_row_violations(
1696 &status_rows,
1697 f32::from(MENU_ICON_LABEL_GAP),
1698 ));
1699 visual.simulate_keystrokes("escape");
1700 collect(&mut visual, None);
1701 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1702 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1703 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1704 collect(&mut visual, Some(MENU));
1705 let chat_rows = menu_rows(&mut visual);
1706 assert!(
1707 chat_rows.iter().any(|row| row.icon.is_some()),
1708 "chat menu shows icons"
1709 );
1710 found.extend(menu_row_violations(
1711 &chat_rows,
1712 f32::from(MENU_ICON_LABEL_GAP),
1713 ));
1714 let found: Vec<String> = found
1715 .into_iter()
1716 .map(|(key, message)| format!("{key}: {message}"))
1717 .collect();
1718 assert!(found.is_empty(), "{}", found.join("\n"));
1719 }
1720
1721 #[gpui_kit::test]
1722 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1723 let (handle, state) = mount(cx);
1724 let mut visual = VisualTestContext::from_window(handle, cx);
1725 visual.simulate_resize(size(px(1280.), px(800.)));
1726 visual.update(|_, cx| {
1727 state.update(cx, |state, cx| {
1728 state.open_settings(SettingsSection::Appearance, cx)
1729 })
1730 });
1731 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1732 collect(&mut visual, Some(select));
1733 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1734 visual.simulate_click(trigger.center(), Default::default());
1735 collect(&mut visual, Some(MENU));
1736 let menu = visual.debug_bounds(MENU).expect("list rendered");
1737 let items = visual
1738 .debug_bounds(ITEMS_SELECTOR)
1739 .expect("list items rendered");
1740 let rows = menu_rows(&mut visual);
1741 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1742 .into_iter()
1743 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1744 .map(|(key, message)| format!("{key}: {message}"))
1745 .collect();
1746 assert!(found.is_empty(), "{}", found.join("\n"));
1747 }
1748
1749 const BADGE_SAMPLES: [(u32, bool); 5] =
1750 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1751
1752 struct BadgeSamples;
1753
1754 impl gpui_kit::Render for BadgeSamples {
1755 fn render(
1756 &mut self,
1757 _: &mut gpui_kit::Window,
1758 _: &mut gpui_kit::Context<Self>,
1759 ) -> impl gpui_kit::IntoElement {
1760 use gpui_kit::{ParentElement as _, Styled as _};
1761 gpui_kit::div()
1762 .flex()
1763 .gap(px(12.))
1764 .p(px(12.))
1765 .children(BADGE_SAMPLES.map(|(count, rail)| {
1766 if rail {
1767 badge_pill(
1768 count,
1769 RAIL_BADGE,
1770 crate::theme::accent(),
1771 crate::theme::on_accent(),
1772 )
1773 } else {
1774 count_badge(count, false)
1775 }
1776 }))
1777 }
1778 }
1779
1780 fn badge_violation(
1781 text: &str,
1782 pill: Bounds<Pixels>,
1783 label: Bounds<Pixels>,
1784 ink_offset: (f32, f32),
1785 ) -> Option<(String, String)> {
1786 let ink_x = f32::from(label.center().x) + ink_offset.0;
1787 let ink_y = f32::from(label.center().y) + ink_offset.1;
1788 let off_x = ink_x - f32::from(pill.center().x);
1789 let off_y = ink_y - f32::from(pill.center().y);
1790 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1791 (
1792 format!("count-badge/{text}:off-centre"),
1793 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1794 )
1795 })
1796 }
1797
1798 #[test]
1799 fn badge_rule_flags_off_centre_text() {
1800 let pill = rectangle(0., 0., 18., 18.);
1801 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1802 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1803 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1804 }
1805
1806 #[gpui_kit::test]
1807 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1808 cx.update(gpui_kit::init);
1809 cx.update(crate::theme::apply);
1810 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1811 collect(visual, None);
1812 let mut found = Vec::new();
1813 for (count, rail) in BADGE_SAMPLES {
1814 let text = crate::format::badge_text(count);
1815 let pill = visual
1816 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1817 .expect("badge rendered");
1818 let label = visual
1819 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1820 .expect("badge text rendered");
1821 let font_size = if rail {
1822 RAIL_BADGE.font_size
1823 } else {
1824 COUNT_BADGE.font_size
1825 };
1826 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1827 found.extend(badge_violation(&text, pill, label, offset));
1828 }
1829 let found: Vec<String> = found
1830 .into_iter()
1831 .map(|(key, message)| format!("{key}: {message}"))
1832 .collect();
1833 assert!(found.is_empty(), "{}", found.join("\n"));
1834 }
1835
1484 const PINNED_CHAT: &str = "demo-chat-release";
1836 const PINNED_CHAT: &str = "demo-chat-release";
1485 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1837 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1486
1838
@@ -1507,12 +1859,13 @@ mod frames {
1507 ("below divider", f32::from(banner.top() - divider.bottom())),
1859 ("below divider", f32::from(banner.top() - divider.bottom())),
1508 ];
1860 ];
1509 let side = gaps[1].1;
1861 let side = gaps[1].1;
1510 if gaps
1862 if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1511 .iter()
1863 || gaps
1512 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1864 .iter()
1865 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1513 {
1866 {
1514 found.push(format!(
1867 found.push(format!(
1515 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1868 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1516 ));
1869 ));
1517 }
1870 }
1518 }
1871 }
crates/app/src/notify/center.rs +32 −8
@@ -13,7 +13,7 @@ use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13 13 use super::ring_view::RingView;
14 14 use super::rules::{
15 15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback, shows_preview,
17 17 };
18 18 use super::settings;
19 19 use super::sound_cache::{self, SoundHandle};
@@ -106,7 +106,8 @@ impl NotificationCenter {
106 106 window: &mut Window,
107 107 cx: &mut Context<Self>,
108 108 ) -> Self {
109 let settings = settings::load(&app.read(cx).store);
109 let mut settings = settings::load(&app.read(cx).store);
110 settings.account = app.read(cx).account_chat_settings().notifications;
110 111 let app_icon = active_appearance::current(cx).app_icon;
111 112 let tray = if app.read(cx).mode.demo {
112 113 None
@@ -272,13 +273,19 @@ impl NotificationCenter {
272 273 self.sync_tray();
273 274 if self.settings.sounds != previous {
274 275 let updated = self.settings.sounds.clone();
275 self.app
276 .update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
276 self.app.update(cx, |state, cx| {
277 state.save_sound_settings(previous, updated, cx)
278 });
277 279 self.prefetch_sounds(cx);
278 280 }
279 281 cx.notify();
280 282 }
281 283
284 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
285 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
286 cx.notify();
287 }
288
282 289 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
283 290 let Some(account) = self.app.read(cx).account_sounds.clone() else {
284 291 return;
@@ -328,6 +335,7 @@ impl NotificationCenter {
328 335 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
329 336 AppEvent::Call => self.sync_call_sounds(cx),
330 337 AppEvent::SoundSettings => self.on_account_sounds(cx),
338 AppEvent::ChatSettings => self.on_account_notifications(cx),
331 339 _ => {}
332 340 }
333 341 }
@@ -390,7 +398,11 @@ impl NotificationCenter {
390 398 .unwrap_or(false)
391 399 }
392 400
393 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
401 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
402 incoming.chat.desktop = self
403 .app
404 .read(cx)
405 .chat_desktop_notifications(&incoming.conversation_id);
394 406 let bubble_text = match &incoming.preview {
395 407 Preview::Text(text) => text.replace('\n', " "),
396 408 Preview::Image => "Sent a picture".to_owned(),
@@ -558,7 +570,9 @@ impl NotificationCenter {
558 570 .map(|toast| {
559 571 let lines = match &toast.agent {
560 572 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
561 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
573 None => {
574 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
575 }
562 576 };
563 577 layout::toast_height(toast, lines)
564 578 })
@@ -708,7 +722,12 @@ impl NotificationCenter {
708 722 let reconnecting =
709 723 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
710 724 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
711 sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
725 sync_loop(
726 &mut self.reconnecting,
727 reconnecting,
728 CallTone::Reconnecting,
729 cx,
730 );
712 731 }
713 732
714 733 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -1118,6 +1137,7 @@ impl NotificationCenter {
1118 1137 mentions_me: false,
1119 1138 muted: false,
1120 1139 signals: Default::default(),
1140 chat: Default::default(),
1121 1141 created_at: Utc::now(),
1122 1142 };
1123 1143 let decision = Decision {
@@ -1287,6 +1307,7 @@ fn demo_incoming() -> Vec<Incoming> {
1287 1307 mentions_me: mention,
1288 1308 muted: false,
1289 1309 signals: Default::default(),
1310 chat: Default::default(),
1290 1311 created_at: Utc::now(),
1291 1312 };
1292 1313 vec![
@@ -1363,7 +1384,10 @@ mod tests {
1363 1384 scale: 1.,
1364 1385 };
1365 1386 let options = popup_options(slot, area);
1366 assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1387 assert_eq!(
1388 options.window_background,
1389 WindowBackgroundAppearance::Transparent
1390 );
1367 1391 assert_eq!(options.kind, WindowKind::PopUp);
1368 1392 }
1369 1393
@@ -13,7 +13,7 @@ use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13use super::ring_view::RingView;
13use super::ring_view::RingView;
14use super::rules::{
14use super::rules::{
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
15 ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback,
16 meeting_start_sound, ringtone_for, should_flash, should_ringback, shows_preview,
17};
17};
18use super::settings;
18use super::settings;
19use super::sound_cache::{self, SoundHandle};
19use super::sound_cache::{self, SoundHandle};
@@ -106,7 +106,8 @@ impl NotificationCenter {
106 window: &mut Window,
106 window: &mut Window,
107 cx: &mut Context<Self>,
107 cx: &mut Context<Self>,
108 ) -> Self {
108 ) -> Self {
109 let settings = settings::load(&app.read(cx).store);
109 let mut settings = settings::load(&app.read(cx).store);
110 settings.account = app.read(cx).account_chat_settings().notifications;
110 let app_icon = active_appearance::current(cx).app_icon;
111 let app_icon = active_appearance::current(cx).app_icon;
111 let tray = if app.read(cx).mode.demo {
112 let tray = if app.read(cx).mode.demo {
112 None
113 None
@@ -272,13 +273,19 @@ impl NotificationCenter {
272 self.sync_tray();
273 self.sync_tray();
273 if self.settings.sounds != previous {
274 if self.settings.sounds != previous {
274 let updated = self.settings.sounds.clone();
275 let updated = self.settings.sounds.clone();
275 self.app
276 self.app.update(cx, |state, cx| {
276 .update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
277 state.save_sound_settings(previous, updated, cx)
278 });
277 self.prefetch_sounds(cx);
279 self.prefetch_sounds(cx);
278 }
280 }
279 cx.notify();
281 cx.notify();
280 }
282 }
281
283
284 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
285 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
286 cx.notify();
287 }
288
282 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
289 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
283 let Some(account) = self.app.read(cx).account_sounds.clone() else {
290 let Some(account) = self.app.read(cx).account_sounds.clone() else {
284 return;
291 return;
@@ -328,6 +335,7 @@ impl NotificationCenter {
328 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
335 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
329 AppEvent::Call => self.sync_call_sounds(cx),
336 AppEvent::Call => self.sync_call_sounds(cx),
330 AppEvent::SoundSettings => self.on_account_sounds(cx),
337 AppEvent::SoundSettings => self.on_account_sounds(cx),
338 AppEvent::ChatSettings => self.on_account_notifications(cx),
331 _ => {}
339 _ => {}
332 }
340 }
333 }
341 }
@@ -390,7 +398,11 @@ impl NotificationCenter {
390 .unwrap_or(false)
398 .unwrap_or(false)
391 }
399 }
392
400
393 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
401 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
402 incoming.chat.desktop = self
403 .app
404 .read(cx)
405 .chat_desktop_notifications(&incoming.conversation_id);
394 let bubble_text = match &incoming.preview {
406 let bubble_text = match &incoming.preview {
395 Preview::Text(text) => text.replace('\n', " "),
407 Preview::Text(text) => text.replace('\n', " "),
396 Preview::Image => "Sent a picture".to_owned(),
408 Preview::Image => "Sent a picture".to_owned(),
@@ -558,7 +570,9 @@ impl NotificationCenter {
558 .map(|toast| {
570 .map(|toast| {
559 let lines = match &toast.agent {
571 let lines = match &toast.agent {
560 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
572 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
561 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
573 None => {
574 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
575 }
562 };
576 };
563 layout::toast_height(toast, lines)
577 layout::toast_height(toast, lines)
564 })
578 })
@@ -708,7 +722,12 @@ impl NotificationCenter {
708 let reconnecting =
722 let reconnecting =
709 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
723 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
710 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
724 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
711 sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
725 sync_loop(
726 &mut self.reconnecting,
727 reconnecting,
728 CallTone::Reconnecting,
729 cx,
730 );
712 }
731 }
713
732
714 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
733 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -1118,6 +1137,7 @@ impl NotificationCenter {
1118 mentions_me: false,
1137 mentions_me: false,
1119 muted: false,
1138 muted: false,
1120 signals: Default::default(),
1139 signals: Default::default(),
1140 chat: Default::default(),
1121 created_at: Utc::now(),
1141 created_at: Utc::now(),
1122 };
1142 };
1123 let decision = Decision {
1143 let decision = Decision {
@@ -1287,6 +1307,7 @@ fn demo_incoming() -> Vec<Incoming> {
1287 mentions_me: mention,
1307 mentions_me: mention,
1288 muted: false,
1308 muted: false,
1289 signals: Default::default(),
1309 signals: Default::default(),
1310 chat: Default::default(),
1290 created_at: Utc::now(),
1311 created_at: Utc::now(),
1291 };
1312 };
1292 vec![
1313 vec![
@@ -1363,7 +1384,10 @@ mod tests {
1363 scale: 1.,
1384 scale: 1.,
1364 };
1385 };
1365 let options = popup_options(slot, area);
1386 let options = popup_options(slot, area);
1366 assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1387 assert_eq!(
1388 options.window_background,
1389 WindowBackgroundAppearance::Transparent
1390 );
1367 assert_eq!(options.kind, WindowKind::PopUp);
1391 assert_eq!(options.kind, WindowKind::PopUp);
1368 }
1392 }
1369
1393
crates/app/src/notify/toast.rs +1 −1
@@ -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();
crates/app/src/settings/account.rs added +144 −0
@@ -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 @@
1use gpui_kit::*;
2use teams_core::{
3 ActivityAlert, ChatSettingChange, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
4 NotificationPreset, UpArrowBehavior,
5};
6
7use super::rows::{Choice, control_row, select};
8use crate::app_state::AppState;
9
10pub struct Labeled<T: 'static> {
11 pub label: &'static str,
12 pub value: T,
13}
14
15const fn option<T>(label: &'static str, value: T) -> Labeled<T> {
16 Labeled { label, value }
17}
18
19pub const DENSITY: [Labeled<MessageDensity>; 2] = [
20 option("Comfy", MessageDensity::Comfy),
21 option("Compact", MessageDensity::Compact),
22];
23
24pub 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
32pub 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
41pub const PRESETS: [Labeled<NotificationPreset>; 3] = [
42 option("All activity", NotificationPreset::AllActivity),
43 option("Mentions & replies", NotificationPreset::MentionsAndReplies),
44 option("Customised", NotificationPreset::Customised),
45];
46
47pub const CHAT_MESSAGES: [Labeled<ActivityAlert>; 2] = [
48 option("Show in banner", ActivityAlert::OnlyBanner),
49 option("Off", ActivityAlert::Off),
50];
51
52pub const MENTIONS: [Labeled<ActivityAlert>; 2] = [
53 option("Show in Activity and banner", ActivityAlert::BannerAndFeed),
54 option("Show in Activity", ActivityAlert::OnlyFeed),
55];
56
57pub 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
63pub 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
72pub 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
80pub 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
90pub 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
98pub 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)]
122mod 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}
crates/app/src/settings/chats.rs +78 −20
@@ -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 @@
1use gpui_kit::component::v_flex;
1use gpui_kit::component::v_flex;
2use gpui_kit::*;
2use gpui_kit::*;
3use teams_core::ChatSection;
3use teams_core::{ChatSection, ChatSettingChange};
4
4
5use super::account::{DENSITY, ENTER_KEY, account_select};
5use super::rows::{caption, toggle_row};
6use super::rows::{caption, toggle_row};
6use crate::app_state::AppState;
7use crate::app_state::AppState;
7use crate::theme;
8use crate::theme;
8
9
10const 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.";
11const 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
9pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
13pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
10 let enabled = app
14 let state = app.read(cx);
11 .read(cx)
15 let muted_section = state.directory.section_settings.enabled(ChatSection::Muted);
12 .directory
16 let settings = state.account_chat_settings();
13 .section_settings
17 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}
crates/app/src/settings/dialog.rs +1 −1
@@ -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(),
crates/app/src/settings/general.rs +14 −1
@@ -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};
8use gpui_kit::*;
8use gpui_kit::*;
9use teams_core::TranslationBehavior;
9use teams_core::{ChatSettingChange, TranslationBehavior};
10
10
11use super::account::{UP_ARROW, account_select};
11use super::rows::{Choice, caption, control_row, select, toggle_row};
12use super::rows::{Choice, caption, control_row, select, toggle_row};
12use crate::app_state::AppState;
13use crate::app_state::AppState;
13use crate::notify::NotificationCenter;
14use 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}
crates/app/src/settings/mod.rs +2 −1
@@ -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 @@
1mod about;
1mod about;
2mod account;
2mod appearance;
3mod appearance;
3mod calls;
4mod calls;
4mod chats;
5mod chats;
@@ -15,4 +16,4 @@ pub use dialog::metrics;
15pub use dialog::{SettingsDialog, SettingsDialogEvent};
16pub use dialog::{SettingsDialog, SettingsDialogEvent};
16#[cfg(test)]
17#[cfg(test)]
17pub use nav::{item_selector, label, label_selector};
18pub use nav::{item_selector, label, label_selector};
18pub(crate) use rows::switch;
19pub(crate) use rows::{select_selector, switch};
crates/app/src/settings/notifications.rs +90 −27
@@ -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 @@
1use gpui_kit::component::{h_flex, v_flex};
1use gpui_kit::component::{h_flex, v_flex};
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use teams_core::ChatSettingChange;
5
6use super::account::{
7 ACTIVITY_OR_OFF, CHAT_MESSAGES, MEETING_CHATS, MENTIONS, PRESETS, account_select,
8 meeting_chats_detail, preset_detail,
9};
4use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
10use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11use crate::app_state::AppState;
5use crate::notify::NotificationCenter;
12use crate::notify::NotificationCenter;
6use crate::notify::rules::{Corner, Settings};
13use crate::notify::rules::{Corner, Settings};
7use crate::notify::sounds::AlertSound;
14use crate::notify::sounds::AlertSound;
@@ -17,20 +24,12 @@ struct Toggle {
17 field: Accessor,
24 field: Accessor,
18}
25}
19
26
20const APPEARANCE: [Toggle; 2] = [
27const 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
35const NOTIFICATION_SOUND: Toggle = Toggle {
34const 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
64const 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
71const HIDE_IN_CALLS: Toggle = Toggle {
63const 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
78pub fn render(center: &Entity<NotificationCenter>, cx: &App) -> Div {
70pub 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
197fn 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
150fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {
213fn 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;
crates/app/src/settings/rows.rs +8 −1
@@ -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
165pub fn select_selector(id: &str) -> String {
166 format!("settings-select/{id}")
167}
168
165pub fn select(
169pub 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}
crates/app/src/views/calls_tab.rs +3 −8
@@ -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;
13use super::new_meeting_dialog::open_new_meeting;
13use super::new_meeting_dialog::open_new_meeting;
14use super::scroll_edge::with_top_edge;
14use super::scroll_edge::with_top_edge;
15use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
15use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
16use super::widgets::icon;
16use super::widgets::{icon, menu_icon};
17use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::call::{
18use 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.;
25const VIEWPORT_MARGIN: f32 = 300.;
25const VIEWPORT_MARGIN: f32 = 300.;
26const TIME_COLUMN_WIDTH: f32 = 96.;
26const TIME_COLUMN_WIDTH: f32 = 96.;
27const AVATAR_SIZE: f32 = 36.;
27const AVATAR_SIZE: f32 = 36.;
28const MENU_ICON_SIZE: f32 = 15.;
29
28
30fn meeting_avatar() -> Div {
29fn 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)
crates/app/src/views/composer.rs +108 −40
@@ -24,9 +24,10 @@ 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
32 33 mod drafts;
@@ -120,6 +121,7 @@ pub enum ComposerEvent {
120 121 send_at: DateTime<Utc>,
121 122 },
122 123 EditLast,
124 FocusMessages,
123 125 Typing(bool),
124 126 }
125 127
@@ -230,6 +232,19 @@ pub struct Composer {
230 232
231 233 impl EventEmitter<ComposerEvent> for Composer {}
232 234
235 /// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.
236 pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {
237 behavior == EnterKeyBehavior::NewLine && !shift && !secondary
238 }
239
240 pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {
241 match behavior {
242 UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),
243 UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),
244 UpArrowBehavior::StayInCompose => None,
245 }
246 }
247
233 248 pub fn is_plain_enter(event: &InputEvent) -> bool {
234 249 matches!(event, InputEvent::PressEnter { shift: false, .. })
235 250 }
@@ -536,7 +551,10 @@ impl Composer {
536 551 return;
537 552 }
538 553 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
539 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
554 if typed.is_some()
555 && !self.app.read(cx).markdown_mode
556 && self.convert_markdown(cursor, window, cx)
557 {
540 558 return;
541 559 }
542 560 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
@@ -1706,12 +1724,15 @@ impl Composer {
1706 1724 draft.replace(range, glyph);
1707 1725 draft.take_edits();
1708 1726 }
1709 let mentions = state
1727 let mentions: Vec<MentionInput> = state
1710 1728 .tokens()
1711 1729 .iter()
1712 1730 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1713 1731 .cloned()
1714 1732 .collect();
1733 if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {
1734 draft = Draft::from_markdown(draft.text());
1735 }
1715 1736 Outgoing {
1716 1737 draft,
1717 1738 subject: None,
@@ -2426,7 +2447,10 @@ impl Composer {
2426 2447
2427 2448 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2428 2449 let composer = cx.entity().downgrade();
2429 let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();
2450 let floating = focused
2451 && self.toolbar_requested(cx)
2452 && !self.format_bar_open()
2453 && !self.app.read(cx).markdown_mode;
2430 2454 if self.link_editor.is_none() && !floating {
2431 2455 return None;
2432 2456 }
@@ -2729,36 +2753,39 @@ impl Render for Composer {
2729 2753 ))
2730 2754 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2731 2755 });
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)));
2756 let markdown_mode = self.app.read(cx).markdown_mode;
2757 let format_open = self.format_bar_open() && !markdown_mode;
2758 let format_toggle = (!markdown_mode).then(|| {
2759 div()
2760 .id("composer-format")
2761 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2762 .size(px(COMPOSER_BUTTON_SIZE))
2763 .flex_none()
2764 .flex()
2765 .items_center()
2766 .justify_center()
2767 .rounded(px(8.))
2768 .cursor_pointer()
2769 .when(format_open, |button| button.bg(theme::popup_hover()))
2770 .hover(|button| button.bg(theme::popup_hover()))
2771 .tooltip(move |window, cx| {
2772 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2773 })
2774 .child(symbol(
2775 format_toolbar::toggle_symbol(format_open),
2776 COMPOSER_ICON_SIZE,
2777 if format_open {
2778 theme::accent_soft()
2779 } else {
2780 theme::text_muted()
2781 },
2782 ))
2783 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2784 window.prevent_default();
2785 cx.stop_propagation();
2786 })
2787 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
2788 });
2762 2789 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2763 2790 let composer = cx.weak_entity();
2764 2791 let tokens_composer = composer.clone();
@@ -2979,8 +3006,12 @@ impl Render for Composer {
2979 3006 } else if this.popup_is_open() {
2980 3007 this.move_highlight(-1, cx);
2981 3008 cx.stop_propagation();
2982 } else if this.editing.is_none() && this.is_empty(cx) {
2983 cx.emit(ComposerEvent::EditLast);
3009 } else if this.editing.is_none()
3010 && this.is_empty(cx)
3011 && let Some(event) =
3012 up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3013 {
3014 cx.emit(event);
2984 3015 cx.stop_propagation();
2985 3016 }
2986 3017 }))
@@ -3026,6 +3057,19 @@ impl Render for Composer {
3026 3057 } else if this.popup_is_open() {
3027 3058 this.accept_popup(window, cx);
3028 3059 cx.stop_propagation();
3060 } else if enter_starts_line(
3061 this.app.read(cx).account_chat_settings().enter_key,
3062 action.shift,
3063 action.secondary,
3064 ) {
3065 cx.stop_propagation();
3066 window.dispatch_action(
3067 Box::new(Enter {
3068 secondary: false,
3069 shift: true,
3070 }),
3071 cx,
3072 );
3029 3073 } else if this.break_line(action.shift, window, cx) {
3030 3074 cx.stop_propagation();
3031 3075 }
@@ -3154,7 +3198,7 @@ impl Render for Composer {
3154 3198 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3155 3199 .flex_none()
3156 3200 .gap(px(COMPOSER_BUTTON_INSET))
3157 .child(format_toggle)
3201 .children(format_toggle)
3158 3202 .children(fun)
3159 3203 .children(attach),
3160 3204 )
@@ -3194,7 +3238,31 @@ impl Render for Composer {
3194 3238
3195 3239 #[cfg(test)]
3196 3240 mod tests {
3197 use super::{active_mention, submitted_text};
3241 use super::{
3242 ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,
3243 submitted_text, up_arrow_event,
3244 };
3245
3246 #[test]
3247 fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3248 assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3249 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3250 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3251 assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3252 }
3253
3254 #[test]
3255 fn up_arrow_follows_the_account_setting() {
3256 assert!(matches!(
3257 up_arrow_event(UpArrowBehavior::EditLastMessage),
3258 Some(ComposerEvent::EditLast)
3259 ));
3260 assert!(matches!(
3261 up_arrow_event(UpArrowBehavior::NavigateToMessages),
3262 Some(ComposerEvent::FocusMessages)
3263 ));
3264 assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3265 }
3198 3266 use gpui_kit::component::input::InputEvent;
3199 3267
3200 3268 fn press(shift: bool) -> InputEvent {
@@ -24,9 +24,10 @@ use gpui_kit::component::{
24use gpui_kit::prelude::FluentBuilder as _;
24use gpui_kit::prelude::FluentBuilder as _;
25use gpui_kit::*;
25use gpui_kit::*;
26use teams_core::{
26use 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
32mod drafts;
33mod drafts;
@@ -120,6 +121,7 @@ pub enum ComposerEvent {
120 send_at: DateTime<Utc>,
121 send_at: DateTime<Utc>,
121 },
122 },
122 EditLast,
123 EditLast,
124 FocusMessages,
123 Typing(bool),
125 Typing(bool),
124}
126}
125
127
@@ -230,6 +232,19 @@ pub struct Composer {
230
232
231impl EventEmitter<ComposerEvent> for Composer {}
233impl EventEmitter<ComposerEvent> for Composer {}
232
234
235/// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.
236pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {
237 behavior == EnterKeyBehavior::NewLine && !shift && !secondary
238}
239
240pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {
241 match behavior {
242 UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),
243 UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),
244 UpArrowBehavior::StayInCompose => None,
245 }
246}
247
233pub fn is_plain_enter(event: &InputEvent) -> bool {
248pub fn is_plain_enter(event: &InputEvent) -> bool {
234 matches!(event, InputEvent::PressEnter { shift: false, .. })
249 matches!(event, InputEvent::PressEnter { shift: false, .. })
235}
250}
@@ -536,7 +551,10 @@ impl Composer {
536 return;
551 return;
537 }
552 }
538 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
553 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
539 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
554 if typed.is_some()
555 && !self.app.read(cx).markdown_mode
556 && self.convert_markdown(cursor, window, cx)
557 {
540 return;
558 return;
541 }
559 }
542 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
560 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
@@ -1706,12 +1724,15 @@ impl Composer {
1706 draft.replace(range, glyph);
1724 draft.replace(range, glyph);
1707 draft.take_edits();
1725 draft.take_edits();
1708 }
1726 }
1709 let mentions = state
1727 let mentions: Vec<MentionInput> = state
1710 .tokens()
1728 .tokens()
1711 .iter()
1729 .iter()
1712 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1730 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1713 .cloned()
1731 .cloned()
1714 .collect();
1732 .collect();
1733 if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {
1734 draft = Draft::from_markdown(draft.text());
1735 }
1715 Outgoing {
1736 Outgoing {
1716 draft,
1737 draft,
1717 subject: None,
1738 subject: None,
@@ -2426,7 +2447,10 @@ impl Composer {
2426
2447
2427 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2448 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2428 let composer = cx.entity().downgrade();
2449 let composer = cx.entity().downgrade();
2429 let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();
2450 let floating = focused
2451 && self.toolbar_requested(cx)
2452 && !self.format_bar_open()
2453 && !self.app.read(cx).markdown_mode;
2430 if self.link_editor.is_none() && !floating {
2454 if self.link_editor.is_none() && !floating {
2431 return None;
2455 return None;
2432 }
2456 }
@@ -2729,36 +2753,39 @@ impl Render for Composer {
2729 ))
2753 ))
2730 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2754 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2731 });
2755 });
2732 let format_open = self.format_bar_open();
2756 let markdown_mode = self.app.read(cx).markdown_mode;
2733 let format_toggle = div()
2757 let format_open = self.format_bar_open() && !markdown_mode;
2734 .id("composer-format")
2758 let format_toggle = (!markdown_mode).then(|| {
2735 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2759 div()
2736 .size(px(COMPOSER_BUTTON_SIZE))
2760 .id("composer-format")
2737 .flex_none()
2761 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2738 .flex()
2762 .size(px(COMPOSER_BUTTON_SIZE))
2739 .items_center()
2763 .flex_none()
2740 .justify_center()
2764 .flex()
2741 .rounded(px(8.))
2765 .items_center()
2742 .cursor_pointer()
2766 .justify_center()
2743 .when(format_open, |button| button.bg(theme::popup_hover()))
2767 .rounded(px(8.))
2744 .hover(|button| button.bg(theme::popup_hover()))
2768 .cursor_pointer()
2745 .tooltip(move |window, cx| {
2769 .when(format_open, |button| button.bg(theme::popup_hover()))
2746 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2770 .hover(|button| button.bg(theme::popup_hover()))
2747 })
2771 .tooltip(move |window, cx| {
2748 .child(symbol(
2772 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2749 format_toolbar::toggle_symbol(format_open),
2773 })
2750 COMPOSER_ICON_SIZE,
2774 .child(symbol(
2751 if format_open {
2775 format_toolbar::toggle_symbol(format_open),
2752 theme::accent_soft()
2776 COMPOSER_ICON_SIZE,
2753 } else {
2777 if format_open {
2754 theme::text_muted()
2778 theme::accent_soft()
2755 },
2779 } else {
2756 ))
2780 theme::text_muted()
2757 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2781 },
2758 window.prevent_default();
2782 ))
2759 cx.stop_propagation();
2783 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2760 })
2784 window.prevent_default();
2761 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)));
2785 cx.stop_propagation();
2786 })
2787 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
2788 });
2762 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2789 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2763 let composer = cx.weak_entity();
2790 let composer = cx.weak_entity();
2764 let tokens_composer = composer.clone();
2791 let tokens_composer = composer.clone();
@@ -2979,8 +3006,12 @@ impl Render for Composer {
2979 } else if this.popup_is_open() {
3006 } else if this.popup_is_open() {
2980 this.move_highlight(-1, cx);
3007 this.move_highlight(-1, cx);
2981 cx.stop_propagation();
3008 cx.stop_propagation();
2982 } else if this.editing.is_none() && this.is_empty(cx) {
3009 } else if this.editing.is_none()
2983 cx.emit(ComposerEvent::EditLast);
3010 && this.is_empty(cx)
3011 && let Some(event) =
3012 up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3013 {
3014 cx.emit(event);
2984 cx.stop_propagation();
3015 cx.stop_propagation();
2985 }
3016 }
2986 }))
3017 }))
@@ -3026,6 +3057,19 @@ impl Render for Composer {
3026 } else if this.popup_is_open() {
3057 } else if this.popup_is_open() {
3027 this.accept_popup(window, cx);
3058 this.accept_popup(window, cx);
3028 cx.stop_propagation();
3059 cx.stop_propagation();
3060 } else if enter_starts_line(
3061 this.app.read(cx).account_chat_settings().enter_key,
3062 action.shift,
3063 action.secondary,
3064 ) {
3065 cx.stop_propagation();
3066 window.dispatch_action(
3067 Box::new(Enter {
3068 secondary: false,
3069 shift: true,
3070 }),
3071 cx,
3072 );
3029 } else if this.break_line(action.shift, window, cx) {
3073 } else if this.break_line(action.shift, window, cx) {
3030 cx.stop_propagation();
3074 cx.stop_propagation();
3031 }
3075 }
@@ -3154,7 +3198,7 @@ impl Render for Composer {
3154 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3198 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3155 .flex_none()
3199 .flex_none()
3156 .gap(px(COMPOSER_BUTTON_INSET))
3200 .gap(px(COMPOSER_BUTTON_INSET))
3157 .child(format_toggle)
3201 .children(format_toggle)
3158 .children(fun)
3202 .children(fun)
3159 .children(attach),
3203 .children(attach),
3160 )
3204 )
@@ -3194,7 +3238,31 @@ impl Render for Composer {
3194
3238
3195#[cfg(test)]
3239#[cfg(test)]
3196mod tests {
3240mod tests {
3197 use super::{active_mention, submitted_text};
3241 use super::{
3242 ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,
3243 submitted_text, up_arrow_event,
3244 };
3245
3246 #[test]
3247 fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3248 assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3249 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3250 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3251 assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3252 }
3253
3254 #[test]
3255 fn up_arrow_follows_the_account_setting() {
3256 assert!(matches!(
3257 up_arrow_event(UpArrowBehavior::EditLastMessage),
3258 Some(ComposerEvent::EditLast)
3259 ));
3260 assert!(matches!(
3261 up_arrow_event(UpArrowBehavior::NavigateToMessages),
3262 Some(ComposerEvent::FocusMessages)
3263 ));
3264 assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3265 }
3198 use gpui_kit::component::input::InputEvent;
3266 use gpui_kit::component::input::InputEvent;
3199
3267
3200 fn press(shift: bool) -> InputEvent {
3268 fn press(shift: bool) -> InputEvent {
crates/app/src/views/conversation.rs +12 −1
@@ -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};
@@ -689,7 +690,7 @@ impl ConversationView {
689 690 | AppEvent::Call => {}
690 691 AppEvent::LiveMeeting => cx.notify(),
691 692 AppEvent::Saved => cx.notify(),
692 AppEvent::Translation => self.rebuild(false, cx),
693 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
693 694 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
694 695 AppEvent::Typing => cx.notify(),
695 696 AppEvent::Scheduled => self.rebuild(false, cx),
@@ -739,6 +740,7 @@ impl ConversationView {
739 740 self.schedule((**outgoing).clone(), *send_at, window, cx)
740 741 }
741 742 ComposerEvent::EditLast => self.edit_last_own(window, cx),
743 ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
742 744 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
743 745 }
744 746 }
@@ -1892,6 +1894,15 @@ impl ConversationView {
1892 1894 }
1893 1895
1894 1896 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1897 let settings = self.app.read(cx).account_chat_settings();
1898 let mut receipts = self.raw_receipts(records, cx);
1899 for receipt in receipts.values_mut() {
1900 *receipt = shown_receipt(&settings, *receipt);
1901 }
1902 receipts
1903 }
1904
1905 fn raw_receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1895 1906 let state = self.app.read(cx);
1896 1907 if state.mode.demo {
1897 1908 let read_ids = crate::demo::read_message_ids(records);
@@ -65,6 +65,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
65use crate::backend::Engine;
65use crate::backend::Engine;
66use crate::card_state::CardScope;
66use crate::card_state::CardScope;
67use crate::channel_files::DownloadSource;
67use crate::channel_files::DownloadSource;
68use crate::chat_settings_actions::shown_receipt;
68use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
69use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
69use crate::demo_library::DemoLibrary;
70use crate::demo_library::DemoLibrary;
70use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
71use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
@@ -689,7 +690,7 @@ impl ConversationView {
689 | AppEvent::Call => {}
690 | AppEvent::Call => {}
690 AppEvent::LiveMeeting => cx.notify(),
691 AppEvent::LiveMeeting => cx.notify(),
691 AppEvent::Saved => cx.notify(),
692 AppEvent::Saved => cx.notify(),
692 AppEvent::Translation => self.rebuild(false, cx),
693 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
693 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
694 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
694 AppEvent::Typing => cx.notify(),
695 AppEvent::Typing => cx.notify(),
695 AppEvent::Scheduled => self.rebuild(false, cx),
696 AppEvent::Scheduled => self.rebuild(false, cx),
@@ -739,6 +740,7 @@ impl ConversationView {
739 self.schedule((**outgoing).clone(), *send_at, window, cx)
740 self.schedule((**outgoing).clone(), *send_at, window, cx)
740 }
741 }
741 ComposerEvent::EditLast => self.edit_last_own(window, cx),
742 ComposerEvent::EditLast => self.edit_last_own(window, cx),
743 ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
742 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
744 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
743 }
745 }
744 }
746 }
@@ -1892,6 +1894,15 @@ impl ConversationView {
1892 }
1894 }
1893
1895
1894 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1896 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1897 let settings = self.app.read(cx).account_chat_settings();
1898 let mut receipts = self.raw_receipts(records, cx);
1899 for receipt in receipts.values_mut() {
1900 *receipt = shown_receipt(&settings, *receipt);
1901 }
1902 receipts
1903 }
1904
1905 fn raw_receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1895 let state = self.app.read(cx);
1906 let state = self.app.read(cx);
1896 if state.mode.demo {
1907 if state.mode.demo {
1897 let read_ids = crate::demo::read_message_ids(records);
1908 let read_ids = crate::demo::read_message_ids(records);
crates/app/src/views/conversation/feed.rs +3 −1
@@ -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::EditLast
195 | ComposerEvent::FocusMessages => {}
194 }
196 }
195 }
197 }
196
198
crates/app/src/views/conversation/render_env.rs +2 −0
@@ -314,6 +314,8 @@ impl RenderEnv {
314 314 call: self.call_actions(message, cx),
315 315 reaction_proposal,
316 316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
317 compact: self.app.read(cx).account_chat_settings().message_density
318 == teams_core::MessageDensity::Compact,
317 319 }
318 320 }
319 321
@@ -314,6 +314,8 @@ impl RenderEnv {
314 call: self.call_actions(message, cx),
314 call: self.call_actions(message, cx),
315 reaction_proposal,
315 reaction_proposal,
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
316 undo_delete: self.undo_delete_action(message, is_real, view, cx),
317 compact: self.app.read(cx).account_chat_settings().message_density
318 == teams_core::MessageDensity::Compact,
317 }
319 }
318 }
320 }
319
321
crates/app/src/views/image_menu.rs +2 −12
@@ -2,26 +2,16 @@ use std::path::PathBuf;
2 2 use std::rc::Rc;
3 3
4 4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{
6 Icon,
7 menu::{ContextMenuExt as _, PopupMenuItem},
8 };
5 use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
9 6 use gpui_kit::*;
10 7
11 8 use super::image_viewer::{suggested_name, write_image};
12 use super::widgets::icon;
9 use super::widgets::menu_icon;
13 10 use crate::downloads;
14 11 use crate::image_clipboard::ClipboardImage;
15 use crate::theme;
16
17 const MENU_ICON_SIZE: f32 = 16.;
18 12
19 13 pub type ImageShare = Rc<dyn Fn(&mut App)>;
20 14
21 fn menu_icon(glyph: IconName) -> Icon {
22 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
23 }
24
25 15 pub fn copy_image_file(path: PathBuf, cx: &mut App) {
26 16 cx.spawn(async move |cx| {
27 17 let image = cx
@@ -2,26 +2,16 @@ use std::path::PathBuf;
2use std::rc::Rc;
2use std::rc::Rc;
3
3
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6 Icon,
7 menu::{ContextMenuExt as _, PopupMenuItem},
8};
9use gpui_kit::*;
6use gpui_kit::*;
10
7
11use super::image_viewer::{suggested_name, write_image};
8use super::image_viewer::{suggested_name, write_image};
12use super::widgets::icon;
9use super::widgets::menu_icon;
13use crate::downloads;
10use crate::downloads;
14use crate::image_clipboard::ClipboardImage;
11use crate::image_clipboard::ClipboardImage;
15use crate::theme;
16
17const MENU_ICON_SIZE: f32 = 16.;
18
12
19pub type ImageShare = Rc<dyn Fn(&mut App)>;
13pub type ImageShare = Rc<dyn Fn(&mut App)>;
20
14
21fn menu_icon(glyph: IconName) -> Icon {
22 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
23}
24
25pub fn copy_image_file(path: PathBuf, cx: &mut App) {
15pub fn copy_image_file(path: PathBuf, cx: &mut App) {
26 cx.spawn(async move |cx| {
16 cx.spawn(async move |cx| {
27 let image = cx
17 let image = cx
crates/app/src/views/message_row.rs +41 −7
@@ -49,6 +49,10 @@ pub const BUBBLE_TAGS: [&str; 12] = [
49 49 pub(super) const AVATAR_SIZE: f32 = 28.;
50 50 pub(super) const AVATAR_GAP: f32 = 8.;
51 51 const SERIES_START_GAP: f32 = 8.;
52 const SERIES_GAP: f32 = 2.;
53 const COMPACT_SERIES_START_GAP: f32 = 4.;
54 const COMPACT_SERIES_GAP: f32 = 1.;
55 const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;
52 56 pub(super) const BODY_SIZE: f32 = 13.5;
53 57 const MAX_WIDTH_RATIO: f32 = 0.7;
54 58 const NARROW_BUBBLE_WIDTH: f32 = 300.;
@@ -89,6 +93,24 @@ pub struct RowActions {
89 93 pub call: CallActions,
90 94 pub reaction_proposal: Option<ReactionPill>,
91 95 pub undo_delete: SharedRowAction,
96 pub compact: bool,
97 }
98
99 pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
100 match (has_previous, compact) {
101 (true, false) => SERIES_GAP,
102 (true, true) => COMPACT_SERIES_GAP,
103 (false, false) => SERIES_START_GAP,
104 (false, true) => COMPACT_SERIES_START_GAP,
105 }
106 }
107
108 pub fn bubble_padding_y(compact: bool) -> f32 {
109 if compact {
110 COMPACT_BUBBLE_PADDING_Y
111 } else {
112 BUBBLE_PADDING_Y
113 }
92 114 }
93 115
94 116 const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -190,7 +212,7 @@ fn bubble(
190 212 .rounded_br(px(corners.bottom_right))
191 213 .rounded_bl(px(corners.bottom_left))
192 214 .px(px(12.))
193 .py(px(BUBBLE_PADDING_Y))
215 .py(px(bubble_padding_y(extras.compact)))
194 216 })
195 217 .text_size(px(BODY_SIZE))
196 218 .line_height(relative(1.45));
@@ -299,7 +321,7 @@ fn bubble(
299 321 .child(
300 322 h_flex()
301 323 .flex_none()
302 .mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
324 .mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))
303 325 .child(bubble_meta(row, own, saved)),
304 326 ),
305 327 );
@@ -348,6 +370,7 @@ struct BubbleExtras {
348 370 agent_run: Option<AgentRun>,
349 371 reaction_proposal: Option<ReactionPill>,
350 372 undo_delete: SharedRowAction,
373 compact: bool,
351 374 }
352 375
353 376 fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -685,6 +708,7 @@ pub fn render_message_row(
685 708 pinned: _,
686 709 reaction_proposal,
687 710 undo_delete,
711 compact,
688 712 } = actions;
689 713 let extras = BubbleExtras {
690 714 hover: hovered,
@@ -700,13 +724,10 @@ pub fn render_message_row(
700 724 agent_run,
701 725 reaction_proposal,
702 726 undo_delete,
727 compact,
703 728 };
704 729 let own = row.own;
705 let spacing = if row.series.has_prev {
706 px(2.)
707 } else {
708 px(SERIES_START_GAP)
709 };
730 let spacing = px(row_spacing(row.series.has_prev, compact));
710 731 let mut container = v_flex().w_full().px(px(ROW_PADDING));
711 732 if let Some(day) = &row.day_header {
712 733 container = container.child(day_separator(day));
@@ -740,3 +761,16 @@ pub fn render_message_row(
740 761 )
741 762 .into_any_element()
742 763 }
764
765 #[cfg(test)]
766 mod density_tests {
767 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
768
769 #[test]
770 fn compact_density_tightens_gaps_and_bubble_padding() {
771 assert!(row_spacing(false, true) < row_spacing(false, false));
772 assert!(row_spacing(true, true) < row_spacing(true, false));
773 assert!(bubble_padding_y(true) < bubble_padding_y(false));
774 assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);
775 }
776 }
@@ -49,6 +49,10 @@ pub const BUBBLE_TAGS: [&str; 12] = [
49pub(super) const AVATAR_SIZE: f32 = 28.;
49pub(super) const AVATAR_SIZE: f32 = 28.;
50pub(super) const AVATAR_GAP: f32 = 8.;
50pub(super) const AVATAR_GAP: f32 = 8.;
51const SERIES_START_GAP: f32 = 8.;
51const SERIES_START_GAP: f32 = 8.;
52const SERIES_GAP: f32 = 2.;
53const COMPACT_SERIES_START_GAP: f32 = 4.;
54const COMPACT_SERIES_GAP: f32 = 1.;
55const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;
52pub(super) const BODY_SIZE: f32 = 13.5;
56pub(super) const BODY_SIZE: f32 = 13.5;
53const MAX_WIDTH_RATIO: f32 = 0.7;
57const MAX_WIDTH_RATIO: f32 = 0.7;
54const NARROW_BUBBLE_WIDTH: f32 = 300.;
58const NARROW_BUBBLE_WIDTH: f32 = 300.;
@@ -89,6 +93,24 @@ pub struct RowActions {
89 pub call: CallActions,
93 pub call: CallActions,
90 pub reaction_proposal: Option<ReactionPill>,
94 pub reaction_proposal: Option<ReactionPill>,
91 pub undo_delete: SharedRowAction,
95 pub undo_delete: SharedRowAction,
96 pub compact: bool,
97}
98
99pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
100 match (has_previous, compact) {
101 (true, false) => SERIES_GAP,
102 (true, true) => COMPACT_SERIES_GAP,
103 (false, false) => SERIES_START_GAP,
104 (false, true) => COMPACT_SERIES_START_GAP,
105 }
106}
107
108pub fn bubble_padding_y(compact: bool) -> f32 {
109 if compact {
110 COMPACT_BUBBLE_PADDING_Y
111 } else {
112 BUBBLE_PADDING_Y
113 }
92}
114}
93
115
94const TOOLBAR_RIGHT_INSET: f32 = 0.;
116const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -190,7 +212,7 @@ fn bubble(
190 .rounded_br(px(corners.bottom_right))
212 .rounded_br(px(corners.bottom_right))
191 .rounded_bl(px(corners.bottom_left))
213 .rounded_bl(px(corners.bottom_left))
192 .px(px(12.))
214 .px(px(12.))
193 .py(px(BUBBLE_PADDING_Y))
215 .py(px(bubble_padding_y(extras.compact)))
194 })
216 })
195 .text_size(px(BODY_SIZE))
217 .text_size(px(BODY_SIZE))
196 .line_height(relative(1.45));
218 .line_height(relative(1.45));
@@ -299,7 +321,7 @@ fn bubble(
299 .child(
321 .child(
300 h_flex()
322 h_flex()
301 .flex_none()
323 .flex_none()
302 .mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
324 .mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))
303 .child(bubble_meta(row, own, saved)),
325 .child(bubble_meta(row, own, saved)),
304 ),
326 ),
305 );
327 );
@@ -348,6 +370,7 @@ struct BubbleExtras {
348 agent_run: Option<AgentRun>,
370 agent_run: Option<AgentRun>,
349 reaction_proposal: Option<ReactionPill>,
371 reaction_proposal: Option<ReactionPill>,
350 undo_delete: SharedRowAction,
372 undo_delete: SharedRowAction,
373 compact: bool,
351}
374}
352
375
353fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
376fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -685,6 +708,7 @@ pub fn render_message_row(
685 pinned: _,
708 pinned: _,
686 reaction_proposal,
709 reaction_proposal,
687 undo_delete,
710 undo_delete,
711 compact,
688 } = actions;
712 } = actions;
689 let extras = BubbleExtras {
713 let extras = BubbleExtras {
690 hover: hovered,
714 hover: hovered,
@@ -700,13 +724,10 @@ pub fn render_message_row(
700 agent_run,
724 agent_run,
701 reaction_proposal,
725 reaction_proposal,
702 undo_delete,
726 undo_delete,
727 compact,
703 };
728 };
704 let own = row.own;
729 let own = row.own;
705 let spacing = if row.series.has_prev {
730 let spacing = px(row_spacing(row.series.has_prev, compact));
706 px(2.)
707 } else {
708 px(SERIES_START_GAP)
709 };
710 let mut container = v_flex().w_full().px(px(ROW_PADDING));
731 let mut container = v_flex().w_full().px(px(ROW_PADDING));
711 if let Some(day) = &row.day_header {
732 if let Some(day) = &row.day_header {
712 container = container.child(day_separator(day));
733 container = container.child(day_separator(day));
@@ -740,3 +761,16 @@ pub fn render_message_row(
740 )
761 )
741 .into_any_element()
762 .into_any_element()
742}
763}
764
765#[cfg(test)]
766mod density_tests {
767 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
768
769 #[test]
770 fn compact_density_tightens_gaps_and_bubble_padding() {
771 assert!(row_spacing(false, true) < row_spacing(false, false));
772 assert!(row_spacing(true, true) < row_spacing(true, false));
773 assert!(bubble_padding_y(true) < bubble_padding_y(false));
774 assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);
775 }
776}
crates/app/src/views/new_meeting_dialog.rs +2 −1
@@ -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))
crates/app/src/views/pin_banner.rs +1 −1
@@ -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;
10use crate::theme;
10use crate::theme;
11
11
12const BANNER_HEIGHT: f32 = 40.;
12const BANNER_HEIGHT: f32 = 40.;
13const BANNER_INSET: f32 = ROW_PADDING;
14pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
13pub const PIN_BANNER_TAG: &str = "shell/islands/main/pin-banner";
15const BANNER_GAP: f32 = 8.;
14const BANNER_GAP: f32 = 8.;
16const BANNER_PADDING: f32 = 12.;
15const BANNER_PADDING: f32 = 12.;
16pub const BANNER_INSET: f32 = ROW_PADDING - BANNER_PADDING;
17const BUTTON_SIZE: f32 = 28.;
17const BUTTON_SIZE: f32 = 28.;
18const FALLBACK_PREVIEW: &str = "Pinned message";
18const FALLBACK_PREVIEW: &str = "Pinned message";
19
19
crates/app/src/views/rail.rs +7 −19
@@ -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,23 +207,12 @@ 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
@@ -5,11 +5,10 @@ use gpui_kit::*;
5
5
6use super::shortcuts::keys_for_label;
6use super::shortcuts::keys_for_label;
7use super::sidebar::{SidebarTab, SidebarView};
7use super::sidebar::{SidebarTab, SidebarView};
8use super::widgets::icon;
8use super::widgets::{RAIL_BADGE, badge_pill, icon};
9use crate::activity::ActivityCenter;
9use crate::activity::ActivityCenter;
10use crate::agents::{AgentRuns, runs_handle};
10use crate::agents::{AgentRuns, runs_handle};
11use crate::app_state::AppState;
11use crate::app_state::AppState;
12use crate::format;
13use crate::sidebar_model::{any_unread_channel, unread_chat_count};
12use crate::sidebar_model::{any_unread_channel, unread_chat_count};
14use crate::theme;
13use crate::theme;
15use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
14use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
@@ -208,23 +207,12 @@ 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
crates/app/src/views/shared_tab.rs +1 −6
@@ -14,7 +14,7 @@ use gpui_kit::*;
14 14 use teams_core::{DriveEntry, FileKind};
15 15
16 16 use super::attachments::file_badge;
17 use super::widgets::icon;
17 use super::widgets::{icon, menu_icon};
18 18 use crate::channel_files::{
19 19 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
20 20 };
@@ -30,7 +30,6 @@ const MODIFIED_BY_WIDTH: f32 = 160.;
30 30 const SIZE_WIDTH: f32 = 90.;
31 31 const SKELETON_ROWS: usize = 6;
32 32 const NEW_FOLDER_WIDTH: f32 = 220.;
33 const MENU_ICON_SIZE: f32 = 14.;
34 33
35 34 pub const EMPTY_LIBRARY: &str = "No files yet. Upload or drop files here.";
36 35 pub const EMPTY_MESSAGES: &str = "No files or links shared in this channel yet.";
@@ -254,10 +253,6 @@ fn modified_text(entry: &DriveEntry) -> String {
254 253 })
255 254 }
256 255
257 fn menu_icon(glyph: IconName) -> gpui_kit::component::Icon {
258 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
259 }
260
261 256 fn entry_row(
262 257 index: usize,
263 258 entry: &DriveEntry,
@@ -14,7 +14,7 @@ use gpui_kit::*;
14use teams_core::{DriveEntry, FileKind};
14use teams_core::{DriveEntry, FileKind};
15
15
16use super::attachments::file_badge;
16use super::attachments::file_badge;
17use super::widgets::icon;
17use super::widgets::{icon, menu_icon};
18use crate::channel_files::{
18use crate::channel_files::{
19 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
19 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
20};
20};
@@ -30,7 +30,6 @@ const MODIFIED_BY_WIDTH: f32 = 160.;
30const SIZE_WIDTH: f32 = 90.;
30const SIZE_WIDTH: f32 = 90.;
31const SKELETON_ROWS: usize = 6;
31const SKELETON_ROWS: usize = 6;
32const NEW_FOLDER_WIDTH: f32 = 220.;
32const NEW_FOLDER_WIDTH: f32 = 220.;
33const MENU_ICON_SIZE: f32 = 14.;
34
33
35pub const EMPTY_LIBRARY: &str = "No files yet. Upload or drop files here.";
34pub const EMPTY_LIBRARY: &str = "No files yet. Upload or drop files here.";
36pub const EMPTY_MESSAGES: &str = "No files or links shared in this channel yet.";
35pub const EMPTY_MESSAGES: &str = "No files or links shared in this channel yet.";
@@ -254,10 +253,6 @@ fn modified_text(entry: &DriveEntry) -> String {
254 })
253 })
255}
254}
256
255
257fn menu_icon(glyph: IconName) -> gpui_kit::component::Icon {
258 icon(glyph, MENU_ICON_SIZE, theme::text_muted())
259}
260
261fn entry_row(
256fn entry_row(
262 index: usize,
257 index: usize,
263 entry: &DriveEntry,
258 entry: &DriveEntry,
crates/app/src/views/sidebar.rs +91 −21
@@ -13,7 +13,7 @@ use gpui_kit::*;
13 13 use store::{
14 14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
15 15 };
16 use teams_core::is_notes_chat;
16 use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
17 17
18 18 use super::activity_panel::ActivityPanel;
19 19 use super::avatar::{spec_avatar, square_avatar, with_presence};
@@ -21,7 +21,7 @@ use super::calls_tab::calls_body;
21 21 use super::saved_panel::SavedPanel;
22 22 use super::scroll_edge::with_top_edge;
23 23 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24 use super::widgets::{count_badge, icon, page_header, unread_marker};
24 use super::widgets::{count_badge, icon, menu_icon, page_header, unread_marker};
25 25 use crate::agents::AgentsPanel;
26 26 use crate::app_state::{AppEvent, AppState, Selection};
27 27 use crate::channel_menu::{
@@ -67,7 +67,6 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
67 67 const TEAM_ROW_HEIGHT: f32 = 40.;
68 68 const REVEAL_ROW_HEIGHT: f32 = 32.;
69 69 const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70 const MENU_ICON_SIZE: f32 = 15.;
71 70 const NOTIFICATION_ICON_SIZE: f32 = 13.;
72 71 const MENTION_ICON_SIZE: f32 = 15.;
73 72
@@ -94,6 +93,10 @@ impl SidebarTab {
94 93 }
95 94 }
96 95
96 pub fn chat_row_selector(chat_id: &str) -> String {
97 format!("chat-row/{chat_id}")
98 }
99
97 100 #[derive(Clone)]
98 101 struct DraggedChat {
99 102 id: String,
@@ -135,10 +138,6 @@ struct MenuContext {
135 138 folders: Vec<(String, String)>,
136 139 }
137 140
138 fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
139 icon(name, MENU_ICON_SIZE, theme::text_muted())
140 }
141
142 141 fn chat_menu(
143 142 popup: PopupMenu,
144 143 window: &mut Window,
@@ -219,18 +218,18 @@ fn chat_menu(
219 218 if notes {
220 219 return popup;
221 220 }
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 )
221 popup = popup.item(
222 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
223 .icon(menu_icon(if muted {
224 IconName::Bell
225 } else {
226 IconName::BellOff
227 }))
228 .on_click(move |_, _, cx| {
229 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
230 }),
231 );
232 popup = chat_notifications_submenu(popup, window, cx, context, target)
234 233 .separator()
235 234 .item(
236 235 PopupMenuItem::new("Hide")
@@ -259,7 +258,7 @@ fn chat_menu(
259 258 PopupMenuItem::element(|_, _| {
260 259 div().text_color(theme::red_soft()).child("Leave chat...")
261 260 })
262 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
261 .icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))
263 262 .on_click(move |_, window, cx| {
264 263 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
265 264 }),
@@ -268,6 +267,76 @@ fn chat_menu(
268 267 popup
269 268 }
270 269
270 const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [
271 ("All new messages", ChatNotificationMode::AllNewMessages),
272 ("Mute", ChatNotificationMode::Mute),
273 ];
274
275 const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
276 (
277 "Match settings used for all chats",
278 DesktopNotifications::MatchAllChats,
279 ),
280 ("Don't get desktop notifications", DesktopNotifications::Off),
281 ];
282
283 fn chat_notifications_submenu(
284 popup: PopupMenu,
285 window: &mut Window,
286 cx: &mut Context<PopupMenu>,
287 context: &MenuContext,
288 target: &ChatMenuTarget,
289 ) -> PopupMenu {
290 let state = context.state.clone();
291 let chat_id = target.id.clone();
292 let mode = if target.muted {
293 ChatNotificationMode::Mute
294 } else {
295 ChatNotificationMode::AllNewMessages
296 };
297 let desktop = state.read(cx).chat_desktop_notifications(&chat_id);
298 popup.submenu_with_icon(
299 Some(menu_icon(IconName::Bell)),
300 "Manage notifications",
301 window,
302 cx,
303 move |submenu, _, _| {
304 let choose = |chosen_mode: ChatNotificationMode,
305 chosen_desktop: DesktopNotifications| {
306 let (state, chat_id) = (state.clone(), chat_id.clone());
307 move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
308 state.update(cx, |state, cx| {
309 state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)
310 });
311 }
312 };
313 let submenu = submenu.label("Chat notification mode");
314 let submenu =
315 CHAT_NOTIFICATION_MODES
316 .iter()
317 .fold(submenu, |submenu, (label, value)| {
318 submenu.item(
319 PopupMenuItem::new(*label)
320 .checked(*value == mode)
321 .on_click(choose(*value, desktop)),
322 )
323 });
324 let submenu = submenu
325 .separator()
326 .label("Set a desktop notification preference");
327 DESKTOP_NOTIFICATIONS
328 .iter()
329 .fold(submenu, |submenu, (label, value)| {
330 submenu.item(
331 PopupMenuItem::new(*label)
332 .checked(*value == desktop)
333 .on_click(choose(mode, *value)),
334 )
335 })
336 },
337 )
338 }
339
271 340 #[derive(Clone)]
272 341 struct SectionMenuTarget {
273 342 id: String,
@@ -410,7 +479,7 @@ fn section_menu(
410 479 PopupMenuItem::element(|_, _| {
411 480 div().text_color(theme::red_soft()).child("Delete section")
412 481 })
413 .icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
482 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
414 483 .disabled(target.read_only)
415 484 .on_click(move |_, window, cx| {
416 485 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
@@ -1123,6 +1192,7 @@ impl SidebarView {
1123 1192 };
1124 1193 h_flex()
1125 1194 .id(SharedString::from(format!("chat-{}", item.id)))
1195 .debug_selector(|| chat_row_selector(&item.id))
1126 1196 .mx(px(6.))
1127 1197 .h(px(ROW_HEIGHT))
1128 1198 .flex_none()
@@ -13,7 +13,7 @@ use gpui_kit::*;
13use store::{
13use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
15};
15};
16use teams_core::is_notes_chat;
16use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
17
17
18use super::activity_panel::ActivityPanel;
18use super::activity_panel::ActivityPanel;
19use super::avatar::{spec_avatar, square_avatar, with_presence};
19use super::avatar::{spec_avatar, square_avatar, with_presence};
@@ -21,7 +21,7 @@ use super::calls_tab::calls_body;
21use super::saved_panel::SavedPanel;
21use super::saved_panel::SavedPanel;
22use super::scroll_edge::with_top_edge;
22use super::scroll_edge::with_top_edge;
23use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
23use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24use super::widgets::{count_badge, icon, page_header, unread_marker};
24use super::widgets::{count_badge, icon, menu_icon, page_header, unread_marker};
25use crate::agents::AgentsPanel;
25use crate::agents::AgentsPanel;
26use crate::app_state::{AppEvent, AppState, Selection};
26use crate::app_state::{AppEvent, AppState, Selection};
27use crate::channel_menu::{
27use crate::channel_menu::{
@@ -67,7 +67,6 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
67const TEAM_ROW_HEIGHT: f32 = 40.;
67const TEAM_ROW_HEIGHT: f32 = 40.;
68const REVEAL_ROW_HEIGHT: f32 = 32.;
68const REVEAL_ROW_HEIGHT: f32 = 32.;
69const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
69const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70const MENU_ICON_SIZE: f32 = 15.;
71const NOTIFICATION_ICON_SIZE: f32 = 13.;
70const NOTIFICATION_ICON_SIZE: f32 = 13.;
72const MENTION_ICON_SIZE: f32 = 15.;
71const MENTION_ICON_SIZE: f32 = 15.;
73
72
@@ -94,6 +93,10 @@ impl SidebarTab {
94 }
93 }
95}
94}
96
95
96pub fn chat_row_selector(chat_id: &str) -> String {
97 format!("chat-row/{chat_id}")
98}
99
97#[derive(Clone)]
100#[derive(Clone)]
98struct DraggedChat {
101struct DraggedChat {
99 id: String,
102 id: String,
@@ -135,10 +138,6 @@ struct MenuContext {
135 folders: Vec<(String, String)>,
138 folders: Vec<(String, String)>,
136}
139}
137
140
138fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
139 icon(name, MENU_ICON_SIZE, theme::text_muted())
140}
141
142fn chat_menu(
141fn chat_menu(
143 popup: PopupMenu,
142 popup: PopupMenu,
144 window: &mut Window,
143 window: &mut Window,
@@ -219,18 +218,18 @@ fn chat_menu(
219 if notes {
218 if notes {
220 return popup;
219 return popup;
221 }
220 }
222 popup = popup
221 popup = popup.item(
223 .item(
222 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
224 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
223 .icon(menu_icon(if muted {
225 .icon(menu_icon(if muted {
224 IconName::Bell
226 IconName::Bell
225 } else {
227 } else {
226 IconName::BellOff
228 IconName::BellOff
227 }))
229 }))
228 .on_click(move |_, _, cx| {
230 .on_click(move |_, _, cx| {
229 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));
230 }),
232 }),
231 );
233 )
232 popup = chat_notifications_submenu(popup, window, cx, context, target)
234 .separator()
233 .separator()
235 .item(
234 .item(
236 PopupMenuItem::new("Hide")
235 PopupMenuItem::new("Hide")
@@ -259,7 +258,7 @@ fn chat_menu(
259 PopupMenuItem::element(|_, _| {
258 PopupMenuItem::element(|_, _| {
260 div().text_color(theme::red_soft()).child("Leave chat...")
259 div().text_color(theme::red_soft()).child("Leave chat...")
261 })
260 })
262 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
261 .icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))
263 .on_click(move |_, window, cx| {
262 .on_click(move |_, window, cx| {
264 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
263 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
265 }),
264 }),
@@ -268,6 +267,76 @@ fn chat_menu(
268 popup
267 popup
269}
268}
270
269
270const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [
271 ("All new messages", ChatNotificationMode::AllNewMessages),
272 ("Mute", ChatNotificationMode::Mute),
273];
274
275const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
276 (
277 "Match settings used for all chats",
278 DesktopNotifications::MatchAllChats,
279 ),
280 ("Don't get desktop notifications", DesktopNotifications::Off),
281];
282
283fn chat_notifications_submenu(
284 popup: PopupMenu,
285 window: &mut Window,
286 cx: &mut Context<PopupMenu>,
287 context: &MenuContext,
288 target: &ChatMenuTarget,
289) -> PopupMenu {
290 let state = context.state.clone();
291 let chat_id = target.id.clone();
292 let mode = if target.muted {
293 ChatNotificationMode::Mute
294 } else {
295 ChatNotificationMode::AllNewMessages
296 };
297 let desktop = state.read(cx).chat_desktop_notifications(&chat_id);
298 popup.submenu_with_icon(
299 Some(menu_icon(IconName::Bell)),
300 "Manage notifications",
301 window,
302 cx,
303 move |submenu, _, _| {
304 let choose = |chosen_mode: ChatNotificationMode,
305 chosen_desktop: DesktopNotifications| {
306 let (state, chat_id) = (state.clone(), chat_id.clone());
307 move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
308 state.update(cx, |state, cx| {
309 state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)
310 });
311 }
312 };
313 let submenu = submenu.label("Chat notification mode");
314 let submenu =
315 CHAT_NOTIFICATION_MODES
316 .iter()
317 .fold(submenu, |submenu, (label, value)| {
318 submenu.item(
319 PopupMenuItem::new(*label)
320 .checked(*value == mode)
321 .on_click(choose(*value, desktop)),
322 )
323 });
324 let submenu = submenu
325 .separator()
326 .label("Set a desktop notification preference");
327 DESKTOP_NOTIFICATIONS
328 .iter()
329 .fold(submenu, |submenu, (label, value)| {
330 submenu.item(
331 PopupMenuItem::new(*label)
332 .checked(*value == desktop)
333 .on_click(choose(mode, *value)),
334 )
335 })
336 },
337 )
338}
339
271#[derive(Clone)]
340#[derive(Clone)]
272struct SectionMenuTarget {
341struct SectionMenuTarget {
273 id: String,
342 id: String,
@@ -410,7 +479,7 @@ fn section_menu(
410 PopupMenuItem::element(|_, _| {
479 PopupMenuItem::element(|_, _| {
411 div().text_color(theme::red_soft()).child("Delete section")
480 div().text_color(theme::red_soft()).child("Delete section")
412 })
481 })
413 .icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
482 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
414 .disabled(target.read_only)
483 .disabled(target.read_only)
415 .on_click(move |_, window, cx| {
484 .on_click(move |_, window, cx| {
416 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
485 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
@@ -1123,6 +1192,7 @@ impl SidebarView {
1123 };
1192 };
1124 h_flex()
1193 h_flex()
1125 .id(SharedString::from(format!("chat-{}", item.id)))
1194 .id(SharedString::from(format!("chat-{}", item.id)))
1195 .debug_selector(|| chat_row_selector(&item.id))
1126 .mx(px(6.))
1196 .mx(px(6.))
1127 .h(px(ROW_HEIGHT))
1197 .h(px(ROW_HEIGHT))
1128 .flex_none()
1198 .flex_none()
crates/app/src/views/status_menu.rs +3 −7
@@ -11,7 +11,7 @@ use gpui_kit::*;
11 11 use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12 12
13 13 use super::avatar::{person_avatar, with_presence, with_presence_badge};
14 use super::widgets::{icon, symbol};
14 use super::widgets::{menu_icon, symbol};
15 15 use crate::app_state::AppState;
16 16 use crate::data::{Person, PresenceKind};
17 17 use crate::own_status::{
@@ -30,7 +30,7 @@ const PRESENCE_OVERHANG: f32 = 2.;
30 30 const TITLE_BUTTON_INSET: f32 = 2.;
31 31 const OWN_STATUS_BUTTON_SIZE: f32 =
32 32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
33 const MENU_ICON_SIZE: f32 = 14.;
33 const PRESENCE_ICON_SIZE: f32 = 14.;
34 34 const ICON_COLUMN: f32 = 16.;
35 35 const HEADER_INSET: f32 = 24.;
36 36
@@ -118,11 +118,7 @@ fn status_icon(kind: PresenceKind) -> gpui_kit::component::Icon {
118 118 PresenceKind::Offline => ("status_ring", theme::text_muted()),
119 119 PresenceKind::Unknown => ("status_ring", theme::text_faint()),
120 120 };
121 symbol(name, MENU_ICON_SIZE, color)
122 }
123
124 fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
125 icon(name, MENU_ICON_SIZE, theme::text_muted())
121 symbol(name, PRESENCE_ICON_SIZE, color)
126 122 }
127 123
128 124 fn header(context: &MenuContext, cx: &App) -> Div {
@@ -11,7 +11,7 @@ use gpui_kit::*;
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
11use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKind};
12
12
13use super::avatar::{person_avatar, with_presence, with_presence_badge};
13use super::avatar::{person_avatar, with_presence, with_presence_badge};
14use super::widgets::{icon, symbol};
14use super::widgets::{menu_icon, symbol};
15use crate::app_state::AppState;
15use crate::app_state::AppState;
16use crate::data::{Person, PresenceKind};
16use crate::data::{Person, PresenceKind};
17use crate::own_status::{
17use crate::own_status::{
@@ -30,7 +30,7 @@ const PRESENCE_OVERHANG: f32 = 2.;
30const TITLE_BUTTON_INSET: f32 = 2.;
30const TITLE_BUTTON_INSET: f32 = 2.;
31const OWN_STATUS_BUTTON_SIZE: f32 =
31const OWN_STATUS_BUTTON_SIZE: f32 =
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
32 TITLE_AVATAR_SIZE + 2. * (PRESENCE_OVERHANG + TITLE_BUTTON_INSET);
33const MENU_ICON_SIZE: f32 = 14.;
33const PRESENCE_ICON_SIZE: f32 = 14.;
34const ICON_COLUMN: f32 = 16.;
34const ICON_COLUMN: f32 = 16.;
35const HEADER_INSET: f32 = 24.;
35const HEADER_INSET: f32 = 24.;
36
36
@@ -118,11 +118,7 @@ fn status_icon(kind: PresenceKind) -> gpui_kit::component::Icon {
118 PresenceKind::Offline => ("status_ring", theme::text_muted()),
118 PresenceKind::Offline => ("status_ring", theme::text_muted()),
119 PresenceKind::Unknown => ("status_ring", theme::text_faint()),
119 PresenceKind::Unknown => ("status_ring", theme::text_faint()),
120 };
120 };
121 symbol(name, MENU_ICON_SIZE, color)
121 symbol(name, PRESENCE_ICON_SIZE, color)
122}
123
124fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
125 icon(name, MENU_ICON_SIZE, theme::text_muted())
126}
122}
127
123
128fn header(context: &MenuContext, cx: &App) -> Div {
124fn header(context: &MenuContext, cx: &App) -> Div {
crates/app/src/views/status_message_dialog.rs +2 −1
@@ -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
crates/chatsvc/src/chat_notifications.rs added +130 −0
@@ -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 @@
1use serde_json::{Map, Value};
2
3pub(crate) const PROPERTY_NAME: &str = "conversationNotificationSettings";
4const ALL_NEW_POSTS: &str = "allNewPosts";
5const DESKTOP: &str = "dskNotif";
6const EVERYONE: &str = "everyone";
7const ON: &str = "On";
8const OFF: &str = "Off";
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
11pub enum ChatNotificationMode {
12 #[default]
13 AllNewMessages,
14 Mute,
15}
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
18pub enum DesktopNotifications {
19 #[default]
20 MatchAllChats,
21 On,
22 Off,
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct ChatNotificationWrite {
27 pub alerts: bool,
28 pub settings: String,
29}
30
31fn 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
37pub 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.
46pub 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)]
73mod 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}
crates/chatsvc/src/chat_settings.rs added +733 −0
@@ -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 @@
1use serde_json::{Map, Value, json};
2use session::Session;
3
4use crate::error::Result;
5use crate::messages::{MessageTransport, SessionMessageTransport};
6use crate::settings::UserSettings;
7
8const READ_RECEIPTS_KEY: &str = "readReceiptsEnabled";
9const MESSAGE_DENSITY_KEY: &str = "messageDensity";
10const COMPOSE_SETTINGS_KEY: &str = "composeUserSettings";
11const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings";
12const ENTER_KEY_FIELD: &str = "enterKeyBehavior";
13const MESSAGING_SETTINGS: &str = "messagingSettings";
14const UP_ARROW_FIELD: &str = "upArrowKeyBehavior";
15const TOAST_SETTINGS: &str = "toastSettings";
16const ACTIVITY_SETTINGS: &str = "activityGenerationSettings";
17const EMAIL_SETTINGS: &str = "emailSettings";
18const CHAT_SETTINGS: &str = "chatSettings";
19const SELECTED_PRESET_FIELD: &str = "selectedPreset";
20const MEETING_CHAT_FIELD: &str = "meetingChatNotification";
21const SHOW_PREVIEW_FIELD: &str = "ShowPreviewInToasts";
22const CHAT_MESSAGES_FIELD: &str = "Chat";
23const PERSONAL_MENTIONS_FIELD: &str = "MentionInChat_Person_v2";
24const EVERYONE_MENTIONS_FIELD: &str = "MentionInChat_Everyone";
25const LIKES_FIELD: &str = "LikeInChat_v2";
26const 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)]
34pub enum MessageDensity {
35 #[default]
36 Comfy,
37 Compact,
38}
39
40impl 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)]
58pub enum EnterKeyBehavior {
59 #[default]
60 Send,
61 NewLine,
62}
63
64impl 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)]
82pub enum UpArrowBehavior {
83 NavigateToMessages,
84 #[default]
85 EditLastMessage,
86 StayInCompose,
87}
88
89impl 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)]
112pub enum NotificationPreset {
113 AllActivity,
114 MentionsAndReplies,
115 #[default]
116 Customised,
117}
118
119impl 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)]
146pub enum ActivityAlert {
147 #[default]
148 BannerAndFeed,
149 OnlyFeed,
150 OnlyBanner,
151 Off,
152}
153
154impl 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)]
173pub enum MeetingChatNotifications {
174 Mute,
175 Unmute,
176 #[default]
177 MuteUntilJoin,
178}
179
180impl 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)]
203pub 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
213impl 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)]
228pub 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
236impl 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)]
249pub 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)]
265pub struct ChatSettingsDocument {
266 properties: Map<String, Value>,
267}
268
269impl 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
357fn 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
365fn 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
371fn text_at<'a>(object: &'a Map<String, Value>, path: &[&str]) -> Option<&'a str> {
372 value_at(object, path)?.as_str()
373}
374
375fn flag_at(object: &Map<String, Value>, group: &str, field: &str) -> Option<bool> {
376 value_at(object, &[group, field]).and_then(flag)
377}
378
379fn 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
395fn 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
402fn 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
429fn 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
439fn 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
443fn 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
450fn 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
490pub struct ChatSettingsClient<T: MessageTransport = SessionMessageTransport> {
491 settings: UserSettings<T>,
492}
493
494impl ChatSettingsClient<SessionMessageTransport> {
495 pub fn new(session: &Session) -> Self {
496 ChatSettingsClient::with_settings(UserSettings::new(session))
497 }
498}
499
500impl<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)]
521mod 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}
crates/chatsvc/src/conversations.rs +86 −4
@@ -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};
2use session::{Method, Request, Session};
2use session::{Method, Request, Session};
3
3
4use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
4use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME};
5use crate::chat_notifications::{
6 self, ChatNotificationMode, ChatNotificationWrite, DesktopNotifications,
7};
5use crate::error::{Error, Result};
8use crate::error::{Error, Result};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
9use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7use crate::pins::DEFAULT_REGION;
10use crate::pins::DEFAULT_REGION;
@@ -12,13 +15,20 @@ const MAX_PAGES: usize = 100;
12const ALERTS_OFF: &str = "false";
15const ALERTS_OFF: &str = "false";
13const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
16const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
14
17
15#[derive(Debug, Clone, PartialEq, Eq)]
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
16pub struct ConversationState {
19pub 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
28impl ConversationState {
29 pub fn desktop_notifications(&self) -> DesktopNotifications {
30 chat_notifications::parse_desktop(self.notification_settings.as_deref())
31 }
22}
32}
23
33
24pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
34pub 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_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 /// 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 = self
126 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 .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}
crates/chatsvc/src/lib.rs +8 −0
@@ -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;
@@ -46,6 +48,12 @@ pub use cards::{
46 48 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
47 49 };
48 50 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
51 pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
52 pub use chat_settings::{
53 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
54 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
55 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
56 };
49 57 pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
50 58 pub use conversations::{ConversationState, Conversations};
51 59 pub use drafts::{ScheduledDraft, ScheduledDrafts};
@@ -4,6 +4,8 @@ pub mod calendar;
4pub mod calllog;
4pub mod calllog;
5pub mod cards;
5pub mod cards;
6pub mod channel_notifications;
6pub mod channel_notifications;
7pub mod chat_notifications;
8pub mod chat_settings;
7pub mod channel_visibility;
9pub mod channel_visibility;
8pub mod conversations;
10pub mod conversations;
9pub mod drafts;
11pub mod drafts;
@@ -46,6 +48,12 @@ pub use cards::{
46 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
48 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
47};
49};
48pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
50pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
51pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
52pub use chat_settings::{
53 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
54 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
55 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
56};
49pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
57pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
50pub use conversations::{ConversationState, Conversations};
58pub use conversations::{ConversationState, Conversations};
51pub use drafts::{ScheduledDraft, ScheduledDrafts};
59pub use drafts::{ScheduledDraft, ScheduledDrafts};
crates/core/src/channel_mentions.rs +2 −0
@@ -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
crates/core/src/chat_settings_sync.rs added +92 −0
@@ -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 @@
1use chatsvc::{
2 ChatNotificationMode, ChatSettingChange, ChatSettingsDocument, DesktopNotifications,
3};
4use store::Store;
5
6use crate::engine::SyncEngine;
7use crate::error::Result;
8use crate::events::CoreEvent;
9use crate::remote::Remote;
10
11const META_CHAT_SETTINGS: &str = "account.chat_settings";
12
13pub 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
22pub fn store_chat_settings(store: &Store, document: &ChatSettingsDocument) -> Result<()> {
23 Ok(store.set_meta(META_CHAT_SETTINGS, &document.to_text())?)
24}
25
26impl<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)]
78mod 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}
crates/core/src/hidden_chats.rs +1 −0
@@ -192,6 +192,7 @@ mod tests {
192 192 muted: false,
193 193 hidden,
194 194 read: chatsvc::ReadHorizon::default(),
195 notification_settings: None,
195 196 history_cleared_ms: None,
196 197 },
197 198 )])
@@ -192,6 +192,7 @@ mod tests {
192 muted: false,
192 muted: false,
193 hidden,
193 hidden,
194 read: chatsvc::ReadHorizon::default(),
194 read: chatsvc::ReadHorizon::default(),
195 notification_settings: None,
195 history_cleared_ms: None,
196 history_cleared_ms: None,
196 },
197 },
197 )])
198 )])
crates/core/src/lib.rs +7 −0
@@ -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;
13mod card_width;
13mod card_width;
14mod channel_mentions;
14mod channel_mentions;
15mod channel_sync;
15mod channel_sync;
16mod chat_settings_sync;
16mod channel_visibility;
17mod channel_visibility;
17mod chat_paging;
18mod chat_paging;
18mod default_reactions;
19mod 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};
107pub use chat_settings_sync::{store_chat_settings, stored_chat_settings};
108pub use chatsvc::{
109 ActivityAlert, ChatAccountSettings, ChatNotificationMode, ChatSettingChange,
110 ChatSettingsDocument, DesktopNotifications, EnterKeyBehavior, MeetingChatNotifications,
111 MessageDensity, NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
112};
106pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
113pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
107pub use chatsvc::{
114pub use chatsvc::{
108 Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
115 Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
crates/core/src/notes_chat.rs +1 −0
@@ -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 }
crates/core/src/remote.rs +41 −2
@@ -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,
@@ -476,6 +477,24 @@ pub trait Remote {
476 477 Err(Error::Unsupported("sound settings"))
477 478 }
478 479
480 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
481 Err(Error::Unsupported("chat settings"))
482 }
483
484 async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
485 Err(Error::Unsupported("chat settings"))
486 }
487
488 async fn set_chat_notifications(
489 &self,
490 _chat_id: &str,
491 _current_settings: Option<&str>,
492 _mode: ChatNotificationMode,
493 _desktop: DesktopNotifications,
494 ) -> Result<ChatNotificationWrite> {
495 Err(Error::Unsupported("chat notifications"))
496 }
497
479 498 async fn save_sound_settings(
480 499 &self,
481 500 _user_mri: &str,
@@ -1241,6 +1260,26 @@ impl Remote for Graph {
1241 1260 Ok(SoundSettingsClient::new(self.session()).read().await?)
1242 1261 }
1243 1262
1263 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1264 Ok(ChatSettingsClient::new(self.session()).read().await?)
1265 }
1266
1267 async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1268 Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1269 }
1270
1271 async fn set_chat_notifications(
1272 &self,
1273 chat_id: &str,
1274 current_settings: Option<&str>,
1275 mode: ChatNotificationMode,
1276 desktop: DesktopNotifications,
1277 ) -> Result<ChatNotificationWrite> {
1278 Ok(Conversations::new(self.session())
1279 .set_chat_notifications(chat_id, current_settings, mode, desktop)
1280 .await?)
1281 }
1282
1244 1283 async fn save_sound_settings(
1245 1284 &self,
1246 1285 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};
5use chatsvc::{
5use 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};
9use chatsvc::{
10use chatsvc::{
10 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
11 BotProfile, BotProfiles, CallLogEntry, CardActions, ChatApp, ConversationRef,
@@ -476,6 +477,24 @@ pub trait Remote {
476 Err(Error::Unsupported("sound settings"))
477 Err(Error::Unsupported("sound settings"))
477 }
478 }
478
479
480 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
481 Err(Error::Unsupported("chat settings"))
482 }
483
484 async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
485 Err(Error::Unsupported("chat settings"))
486 }
487
488 async fn set_chat_notifications(
489 &self,
490 _chat_id: &str,
491 _current_settings: Option<&str>,
492 _mode: ChatNotificationMode,
493 _desktop: DesktopNotifications,
494 ) -> Result<ChatNotificationWrite> {
495 Err(Error::Unsupported("chat notifications"))
496 }
497
479 async fn save_sound_settings(
498 async fn save_sound_settings(
480 &self,
499 &self,
481 _user_mri: &str,
500 _user_mri: &str,
@@ -1241,6 +1260,26 @@ impl Remote for Graph {
1241 Ok(SoundSettingsClient::new(self.session()).read().await?)
1260 Ok(SoundSettingsClient::new(self.session()).read().await?)
1242 }
1261 }
1243
1262
1263 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1264 Ok(ChatSettingsClient::new(self.session()).read().await?)
1265 }
1266
1267 async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1268 Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1269 }
1270
1271 async fn set_chat_notifications(
1272 &self,
1273 chat_id: &str,
1274 current_settings: Option<&str>,
1275 mode: ChatNotificationMode,
1276 desktop: DesktopNotifications,
1277 ) -> Result<ChatNotificationWrite> {
1278 Ok(Conversations::new(self.session())
1279 .set_chat_notifications(chat_id, current_settings, mode, desktop)
1280 .await?)
1281 }
1282
1244 async fn save_sound_settings(
1283 async fn save_sound_settings(
1245 &self,
1284 &self,
1246 user_mri: &str,
1285 user_mri: &str,
crates/core/tests/engine.rs +3 −0
@@ -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 );
@@ -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 );
vendor/gpui-component/src/button/button.rs +2 −3
@@ -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| {
vendor/gpui-component/src/fluent.rs added +29 −0
@@ -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
3use gpui::{Pixels, px};
4
5pub const MENU_ITEM_HEIGHT: Pixels = px(32.);
6pub const MENU_ITEM_PADDING_X: Pixels = px(6.);
7pub const MENU_ICON_SLOT: Pixels = px(20.);
8// A Lucide glyph at 18 px covers what a Fluent 20 px regular icon covers.
9pub const MENU_ICON_GLYPH: Pixels = px(18.);
10pub const MENU_ICON_GAP: Pixels = px(4.);
11pub const MENU_LABEL_INSET: Pixels = px(2.);
12pub const MENU_ICON_LABEL_GAP: Pixels = px(6.);
13pub const MENU_LIST_PADDING: Pixels = px(4.);
14pub const MENU_ITEM_GAP: Pixels = px(2.);
15pub const MENU_DIVIDER_MARGIN_Y: Pixels = px(4.);
16
17pub const OPTION_CHECK_INSET: Pixels = px(6.);
18pub const OPTION_PADDING_RIGHT: Pixels = px(8.);
19pub const OPTION_CHECK_SIZE: Pixels = px(16.);
20pub const OPTION_CHECK_GAP: Pixels = px(6.);
21pub const LISTBOX_MIN_WIDTH: Pixels = px(160.);
22pub const DROPDOWN_OFFSET: Pixels = px(2.);
23
24pub const BUTTON_ICON_GAP: Pixels = px(6.);
25pub const BUTTON_ICON_GAP_SMALL: Pixels = px(4.);
26
27pub const TOAST_ICON_SIZE: Pixels = px(16.);
28pub const TOAST_ICON_GAP: Pixels = px(8.);
29pub const TOAST_LINE_HEIGHT: Pixels = px(20.);
vendor/gpui-component/src/icon.rs +4 −0
@@ -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 angle
171 /// Rotate the icon by the given angle
168 ///
172 ///
169 /// Replaces any previous transformation or rotation.
173 /// Replaces any previous transformation or rotation.
vendor/gpui-component/src/lib.rs +1 −0
@@ -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;
44pub mod dock;
44pub mod dock;
45pub mod elevation;
45pub mod elevation;
46pub mod empty;
46pub mod empty;
47pub mod fluent;
47pub mod form;
48pub mod form;
48pub mod group_box;
49pub mod group_box;
49pub mod highlighter;
50pub mod highlighter;
vendor/gpui-component/src/menu/dropdown_menu.rs +42 −8
@@ -1,12 +1,15 @@
1 use std::cell::Cell;
1 2 use std::rc::Rc;
2 3
3 4 use gpui::{
4 5 Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
5 6 Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
6 RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
7 Pixels, RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
7 8 };
8 9
9 use crate::{Selectable, button::Button, menu::PopupMenu, popover::Popover};
10 use crate::{
11 Selectable, button::Button, fluent::DROPDOWN_OFFSET, menu::PopupMenu, popover::Popover,
12 };
10 13
11 14 /// A dropdown menu trait for buttons and other interactive elements
12 15 pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
@@ -40,6 +43,7 @@ pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
40 43 builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
41 44 on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
42 45 open: Option<bool>,
46 listbox: bool,
43 47 }
44 48
45 49 impl<T> DropdownMenuPopover<T>
@@ -59,6 +63,7 @@ where
59 63 builder: Rc::new(builder),
60 64 on_open_change: None,
61 65 open: None,
66 listbox: false,
62 67 }
63 68 }
64 69
@@ -68,6 +73,13 @@ where
68 73 self
69 74 }
70 75
76 /// Open the menu as a Fluent `Listbox`: left aligned under the trigger,
77 /// 2 px below it and at least as wide, with a check column.
78 pub fn listbox(mut self) -> Self {
79 self.listbox = true;
80 self
81 }
82
71 83 /// Set the anchor corner for the dropdown menu popover.
72 84 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
73 85 self.anchor = anchor.into();
@@ -91,15 +103,28 @@ struct DropdownMenuState {
91 103 menu: Option<Entity<PopupMenu>>,
92 104 }
93 105
106 #[derive(Default)]
107 struct TriggerWidth(Rc<Cell<Pixels>>);
108
94 109 impl<T> RenderOnce for DropdownMenuPopover<T>
95 110 where
96 111 T: Selectable + IntoElement + 'static,
97 112 {
98 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
99 TriggerFocus::new(self.id.clone(), move |trigger_focus, window, cx| {
100 self.render_popover(trigger_focus, window, cx)
101 .into_any_element()
102 })
113 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
114 let width_key = SharedString::from(format!("{}:trigger-width", self.id));
115 let trigger_width = window
116 .use_keyed_state(width_key, cx, |_, _| TriggerWidth::default())
117 .read(cx)
118 .0
119 .clone();
120 TriggerFocus::new(
121 self.id.clone(),
122 trigger_width.clone(),
123 move |trigger_focus, window, cx| {
124 self.render_popover(trigger_focus, trigger_width, window, cx)
125 .into_any_element()
126 },
127 )
103 128 }
104 129 }
105 130
@@ -110,10 +135,12 @@ where
110 135 fn render_popover(
111 136 self,
112 137 trigger_focus: FocusHandle,
138 trigger_width: Rc<Cell<Pixels>>,
113 139 window: &mut Window,
114 140 cx: &mut App,
115 141 ) -> Popover {
116 142 let builder = self.builder.clone();
143 let listbox = self.listbox;
117 144 let menu_state =
118 145 window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
119 146
@@ -122,6 +149,7 @@ where
122 149 .overlay_closable(false)
123 150 .trigger(self.trigger)
124 151 .anchor(self.anchor)
152 .when(listbox, |this| this.offset(DROPDOWN_OFFSET))
125 153 .when_some(self.open, |this, open| this.open(open))
126 154 .when_some(self.on_open_change, |this, callback| {
127 155 this.on_open_change(move |open, window, cx| callback(open, window, cx))
@@ -137,7 +165,9 @@ where
137 165 Some(menu) => menu,
138 166 None => {
139 167 let builder = builder.clone();
168 let width = trigger_width.get();
140 169 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
170 let menu = if listbox { menu.listbox(width) } else { menu };
141 171 builder(menu, window, cx)
142 172 });
143 173 menu.update(cx, |menu, cx| {
@@ -191,6 +221,7 @@ type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> A
191 221 /// the menu was not yet.
192 222 struct TriggerFocus {
193 223 id: ElementId,
224 width: Rc<Cell<Pixels>>,
194 225 build: Option<TriggerFocusBuild>,
195 226 }
196 227
@@ -207,10 +238,12 @@ struct TriggerFocusFrame {
207 238 impl TriggerFocus {
208 239 fn new(
209 240 id: ElementId,
241 width: Rc<Cell<Pixels>>,
210 242 build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
211 243 ) -> Self {
212 244 Self {
213 245 id,
246 width,
214 247 build: Some(Box::new(build)),
215 248 }
216 249 }
@@ -269,11 +302,12 @@ impl Element for TriggerFocus {
269 302 &mut self,
270 303 _: Option<&GlobalElementId>,
271 304 _: Option<&InspectorElementId>,
272 _: gpui::Bounds<gpui::Pixels>,
305 bounds: gpui::Bounds<gpui::Pixels>,
273 306 frame: &mut Self::RequestLayoutState,
274 307 window: &mut Window,
275 308 cx: &mut App,
276 309 ) {
310 self.width.set(bounds.size.width);
277 311 window.set_focus_handle(&frame.focus_handle, cx);
278 312 frame.child.prepaint(window, cx);
279 313 }
@@ -1,12 +1,15 @@
1use std::cell::Cell;
1use std::rc::Rc;
2use std::rc::Rc;
2
3
3use gpui::{
4use gpui::{
4 Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
5 Anchor, AnyElement, App, Context, DismissEvent, Element, ElementId, Entity, FocusHandle,
5 Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
6 Focusable, GlobalElementId, InspectorElementId, InteractiveElement, IntoElement, LayoutId,
6 RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
7 Pixels, RenderOnce, SharedString, Styled, Window, prelude::FluentBuilder,
7};
8};
8
9
9use crate::{Selectable, button::Button, menu::PopupMenu, popover::Popover};
10use crate::{
11 Selectable, button::Button, fluent::DROPDOWN_OFFSET, menu::PopupMenu, popover::Popover,
12};
10
13
11/// A dropdown menu trait for buttons and other interactive elements
14/// A dropdown menu trait for buttons and other interactive elements
12pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
15pub trait DropdownMenu: Styled + Selectable + InteractiveElement + IntoElement + 'static {
@@ -40,6 +43,7 @@ pub struct DropdownMenuPopover<T: Selectable + IntoElement + 'static> {
40 builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
43 builder: Rc<dyn Fn(PopupMenu, &mut Window, &mut Context<PopupMenu>) -> PopupMenu>,
41 on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
44 on_open_change: Option<Rc<dyn Fn(&bool, &mut Window, &mut App)>>,
42 open: Option<bool>,
45 open: Option<bool>,
46 listbox: bool,
43}
47}
44
48
45impl<T> DropdownMenuPopover<T>
49impl<T> DropdownMenuPopover<T>
@@ -59,6 +63,7 @@ where
59 builder: Rc::new(builder),
63 builder: Rc::new(builder),
60 on_open_change: None,
64 on_open_change: None,
61 open: None,
65 open: None,
66 listbox: false,
62 }
67 }
63 }
68 }
64
69
@@ -68,6 +73,13 @@ where
68 self
73 self
69 }
74 }
70
75
76 /// Open the menu as a Fluent `Listbox`: left aligned under the trigger,
77 /// 2 px below it and at least as wide, with a check column.
78 pub fn listbox(mut self) -> Self {
79 self.listbox = true;
80 self
81 }
82
71 /// Set the anchor corner for the dropdown menu popover.
83 /// Set the anchor corner for the dropdown menu popover.
72 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
84 pub fn anchor(mut self, anchor: impl Into<Anchor>) -> Self {
73 self.anchor = anchor.into();
85 self.anchor = anchor.into();
@@ -91,15 +103,28 @@ struct DropdownMenuState {
91 menu: Option<Entity<PopupMenu>>,
103 menu: Option<Entity<PopupMenu>>,
92}
104}
93
105
106#[derive(Default)]
107struct TriggerWidth(Rc<Cell<Pixels>>);
108
94impl<T> RenderOnce for DropdownMenuPopover<T>
109impl<T> RenderOnce for DropdownMenuPopover<T>
95where
110where
96 T: Selectable + IntoElement + 'static,
111 T: Selectable + IntoElement + 'static,
97{
112{
98 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
113 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
99 TriggerFocus::new(self.id.clone(), move |trigger_focus, window, cx| {
114 let width_key = SharedString::from(format!("{}:trigger-width", self.id));
100 self.render_popover(trigger_focus, window, cx)
115 let trigger_width = window
101 .into_any_element()
116 .use_keyed_state(width_key, cx, |_, _| TriggerWidth::default())
102 })
117 .read(cx)
118 .0
119 .clone();
120 TriggerFocus::new(
121 self.id.clone(),
122 trigger_width.clone(),
123 move |trigger_focus, window, cx| {
124 self.render_popover(trigger_focus, trigger_width, window, cx)
125 .into_any_element()
126 },
127 )
103 }
128 }
104}
129}
105
130
@@ -110,10 +135,12 @@ where
110 fn render_popover(
135 fn render_popover(
111 self,
136 self,
112 trigger_focus: FocusHandle,
137 trigger_focus: FocusHandle,
138 trigger_width: Rc<Cell<Pixels>>,
113 window: &mut Window,
139 window: &mut Window,
114 cx: &mut App,
140 cx: &mut App,
115 ) -> Popover {
141 ) -> Popover {
116 let builder = self.builder.clone();
142 let builder = self.builder.clone();
143 let listbox = self.listbox;
117 let menu_state =
144 let menu_state =
118 window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
145 window.use_keyed_state(self.id.clone(), cx, |_, _| DropdownMenuState::default());
119
146
@@ -122,6 +149,7 @@ where
122 .overlay_closable(false)
149 .overlay_closable(false)
123 .trigger(self.trigger)
150 .trigger(self.trigger)
124 .anchor(self.anchor)
151 .anchor(self.anchor)
152 .when(listbox, |this| this.offset(DROPDOWN_OFFSET))
125 .when_some(self.open, |this, open| this.open(open))
153 .when_some(self.open, |this, open| this.open(open))
126 .when_some(self.on_open_change, |this, callback| {
154 .when_some(self.on_open_change, |this, callback| {
127 this.on_open_change(move |open, window, cx| callback(open, window, cx))
155 this.on_open_change(move |open, window, cx| callback(open, window, cx))
@@ -137,7 +165,9 @@ where
137 Some(menu) => menu,
165 Some(menu) => menu,
138 None => {
166 None => {
139 let builder = builder.clone();
167 let builder = builder.clone();
168 let width = trigger_width.get();
140 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
169 let menu = PopupMenu::build(window, cx, move |menu, window, cx| {
170 let menu = if listbox { menu.listbox(width) } else { menu };
141 builder(menu, window, cx)
171 builder(menu, window, cx)
142 });
172 });
143 menu.update(cx, |menu, cx| {
173 menu.update(cx, |menu, cx| {
@@ -191,6 +221,7 @@ type TriggerFocusBuild = Box<dyn FnOnce(FocusHandle, &mut Window, &mut App) -> A
191/// the menu was not yet.
221/// the menu was not yet.
192struct TriggerFocus {
222struct TriggerFocus {
193 id: ElementId,
223 id: ElementId,
224 width: Rc<Cell<Pixels>>,
194 build: Option<TriggerFocusBuild>,
225 build: Option<TriggerFocusBuild>,
195}
226}
196
227
@@ -207,10 +238,12 @@ struct TriggerFocusFrame {
207impl TriggerFocus {
238impl TriggerFocus {
208 fn new(
239 fn new(
209 id: ElementId,
240 id: ElementId,
241 width: Rc<Cell<Pixels>>,
210 build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
242 build: impl FnOnce(FocusHandle, &mut Window, &mut App) -> AnyElement + 'static,
211 ) -> Self {
243 ) -> Self {
212 Self {
244 Self {
213 id,
245 id,
246 width,
214 build: Some(Box::new(build)),
247 build: Some(Box::new(build)),
215 }
248 }
216 }
249 }
@@ -269,11 +302,12 @@ impl Element for TriggerFocus {
269 &mut self,
302 &mut self,
270 _: Option<&GlobalElementId>,
303 _: Option<&GlobalElementId>,
271 _: Option<&InspectorElementId>,
304 _: Option<&InspectorElementId>,
272 _: gpui::Bounds<gpui::Pixels>,
305 bounds: gpui::Bounds<gpui::Pixels>,
273 frame: &mut Self::RequestLayoutState,
306 frame: &mut Self::RequestLayoutState,
274 window: &mut Window,
307 window: &mut Window,
275 cx: &mut App,
308 cx: &mut App,
276 ) {
309 ) {
310 self.width.set(bounds.size.width);
277 window.set_focus_handle(&frame.focus_handle, cx);
311 window.set_focus_handle(&frame.focus_handle, cx);
278 frame.child.prepaint(window, cx);
312 frame.child.prepaint(window, cx);
279 }
313 }
vendor/gpui-component/src/menu/menu_item.rs +10 −0
@@ -11,6 +11,7 @@ use smallvec::SmallVec;
11 11 pub(crate) struct MenuItemElement {
12 12 id: ElementId,
13 13 aria_label: Option<SharedString>,
14 debug_selector: Option<Box<dyn FnOnce() -> String>>,
14 15 style: StyleRefinement,
15 16 disabled: bool,
16 17 selected: bool,
@@ -26,6 +27,7 @@ impl MenuItemElement {
26 27 Self {
27 28 id: id.clone(),
28 29 aria_label: None,
30 debug_selector: None,
29 31 style: StyleRefinement::default(),
30 32 disabled: false,
31 33 selected: false,
@@ -47,6 +49,11 @@ impl MenuItemElement {
47 49 self
48 50 }
49 51
52 pub(crate) fn debug_selector(mut self, selector: impl FnOnce() -> String + 'static) -> Self {
53 self.debug_selector = Some(Box::new(selector));
54 self
55 }
56
50 57 /// Set the disabled state of the MenuItem.
51 58 pub(crate) fn disabled(mut self, disabled: bool) -> Self {
52 59 self.disabled = disabled;
@@ -97,6 +104,9 @@ impl RenderOnce for MenuItemElement {
97 104 .test_support()
98 105 .role(Role::MenuItem)
99 106 .when_some(self.aria_label, |this, label| this.aria_label(label))
107 .when_some(self.debug_selector, |this, selector| {
108 this.debug_selector(selector)
109 })
100 110 .aria_selected(self.selected)
101 111 .gap_x_1()
102 112 .py_1()
@@ -11,6 +11,7 @@ use smallvec::SmallVec;
11pub(crate) struct MenuItemElement {
11pub(crate) struct MenuItemElement {
12 id: ElementId,
12 id: ElementId,
13 aria_label: Option<SharedString>,
13 aria_label: Option<SharedString>,
14 debug_selector: Option<Box<dyn FnOnce() -> String>>,
14 style: StyleRefinement,
15 style: StyleRefinement,
15 disabled: bool,
16 disabled: bool,
16 selected: bool,
17 selected: bool,
@@ -26,6 +27,7 @@ impl MenuItemElement {
26 Self {
27 Self {
27 id: id.clone(),
28 id: id.clone(),
28 aria_label: None,
29 aria_label: None,
30 debug_selector: None,
29 style: StyleRefinement::default(),
31 style: StyleRefinement::default(),
30 disabled: false,
32 disabled: false,
31 selected: false,
33 selected: false,
@@ -47,6 +49,11 @@ impl MenuItemElement {
47 self
49 self
48 }
50 }
49
51
52 pub(crate) fn debug_selector(mut self, selector: impl FnOnce() -> String + 'static) -> Self {
53 self.debug_selector = Some(Box::new(selector));
54 self
55 }
56
50 /// Set the disabled state of the MenuItem.
57 /// Set the disabled state of the MenuItem.
51 pub(crate) fn disabled(mut self, disabled: bool) -> Self {
58 pub(crate) fn disabled(mut self, disabled: bool) -> Self {
52 self.disabled = disabled;
59 self.disabled = disabled;
@@ -97,6 +104,9 @@ impl RenderOnce for MenuItemElement {
97 .test_support()
104 .test_support()
98 .role(Role::MenuItem)
105 .role(Role::MenuItem)
99 .when_some(self.aria_label, |this, label| this.aria_label(label))
106 .when_some(self.aria_label, |this, label| this.aria_label(label))
107 .when_some(self.debug_selector, |this, selector| {
108 this.debug_selector(selector)
109 })
100 .aria_selected(self.selected)
110 .aria_selected(self.selected)
101 .gap_x_1()
111 .gap_x_1()
102 .py_1()
112 .py_1()
vendor/gpui-component/src/menu/mod.rs +1 −0
@@ -5,6 +5,7 @@ mod context_menu;
5 5 mod dropdown_menu;
6 6 mod menu_item;
7 7 mod popup_menu;
8 pub mod selectors;
8 9
9 10 pub use app_menu_bar::AppMenuBar;
10 11 pub use context_menu::{ContextMenu, ContextMenuExt, ContextMenuState};
@@ -5,6 +5,7 @@ mod context_menu;
5mod dropdown_menu;
5mod dropdown_menu;
6mod menu_item;
6mod menu_item;
7mod popup_menu;
7mod popup_menu;
8pub mod selectors;
8
9
9pub use app_menu_bar::AppMenuBar;
10pub use app_menu_bar::AppMenuBar;
10pub use context_menu::{ContextMenu, ContextMenuExt, ContextMenuState};
11pub use context_menu::{ContextMenu, ContextMenuExt, ContextMenuState};
vendor/gpui-component/src/menu/popup_menu.rs +101 −30
@@ -1,7 +1,13 @@
1 1 use crate::ThemeStyled as _;
2 2 use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
3 3 use crate::actions::{SelectLeft, SelectRight};
4 use crate::fluent::{
5 LISTBOX_MIN_WIDTH, MENU_DIVIDER_MARGIN_Y, MENU_ICON_GAP, MENU_ICON_GLYPH, MENU_ICON_SLOT,
6 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LABEL_INSET, MENU_LIST_PADDING,
7 OPTION_CHECK_GAP, OPTION_CHECK_INSET, OPTION_CHECK_SIZE, OPTION_PADDING_RIGHT,
8 };
4 9 use crate::menu::menu_item::MenuItemElement;
10 use crate::menu::selectors::{ITEMS_SELECTOR, icon_selector, item_selector, label_selector};
5 11 use crate::scroll::ScrollableElement;
6 12 use crate::{ActiveTheme, ElementExt, Icon, IconName, Sizable as _, h_flex, v_flex};
7 13 use crate::{Side, Size, kbd::Kbd};
@@ -300,6 +306,7 @@ pub struct PopupMenu {
300 306 bounds: Bounds<Pixels>,
301 307 size: Size,
302 308 check_side: Side,
309 listbox: bool,
303 310
304 311 /// The parent menu of this menu, if this is a submenu
305 312 parent_menu: Option<WeakEntity<Self>>,
@@ -344,6 +351,7 @@ impl PopupMenu {
344 351 max_width: None,
345 352 max_height: None,
346 353 check_side: Side::Left,
354 listbox: false,
347 355 bounds: Bounds::default(),
348 356 scrollable: false,
349 357 scroll_handle: ScrollHandle::default(),
@@ -449,6 +457,15 @@ impl PopupMenu {
449 457 self
450 458 }
451 459
460 /// Lay the menu out as a Fluent `Listbox` under a select trigger: a check
461 /// column on every row and at least the trigger's width.
462 pub fn listbox(mut self, trigger_width: Pixels) -> Self {
463 self.listbox = true;
464 self.check_side = Side::Left;
465 self.min_width = Some(trigger_width.max(LISTBOX_MIN_WIDTH));
466 self
467 }
468
452 469 /// Set the side to show check icon, default is `Side::Left`.
453 470 pub fn check_side(mut self, side: Side) -> Self {
454 471 self.check_side = side;
@@ -1151,25 +1168,37 @@ impl PopupMenu {
1151 1168 }
1152 1169
1153 1170 fn render_icon(
1171 index: usize,
1154 1172 has_icon: bool,
1155 1173 checked: bool,
1156 1174 icon: Option<Icon>,
1157 _: &mut Window,
1158 _: &mut Context<Self>,
1175 listbox: bool,
1159 1176 ) -> Option<impl IntoElement> {
1160 1177 if !has_icon {
1161 1178 return None;
1162 1179 }
1163 1180
1164 let icon = if let Some(icon) = icon {
1165 icon.clone()
1166 } else if checked {
1167 Icon::new(IconName::Check)
1181 let (slot, glyph) = if listbox {
1182 (OPTION_CHECK_SIZE, OPTION_CHECK_SIZE)
1168 1183 } else {
1169 Icon::empty()
1184 (MENU_ICON_SLOT, MENU_ICON_GLYPH)
1185 };
1186 let icon = match icon {
1187 Some(icon) if icon.has_explicit_size() => icon,
1188 Some(icon) => icon.with_size(glyph),
1189 None if checked => Icon::new(IconName::Check).with_size(glyph),
1190 None => Icon::empty().with_size(glyph),
1170 1191 };
1171 1192
1172 Some(icon.xsmall())
1193 Some(
1194 h_flex()
1195 .debug_selector(|| icon_selector(index))
1196 .size(slot)
1197 .flex_none()
1198 .items_center()
1199 .justify_center()
1200 .child(icon),
1201 )
1173 1202 }
1174 1203
1175 1204 #[inline]
@@ -1203,7 +1232,7 @@ impl PopupMenu {
1203 1232 window: &mut Window,
1204 1233 cx: &mut Context<Self>,
1205 1234 ) -> MenuItemElement {
1206 let has_left_icon = options.has_left_icon;
1235 let has_left_icon = options.has_left_icon || self.listbox;
1207 1236 let is_left_check = options.check_side.is_left() && item.is_checked();
1208 1237 let right_check_icon = if options.check_side.is_right() && item.is_checked() {
1209 1238 Some(Icon::new(IconName::Check).xsmall())
@@ -1213,20 +1242,37 @@ impl PopupMenu {
1213 1242
1214 1243 let selected = self.selected_index == Some(ix);
1215 1244 const EDGE_PADDING: Pixels = px(4.);
1216 const INNER_PADDING: Pixels = px(8.);
1245 let listbox = self.listbox;
1246 let (padding_left, padding_right, icon_gap, label_inset) = if listbox {
1247 (
1248 OPTION_CHECK_INSET,
1249 OPTION_PADDING_RIGHT,
1250 OPTION_CHECK_GAP,
1251 px(0.),
1252 )
1253 } else {
1254 (
1255 MENU_ITEM_PADDING_X,
1256 MENU_ITEM_PADDING_X,
1257 MENU_ICON_GAP,
1258 MENU_LABEL_INSET,
1259 )
1260 };
1217 1261
1218 1262 let is_submenu = matches!(item, PopupMenuItem::Submenu { .. });
1219 1263
1220 1264 let (item_height, radius) = match self.size {
1221 1265 Size::Small => (px(20.), options.radius.half()),
1222 _ => (px(26.), options.radius),
1266 _ => (MENU_ITEM_HEIGHT, options.radius),
1223 1267 };
1224 1268
1225 1269 let this = MenuItemElement::new(ix)
1270 .debug_selector(move || item_selector(ix))
1226 1271 .relative()
1227 1272 .text_sm()
1228 1273 .py_0()
1229 .px(INNER_PADDING)
1274 .pl(padding_left)
1275 .pr(padding_right)
1230 1276 .rounded(radius)
1231 1277 .items_center()
1232 1278 .selected(selected)
@@ -1251,7 +1297,7 @@ impl PopupMenu {
1251 1297 PopupMenuItem::Separator => this
1252 1298 .h_auto()
1253 1299 .p_0()
1254 .my_0p5()
1300 .my(MENU_DIVIDER_MARGIN_Y)
1255 1301 .mx_neg_1()
1256 1302 .border_b(px(1.))
1257 1303 .border_color(cx.theme().tokens.sidebar_accent)
@@ -1260,9 +1306,15 @@ impl PopupMenu {
1260 1306 h_flex()
1261 1307 .cursor_default()
1262 1308 .items_center()
1263 .gap_x_1()
1264 .children(Self::render_icon(has_left_icon, false, None, window, cx))
1265 .child(div().flex_1().child(label.clone())),
1309 .gap(icon_gap)
1310 .children(Self::render_icon(ix, has_left_icon, false, None, listbox))
1311 .child(
1312 div().flex_1().px(label_inset).child(
1313 div()
1314 .debug_selector(|| label_selector(ix))
1315 .child(label.clone()),
1316 ),
1317 ),
1266 1318 ),
1267 1319 PopupMenuItem::ElementItem {
1268 1320 render,
@@ -1281,15 +1333,21 @@ impl PopupMenu {
1281 1333 .flex_1()
1282 1334 .min_h(item_height)
1283 1335 .items_center()
1284 .gap_x_1()
1336 .gap(icon_gap)
1285 1337 .children(Self::render_icon(
1338 ix,
1286 1339 has_left_icon,
1287 1340 is_left_check,
1288 1341 icon.clone(),
1289 window,
1290 cx,
1342 listbox,
1291 1343 ))
1292 .child((render)(window, cx))
1344 .child(
1345 div().flex_1().min_w_0().px(label_inset).child(
1346 div()
1347 .debug_selector(|| label_selector(ix))
1348 .child((render)(window, cx)),
1349 ),
1350 )
1293 1351 .children(right_check_icon.map(|icon| icon.ml_3())),
1294 1352 ),
1295 1353 PopupMenuItem::Item {
@@ -1311,21 +1369,28 @@ impl PopupMenu {
1311 1369 })
1312 1370 .disabled(*disabled)
1313 1371 .h(item_height)
1314 .gap_x_1()
1372 .gap(icon_gap)
1315 1373 .children(Self::render_icon(
1374 ix,
1316 1375 has_left_icon,
1317 1376 is_left_check,
1318 1377 icon.clone(),
1319 window,
1320 cx,
1378 listbox,
1321 1379 ))
1322 1380 .child(
1323 1381 h_flex()
1324 1382 .w_full()
1383 .px(label_inset)
1325 1384 .gap_3()
1326 1385 .items_center()
1327 1386 .justify_between()
1328 .when(!show_link_icon, |this| this.child(label.clone()))
1387 .when(!show_link_icon, |this| {
1388 this.child(
1389 div()
1390 .debug_selector(|| label_selector(ix))
1391 .child(label.clone()),
1392 )
1393 })
1329 1394 .children(right_check_icon)
1330 1395 .when(show_link_icon, |this| {
1331 1396 this.child(
@@ -1358,21 +1423,26 @@ impl PopupMenu {
1358 1423 .min_h(item_height)
1359 1424 .size_full()
1360 1425 .items_center()
1361 .gap_x_1()
1426 .gap(icon_gap)
1362 1427 .children(Self::render_icon(
1428 ix,
1363 1429 has_left_icon,
1364 1430 false,
1365 1431 icon.clone(),
1366 window,
1367 cx,
1432 listbox,
1368 1433 ))
1369 1434 .child(
1370 1435 h_flex()
1371 1436 .flex_1()
1437 .px(label_inset)
1372 1438 .gap_2()
1373 1439 .items_center()
1374 1440 .justify_between()
1375 .child(label.clone())
1441 .child(
1442 div()
1443 .debug_selector(|| label_selector(ix))
1444 .child(label.clone()),
1445 )
1376 1446 .child(
1377 1447 Icon::new(IconName::ChevronRight)
1378 1448 .xsmall()
@@ -1485,8 +1555,9 @@ impl Render for PopupMenu {
1485 1555 .child(
1486 1556 v_flex()
1487 1557 .id("items")
1488 .p_1()
1489 .gap_y_0p5()
1558 .debug_selector(|| ITEMS_SELECTOR.into())
1559 .p(MENU_LIST_PADDING)
1560 .gap_y(MENU_ITEM_GAP)
1490 1561 .min_w(rems(8.))
1491 1562 .when_some(self.min_width, |this, min_width| this.min_w(min_width))
1492 1563 .max_w(max_width)
@@ -1,7 +1,13 @@
1use crate::ThemeStyled as _;
1use crate::ThemeStyled as _;
2use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
2use crate::actions::{Cancel, Confirm, SelectDown, SelectUp};
3use crate::actions::{SelectLeft, SelectRight};
3use crate::actions::{SelectLeft, SelectRight};
4use crate::fluent::{
5 LISTBOX_MIN_WIDTH, MENU_DIVIDER_MARGIN_Y, MENU_ICON_GAP, MENU_ICON_GLYPH, MENU_ICON_SLOT,
6 MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LABEL_INSET, MENU_LIST_PADDING,
7 OPTION_CHECK_GAP, OPTION_CHECK_INSET, OPTION_CHECK_SIZE, OPTION_PADDING_RIGHT,
8};
4use crate::menu::menu_item::MenuItemElement;
9use crate::menu::menu_item::MenuItemElement;
10use crate::menu::selectors::{ITEMS_SELECTOR, icon_selector, item_selector, label_selector};
5use crate::scroll::ScrollableElement;
11use crate::scroll::ScrollableElement;
6use crate::{ActiveTheme, ElementExt, Icon, IconName, Sizable as _, h_flex, v_flex};
12use crate::{ActiveTheme, ElementExt, Icon, IconName, Sizable as _, h_flex, v_flex};
7use crate::{Side, Size, kbd::Kbd};
13use crate::{Side, Size, kbd::Kbd};
@@ -300,6 +306,7 @@ pub struct PopupMenu {
300 bounds: Bounds<Pixels>,
306 bounds: Bounds<Pixels>,
301 size: Size,
307 size: Size,
302 check_side: Side,
308 check_side: Side,
309 listbox: bool,
303
310
304 /// The parent menu of this menu, if this is a submenu
311 /// The parent menu of this menu, if this is a submenu
305 parent_menu: Option<WeakEntity<Self>>,
312 parent_menu: Option<WeakEntity<Self>>,
@@ -344,6 +351,7 @@ impl PopupMenu {
344 max_width: None,
351 max_width: None,
345 max_height: None,
352 max_height: None,
346 check_side: Side::Left,
353 check_side: Side::Left,
354 listbox: false,
347 bounds: Bounds::default(),
355 bounds: Bounds::default(),
348 scrollable: false,
356 scrollable: false,
349 scroll_handle: ScrollHandle::default(),
357 scroll_handle: ScrollHandle::default(),
@@ -449,6 +457,15 @@ impl PopupMenu {
449 self
457 self
450 }
458 }
451
459
460 /// Lay the menu out as a Fluent `Listbox` under a select trigger: a check
461 /// column on every row and at least the trigger's width.
462 pub fn listbox(mut self, trigger_width: Pixels) -> Self {
463 self.listbox = true;
464 self.check_side = Side::Left;
465 self.min_width = Some(trigger_width.max(LISTBOX_MIN_WIDTH));
466 self
467 }
468
452 /// Set the side to show check icon, default is `Side::Left`.
469 /// Set the side to show check icon, default is `Side::Left`.
453 pub fn check_side(mut self, side: Side) -> Self {
470 pub fn check_side(mut self, side: Side) -> Self {
454 self.check_side = side;
471 self.check_side = side;
@@ -1151,25 +1168,37 @@ impl PopupMenu {
1151 }
1168 }
1152
1169
1153 fn render_icon(
1170 fn render_icon(
1171 index: usize,
1154 has_icon: bool,
1172 has_icon: bool,
1155 checked: bool,
1173 checked: bool,
1156 icon: Option<Icon>,
1174 icon: Option<Icon>,
1157 _: &mut Window,
1175 listbox: bool,
1158 _: &mut Context<Self>,
1159 ) -> Option<impl IntoElement> {
1176 ) -> Option<impl IntoElement> {
1160 if !has_icon {
1177 if !has_icon {
1161 return None;
1178 return None;
1162 }
1179 }
1163
1180
1164 let icon = if let Some(icon) = icon {
1181 let (slot, glyph) = if listbox {
1165 icon.clone()
1182 (OPTION_CHECK_SIZE, OPTION_CHECK_SIZE)
1166 } else if checked {
1167 Icon::new(IconName::Check)
1168 } else {
1183 } else {
1169 Icon::empty()
1184 (MENU_ICON_SLOT, MENU_ICON_GLYPH)
1185 };
1186 let icon = match icon {
1187 Some(icon) if icon.has_explicit_size() => icon,
1188 Some(icon) => icon.with_size(glyph),
1189 None if checked => Icon::new(IconName::Check).with_size(glyph),
1190 None => Icon::empty().with_size(glyph),
1170 };
1191 };
1171
1192
1172 Some(icon.xsmall())
1193 Some(
1194 h_flex()
1195 .debug_selector(|| icon_selector(index))
1196 .size(slot)
1197 .flex_none()
1198 .items_center()
1199 .justify_center()
1200 .child(icon),
1201 )
1173 }
1202 }
1174
1203
1175 #[inline]
1204 #[inline]
@@ -1203,7 +1232,7 @@ impl PopupMenu {
1203 window: &mut Window,
1232 window: &mut Window,
1204 cx: &mut Context<Self>,
1233 cx: &mut Context<Self>,
1205 ) -> MenuItemElement {
1234 ) -> MenuItemElement {
1206 let has_left_icon = options.has_left_icon;
1235 let has_left_icon = options.has_left_icon || self.listbox;
1207 let is_left_check = options.check_side.is_left() && item.is_checked();
1236 let is_left_check = options.check_side.is_left() && item.is_checked();
1208 let right_check_icon = if options.check_side.is_right() && item.is_checked() {
1237 let right_check_icon = if options.check_side.is_right() && item.is_checked() {
1209 Some(Icon::new(IconName::Check).xsmall())
1238 Some(Icon::new(IconName::Check).xsmall())
@@ -1213,20 +1242,37 @@ impl PopupMenu {
1213
1242
1214 let selected = self.selected_index == Some(ix);
1243 let selected = self.selected_index == Some(ix);
1215 const EDGE_PADDING: Pixels = px(4.);
1244 const EDGE_PADDING: Pixels = px(4.);
1216 const INNER_PADDING: Pixels = px(8.);
1245 let listbox = self.listbox;
1246 let (padding_left, padding_right, icon_gap, label_inset) = if listbox {
1247 (
1248 OPTION_CHECK_INSET,
1249 OPTION_PADDING_RIGHT,
1250 OPTION_CHECK_GAP,
1251 px(0.),
1252 )
1253 } else {
1254 (
1255 MENU_ITEM_PADDING_X,
1256 MENU_ITEM_PADDING_X,
1257 MENU_ICON_GAP,
1258 MENU_LABEL_INSET,
1259 )
1260 };
1217
1261
1218 let is_submenu = matches!(item, PopupMenuItem::Submenu { .. });
1262 let is_submenu = matches!(item, PopupMenuItem::Submenu { .. });
1219
1263
1220 let (item_height, radius) = match self.size {
1264 let (item_height, radius) = match self.size {
1221 Size::Small => (px(20.), options.radius.half()),
1265 Size::Small => (px(20.), options.radius.half()),
1222 _ => (px(26.), options.radius),
1266 _ => (MENU_ITEM_HEIGHT, options.radius),
1223 };
1267 };
1224
1268
1225 let this = MenuItemElement::new(ix)
1269 let this = MenuItemElement::new(ix)
1270 .debug_selector(move || item_selector(ix))
1226 .relative()
1271 .relative()
1227 .text_sm()
1272 .text_sm()
1228 .py_0()
1273 .py_0()
1229 .px(INNER_PADDING)
1274 .pl(padding_left)
1275 .pr(padding_right)
1230 .rounded(radius)
1276 .rounded(radius)
1231 .items_center()
1277 .items_center()
1232 .selected(selected)
1278 .selected(selected)
@@ -1251,7 +1297,7 @@ impl PopupMenu {
1251 PopupMenuItem::Separator => this
1297 PopupMenuItem::Separator => this
1252 .h_auto()
1298 .h_auto()
1253 .p_0()
1299 .p_0()
1254 .my_0p5()
1300 .my(MENU_DIVIDER_MARGIN_Y)
1255 .mx_neg_1()
1301 .mx_neg_1()
1256 .border_b(px(1.))
1302 .border_b(px(1.))
1257 .border_color(cx.theme().tokens.sidebar_accent)
1303 .border_color(cx.theme().tokens.sidebar_accent)
@@ -1260,9 +1306,15 @@ impl PopupMenu {
1260 h_flex()
1306 h_flex()
1261 .cursor_default()
1307 .cursor_default()
1262 .items_center()
1308 .items_center()
1263 .gap_x_1()
1309 .gap(icon_gap)
1264 .children(Self::render_icon(has_left_icon, false, None, window, cx))
1310 .children(Self::render_icon(ix, has_left_icon, false, None, listbox))
1265 .child(div().flex_1().child(label.clone())),
1311 .child(
1312 div().flex_1().px(label_inset).child(
1313 div()
1314 .debug_selector(|| label_selector(ix))
1315 .child(label.clone()),
1316 ),
1317 ),
1266 ),
1318 ),
1267 PopupMenuItem::ElementItem {
1319 PopupMenuItem::ElementItem {
1268 render,
1320 render,
@@ -1281,15 +1333,21 @@ impl PopupMenu {
1281 .flex_1()
1333 .flex_1()
1282 .min_h(item_height)
1334 .min_h(item_height)
1283 .items_center()
1335 .items_center()
1284 .gap_x_1()
1336 .gap(icon_gap)
1285 .children(Self::render_icon(
1337 .children(Self::render_icon(
1338 ix,
1286 has_left_icon,
1339 has_left_icon,
1287 is_left_check,
1340 is_left_check,
1288 icon.clone(),
1341 icon.clone(),
1289 window,
1342 listbox,
1290 cx,
1291 ))
1343 ))
1292 .child((render)(window, cx))
1344 .child(
1345 div().flex_1().min_w_0().px(label_inset).child(
1346 div()
1347 .debug_selector(|| label_selector(ix))
1348 .child((render)(window, cx)),
1349 ),
1350 )
1293 .children(right_check_icon.map(|icon| icon.ml_3())),
1351 .children(right_check_icon.map(|icon| icon.ml_3())),
1294 ),
1352 ),
1295 PopupMenuItem::Item {
1353 PopupMenuItem::Item {
@@ -1311,21 +1369,28 @@ impl PopupMenu {
1311 })
1369 })
1312 .disabled(*disabled)
1370 .disabled(*disabled)
1313 .h(item_height)
1371 .h(item_height)
1314 .gap_x_1()
1372 .gap(icon_gap)
1315 .children(Self::render_icon(
1373 .children(Self::render_icon(
1374 ix,
1316 has_left_icon,
1375 has_left_icon,
1317 is_left_check,
1376 is_left_check,
1318 icon.clone(),
1377 icon.clone(),
1319 window,
1378 listbox,
1320 cx,
1321 ))
1379 ))
1322 .child(
1380 .child(
1323 h_flex()
1381 h_flex()
1324 .w_full()
1382 .w_full()
1383 .px(label_inset)
1325 .gap_3()
1384 .gap_3()
1326 .items_center()
1385 .items_center()
1327 .justify_between()
1386 .justify_between()
1328 .when(!show_link_icon, |this| this.child(label.clone()))
1387 .when(!show_link_icon, |this| {
1388 this.child(
1389 div()
1390 .debug_selector(|| label_selector(ix))
1391 .child(label.clone()),
1392 )
1393 })
1329 .children(right_check_icon)
1394 .children(right_check_icon)
1330 .when(show_link_icon, |this| {
1395 .when(show_link_icon, |this| {
1331 this.child(
1396 this.child(
@@ -1358,21 +1423,26 @@ impl PopupMenu {
1358 .min_h(item_height)
1423 .min_h(item_height)
1359 .size_full()
1424 .size_full()
1360 .items_center()
1425 .items_center()
1361 .gap_x_1()
1426 .gap(icon_gap)
1362 .children(Self::render_icon(
1427 .children(Self::render_icon(
1428 ix,
1363 has_left_icon,
1429 has_left_icon,
1364 false,
1430 false,
1365 icon.clone(),
1431 icon.clone(),
1366 window,
1432 listbox,
1367 cx,
1368 ))
1433 ))
1369 .child(
1434 .child(
1370 h_flex()
1435 h_flex()
1371 .flex_1()
1436 .flex_1()
1437 .px(label_inset)
1372 .gap_2()
1438 .gap_2()
1373 .items_center()
1439 .items_center()
1374 .justify_between()
1440 .justify_between()
1375 .child(label.clone())
1441 .child(
1442 div()
1443 .debug_selector(|| label_selector(ix))
1444 .child(label.clone()),
1445 )
1376 .child(
1446 .child(
1377 Icon::new(IconName::ChevronRight)
1447 Icon::new(IconName::ChevronRight)
1378 .xsmall()
1448 .xsmall()
@@ -1485,8 +1555,9 @@ impl Render for PopupMenu {
1485 .child(
1555 .child(
1486 v_flex()
1556 v_flex()
1487 .id("items")
1557 .id("items")
1488 .p_1()
1558 .debug_selector(|| ITEMS_SELECTOR.into())
1489 .gap_y_0p5()
1559 .p(MENU_LIST_PADDING)
1560 .gap_y(MENU_ITEM_GAP)
1490 .min_w(rems(8.))
1561 .min_w(rems(8.))
1491 .when_some(self.min_width, |this, min_width| this.min_w(min_width))
1562 .when_some(self.min_width, |this, min_width| this.min_w(min_width))
1492 .max_w(max_width)
1563 .max_w(max_width)
vendor/gpui-component/src/menu/selectors.rs added +13 −0
@@ -0,0 +1,13 @@
1 pub const ITEMS_SELECTOR: &str = "popup-menu/items";
2
3 pub fn item_selector(index: usize) -> String {
4 format!("popup-menu/item-{index}")
5 }
6
7 pub fn icon_selector(index: usize) -> String {
8 format!("popup-menu/item-{index}/icon")
9 }
10
11 pub fn label_selector(index: usize) -> String {
12 format!("popup-menu/item-{index}/label")
13 }
@@ -0,0 +1,13 @@
1pub const ITEMS_SELECTOR: &str = "popup-menu/items";
2
3pub fn item_selector(index: usize) -> String {
4 format!("popup-menu/item-{index}")
5}
6
7pub fn icon_selector(index: usize) -> String {
8 format!("popup-menu/item-{index}/icon")
9}
10
11pub fn label_selector(index: usize) -> String {
12 format!("popup-menu/item-{index}/label")
13}
vendor/gpui-component/src/notification.rs +17 −4
@@ -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
22use crate::fluent::{TOAST_ICON_GAP, TOAST_ICON_SIZE, TOAST_LINE_HEIGHT};
22use crate::{
23use 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);
30const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);
31const NOTIFICATION_EXIT_DURATION: Duration = Duration::from_millis(200);
31const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);
32const NOTIFICATION_TRANSITION_OFFSET: Pixels = px(96.);
32const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);
33const DEFAULT_NOTIFICATION_WIDTH: Pixels = px(382.);
34const TOAST_PADDING_X: Pixels = px(16.);
35const TOAST_PADDING_Y: Pixels = px(14.);
33const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);
36const NOTIFICATION_ADVANCE_INTERVAL: Duration = Duration::from_millis(50);
34struct DismissRequest;
37struct 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 })
vendor/gpui-component/src/popover.rs +1 −1
@@ -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