BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/importance

- urgent still bypasses DND and the new account notification rules
- delivery menu uses the shared Fluent menu metrics
- importance label line height follows compact density
- touch_scroll test rows flex_none so layout_guard stays green

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
588d804676434fe5dcb1b272cad938e90de26b37
97 files changed +8578 −400
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 importance: Default::default(),
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 importance: Default::default(),
580 importance: Default::default(),
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)]
@@ -142,6 +143,9 @@ pub struct AppState {
142 143 pub recording_policy: teams_core::RecordingPolicy,
143 144 pub allow_priority_messages: bool,
144 145 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
146 pub chat_settings: teams_core::ChatSettingsDocument,
147 pub markdown_mode: bool,
148 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
145 149 pub own_tenant: Option<String>,
146 150 pub call_share_motion: bool,
147 151 pub call_share_standout: bool,
@@ -233,6 +237,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
233 237 impl AppState {
234 238 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
235 239 let sidebar = store.sidebar().unwrap_or_default();
240 let chat_settings = teams_core::stored_chat_settings(&store);
241 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
236 242 let mut state = AppState {
237 243 store,
238 244 engine: None,
@@ -297,6 +303,9 @@ impl AppState {
297 303 recording_policy: teams_core::RecordingPolicy::default(),
298 304 allow_priority_messages: true,
299 305 account_sounds: None,
306 chat_settings,
307 markdown_mode,
308 demo_chat_desktop: HashMap::new(),
300 309 own_tenant: None,
301 310 call_share_motion: false,
302 311 call_share_standout: false,
@@ -1003,6 +1012,7 @@ impl AppState {
1003 1012 self.refresh_recording_policy(cx);
1004 1013 self.refresh_messaging_policy(cx);
1005 1014 self.refresh_sound_settings(cx);
1015 self.refresh_chat_settings(cx);
1006 1016 let waiting = self.directory.waiting_presence_ids();
1007 1017 self.request_presence(waiting, cx);
1008 1018 self.refresh_own_status(cx);
@@ -73,6 +73,7 @@ pub enum AppEvent {
73 MeetingChime,
73 MeetingChime,
74 CallTone(chatsvc::sounds::CallTone),
74 CallTone(chatsvc::sounds::CallTone),
75 SoundSettings,
75 SoundSettings,
76 ChatSettings,
76}
77}
77
78
78#[derive(Debug, Clone, Copy, Default)]
79#[derive(Debug, Clone, Copy, Default)]
@@ -142,6 +143,9 @@ pub struct AppState {
142 pub recording_policy: teams_core::RecordingPolicy,
143 pub recording_policy: teams_core::RecordingPolicy,
143 pub allow_priority_messages: bool,
144 pub allow_priority_messages: bool,
144 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
145 pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
146 pub chat_settings: teams_core::ChatSettingsDocument,
147 pub markdown_mode: bool,
148 pub demo_chat_desktop: HashMap<String, teams_core::DesktopNotifications>,
145 pub own_tenant: Option<String>,
149 pub own_tenant: Option<String>,
146 pub call_share_motion: bool,
150 pub call_share_motion: bool,
147 pub call_share_standout: bool,
151 pub call_share_standout: bool,
@@ -233,6 +237,8 @@ pub fn selection_title(sidebar: &Sidebar, selection: &Selection) -> String {
233impl AppState {
237impl AppState {
234 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
238 pub fn new(store: Arc<Store>, mode: Mode) -> Self {
235 let sidebar = store.sidebar().unwrap_or_default();
239 let sidebar = store.sidebar().unwrap_or_default();
240 let chat_settings = teams_core::stored_chat_settings(&store);
241 let markdown_mode = crate::chat_settings_actions::stored_markdown_mode(&store);
236 let mut state = AppState {
242 let mut state = AppState {
237 store,
243 store,
238 engine: None,
244 engine: None,
@@ -297,6 +303,9 @@ impl AppState {
297 recording_policy: teams_core::RecordingPolicy::default(),
303 recording_policy: teams_core::RecordingPolicy::default(),
298 allow_priority_messages: true,
304 allow_priority_messages: true,
299 account_sounds: None,
305 account_sounds: None,
306 chat_settings,
307 markdown_mode,
308 demo_chat_desktop: HashMap::new(),
300 own_tenant: None,
309 own_tenant: None,
301 call_share_motion: false,
310 call_share_motion: false,
302 call_share_standout: false,
311 call_share_standout: false,
@@ -1003,6 +1012,7 @@ impl AppState {
1003 self.refresh_recording_policy(cx);
1012 self.refresh_recording_policy(cx);
1004 self.refresh_messaging_policy(cx);
1013 self.refresh_messaging_policy(cx);
1005 self.refresh_sound_settings(cx);
1014 self.refresh_sound_settings(cx);
1015 self.refresh_chat_settings(cx);
1006 let waiting = self.directory.waiting_presence_ids();
1016 let waiting = self.directory.waiting_presence_ids();
1007 self.request_presence(waiting, cx);
1017 self.request_presence(waiting, cx);
1008 self.refresh_own_status(cx);
1018 self.refresh_own_status(cx);
crates/app-state/src/channel_menu.rs added +462 −0
@@ -0,0 +1,462 @@
1 use std::future::Future;
2
3 use gpui_kit::*;
4
5 use crate::app_state::AppState;
6 use crate::sidebar_model::channel_shown;
7
8 pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
9 pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12 pub enum ChannelMenuItem {
13 Notifications,
14 Pin,
15 Unpin,
16 Show,
17 Hide,
18 CopyLink,
19 }
20
21 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
22 pub enum TeamMenuItem {
23 Show,
24 Hide,
25 CopyLink,
26 }
27
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 pub enum MenuEntry<Item> {
30 Item(Item),
31 Separator,
32 }
33
34 impl ChannelMenuItem {
35 pub fn label(self) -> &'static str {
36 match self {
37 ChannelMenuItem::Notifications => "Notifications",
38 ChannelMenuItem::Pin => "Pin",
39 ChannelMenuItem::Unpin => "Unpin",
40 ChannelMenuItem::Show => "Show",
41 ChannelMenuItem::Hide => "Hide",
42 ChannelMenuItem::CopyLink => "Copy link",
43 }
44 }
45 }
46
47 impl TeamMenuItem {
48 pub fn label(self) -> &'static str {
49 match self {
50 TeamMenuItem::Show => "Show",
51 TeamMenuItem::Hide => "Hide",
52 TeamMenuItem::CopyLink => "Copy link",
53 }
54 }
55 }
56
57 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
58 pub struct ChannelMenuState {
59 pub pinned: bool,
60 pub shown: bool,
61 }
62
63 impl ChannelMenuState {
64 pub fn disables(self, item: ChannelMenuItem) -> bool {
65 item == ChannelMenuItem::Hide && self.pinned
66 }
67 }
68
69 pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
70 vec![
71 MenuEntry::Item(ChannelMenuItem::Notifications),
72 MenuEntry::Item(if state.pinned {
73 ChannelMenuItem::Unpin
74 } else {
75 ChannelMenuItem::Pin
76 }),
77 MenuEntry::Item(if state.shown {
78 ChannelMenuItem::Hide
79 } else {
80 ChannelMenuItem::Show
81 }),
82 MenuEntry::Separator,
83 MenuEntry::Item(ChannelMenuItem::CopyLink),
84 ]
85 }
86
87 pub fn team_menu_entries(hidden: bool) -> Vec<MenuEntry<TeamMenuItem>> {
88 vec![
89 MenuEntry::Item(if hidden {
90 TeamMenuItem::Show
91 } else {
92 TeamMenuItem::Hide
93 }),
94 MenuEntry::Separator,
95 MenuEntry::Item(TeamMenuItem::CopyLink),
96 ]
97 }
98
99 pub fn pin_failure(pinned: bool) -> &'static str {
100 if pinned {
101 "We couldn't pin the channel."
102 } else {
103 "We couldn't unpin the channel."
104 }
105 }
106
107 pub fn channel_visibility_failure(shown: bool) -> &'static str {
108 if shown {
109 "We couldn't show the channel."
110 } else {
111 "We couldn't hide the channel."
112 }
113 }
114
115 pub fn team_visibility_failure(shown: bool) -> &'static str {
116 if shown {
117 "We couldn't show the team."
118 } else {
119 "We couldn't hide the team."
120 }
121 }
122
123 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
124 pub struct PostPinDialog {
125 pub title: &'static str,
126 pub body: &'static str,
127 pub confirm: &'static str,
128 }
129
130 pub fn post_pin_dialog(pin: bool) -> PostPinDialog {
131 if pin {
132 PostPinDialog {
133 title: "Pin in channel",
134 body: "The message will be pinned for everyone who views the channel.",
135 confirm: "Pin",
136 }
137 } else {
138 PostPinDialog {
139 title: "Unpin this message?",
140 body: "The message will be unpinned for everyone who views the channel.",
141 confirm: "Unpin",
142 }
143 }
144 }
145
146 pub fn post_pin_notice(pin: bool) -> &'static str {
147 if pin { "Post pinned" } else { "Post unpinned" }
148 }
149
150 pub fn post_pin_failure(pin: bool) -> &'static str {
151 if pin {
152 "We couldn't pin the post."
153 } else {
154 "We couldn't unpin the post."
155 }
156 }
157
158 impl AppState {
159 pub fn channel_menu_state(&self, channel_id: &str) -> ChannelMenuState {
160 ChannelMenuState {
161 pinned: self.channel_pinned(channel_id),
162 shown: self
163 .sidebar
164 .teams
165 .iter()
166 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
167 .is_none_or(|team| channel_shown(team, channel_id)),
168 }
169 }
170
171 pub fn channel_pinned(&self, channel_id: &str) -> bool {
172 self.directory
173 .pinned_channels
174 .iter()
175 .any(|id| id == channel_id)
176 }
177
178 pub fn set_channel_pinned(&mut self, channel_id: &str, pinned: bool, cx: &mut Context<Self>) {
179 if self.channel_pinned(channel_id) == pinned {
180 return;
181 }
182 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
183 return;
184 };
185 let previous = self.directory.pinned_channels.clone();
186 let mut changed = previous.clone();
187 changed.retain(|id| id != channel_id);
188 if pinned {
189 changed.push(channel_id.to_owned());
190 }
191 self.apply_pinned_channels(changed, cx);
192 let Some(engine) = engine_or_demo else {
193 return;
194 };
195 let owned_id = channel_id.to_owned();
196 self.run_channel_action(
197 pin_failure(pinned),
198 async move { engine.set_channel_pinned(&owned_id, pinned).await },
199 move |state, cx| state.apply_pinned_channels(previous, cx),
200 None,
201 cx,
202 );
203 }
204
205 fn apply_pinned_channels(&mut self, channel_ids: Vec<String>, cx: &mut Context<Self>) {
206 let _ = self.store.replace_pinned_channels(&channel_ids);
207 self.directory.pinned_channels = channel_ids;
208 cx.emit(crate::app_state::AppEvent::Sidebar);
209 cx.notify();
210 }
211
212 pub fn set_channel_shown(&mut self, channel_id: &str, shown: bool, cx: &mut Context<Self>) {
213 if !shown && self.channel_pinned(channel_id) {
214 self.raise_notice(PINNED_CHANNEL_CANNOT_HIDE.to_owned(), None, cx);
215 return;
216 }
217 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
218 return;
219 };
220 let _ = self.store.set_channel_hidden(channel_id, !shown);
221 self.reload_sidebar(cx);
222 let Some(engine) = engine_or_demo else {
223 return;
224 };
225 let owned_id = channel_id.to_owned();
226 let revert_id = owned_id.clone();
227 self.run_channel_action(
228 channel_visibility_failure(shown),
229 async move { engine.set_channel_shown(&owned_id, shown).await },
230 move |state, cx| {
231 let _ = state.store.set_channel_hidden(&revert_id, shown);
232 state.reload_sidebar(cx);
233 },
234 None,
235 cx,
236 );
237 }
238
239 pub fn set_team_shown(&mut self, team_id: &str, shown: bool, cx: &mut Context<Self>) {
240 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
241 return;
242 };
243 let _ = self.store.set_team_hidden(team_id, !shown);
244 self.reload_sidebar(cx);
245 let Some(engine) = engine_or_demo else {
246 return;
247 };
248 let owned_id = team_id.to_owned();
249 let revert_id = owned_id.clone();
250 self.run_channel_action(
251 team_visibility_failure(shown),
252 async move { engine.set_team_shown(&owned_id, shown).await },
253 move |state, cx| {
254 let _ = state.store.set_team_hidden(&revert_id, shown);
255 state.reload_sidebar(cx);
256 },
257 None,
258 cx,
259 );
260 }
261
262 pub fn copy_channel_link(&mut self, channel_id: &str, cx: &mut Context<Self>) {
263 let Some(engine) = self.engine.clone() else {
264 if self.mode.demo {
265 let link = teams_core::channel_link(&teams_core::ChannelAddress {
266 tenant_id: crate::demo::DEMO_TENANT_ID.to_owned(),
267 group_id: self.channel_team_id(channel_id).unwrap_or_default(),
268 channel_id: channel_id.to_owned(),
269 channel_name: self.channel_name(channel_id).unwrap_or_default(),
270 membership_type: None,
271 });
272 self.copy_link(link, cx);
273 }
274 return;
275 };
276 let owned_id = channel_id.to_owned();
277 self.copy_link_from(async move { engine.channel_link(&owned_id).await }, cx);
278 }
279
280 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
281 let Some(engine) = self.engine.clone() else {
282 if self.mode.demo {
283 let team_thread_id = self.store.team_thread_id(team_id).ok().flatten();
284 let link = teams_core::team_link(
285 team_thread_id.as_deref().unwrap_or(team_id),
286 team_id,
287 crate::demo::DEMO_TENANT_ID,
288 );
289 self.copy_link(link, cx);
290 }
291 return;
292 };
293 let owned_id = team_id.to_owned();
294 self.copy_link_from(async move { engine.team_link(&owned_id).await }, cx);
295 }
296
297 fn channel_team_id(&self, channel_id: &str) -> Option<String> {
298 self.sidebar.teams.iter().find_map(|team| {
299 team.channels
300 .iter()
301 .any(|channel| channel.id == channel_id)
302 .then(|| team.team.id.clone())
303 })
304 }
305
306 pub fn channel_name(&self, channel_id: &str) -> Option<String> {
307 self.sidebar
308 .teams
309 .iter()
310 .flat_map(|team| &team.channels)
311 .find(|channel| channel.id == channel_id)
312 .map(|channel| channel.name.clone())
313 }
314
315 fn copy_link(&mut self, link: String, cx: &mut Context<Self>) {
316 cx.write_to_clipboard(ClipboardItem::new_string(link));
317 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
318 }
319
320 fn copy_link_from(
321 &mut self,
322 call: impl Future<Output = teams_core::Result<String>> + Send + 'static,
323 cx: &mut Context<Self>,
324 ) {
325 let receiver = crate::runtime::spawn(call);
326 cx.spawn(async move |this, cx| {
327 let outcome = match receiver.await {
328 Ok(Ok(link)) => Ok(link),
329 Ok(Err(error)) => Err(crate::notice::short_error(&error)),
330 Err(_) => Err("cancelled".to_owned()),
331 };
332 this.update(cx, |state, cx| match outcome {
333 Ok(link) => state.copy_link(link, cx),
334 Err(reason) => state.raise_notice(format!("Copy link failed: {reason}"), None, cx),
335 })
336 .ok();
337 })
338 .detach();
339 }
340
341 pub(crate) fn run_channel_action(
342 &mut self,
343 failure: &'static str,
344 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
345 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
346 success: Option<&'static str>,
347 cx: &mut Context<Self>,
348 ) {
349 let receiver = crate::runtime::spawn(call);
350 cx.spawn(async move |this, cx| {
351 let failed = !matches!(receiver.await, Ok(Ok(())));
352 this.update(cx, |state, cx| {
353 if failed {
354 revert(state, cx);
355 state.raise_notice(failure.to_owned(), None, cx);
356 } else if let Some(text) = success {
357 state.raise_notice(text.to_owned(), None, cx);
358 }
359 })
360 .ok();
361 })
362 .detach();
363 }
364 }
365
366 #[cfg(test)]
367 mod tests {
368 use super::{
369 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, channel_menu_entries,
370 channel_visibility_failure, pin_failure, post_pin_dialog, post_pin_failure,
371 post_pin_notice, team_menu_entries, team_visibility_failure,
372 };
373
374 fn labels<Item: Copy>(
375 entries: &[MenuEntry<Item>],
376 label: impl Fn(Item) -> &'static str,
377 ) -> Vec<&'static str> {
378 entries
379 .iter()
380 .map(|entry| match entry {
381 MenuEntry::Item(item) => label(*item),
382 MenuEntry::Separator => "-",
383 })
384 .collect()
385 }
386
387 #[test]
388 fn channel_menu_follows_teams_order() {
389 let shown = channel_menu_entries(ChannelMenuState {
390 pinned: false,
391 shown: true,
392 });
393 assert_eq!(
394 labels(&shown, ChannelMenuItem::label),
395 ["Notifications", "Pin", "Hide", "-", "Copy link"]
396 );
397 let hidden_pinned = channel_menu_entries(ChannelMenuState {
398 pinned: true,
399 shown: false,
400 });
401 assert_eq!(
402 labels(&hidden_pinned, ChannelMenuItem::label),
403 ["Notifications", "Unpin", "Show", "-", "Copy link"]
404 );
405 }
406
407 #[test]
408 fn pinned_channels_cannot_be_hidden() {
409 let pinned = ChannelMenuState {
410 pinned: true,
411 shown: true,
412 };
413 assert!(pinned.disables(ChannelMenuItem::Hide));
414 assert!(!pinned.disables(ChannelMenuItem::Unpin));
415 let unpinned = ChannelMenuState {
416 pinned: false,
417 shown: true,
418 };
419 assert!(!unpinned.disables(ChannelMenuItem::Hide));
420 }
421
422 #[test]
423 fn team_menu_switches_between_show_and_hide() {
424 assert_eq!(
425 labels(&team_menu_entries(false), TeamMenuItem::label),
426 ["Hide", "-", "Copy link"]
427 );
428 assert_eq!(
429 labels(&team_menu_entries(true), TeamMenuItem::label),
430 ["Show", "-", "Copy link"]
431 );
432 }
433
434 #[test]
435 fn post_pin_dialogs_and_notices_use_teams_strings() {
436 let unpin = post_pin_dialog(false);
437 assert_eq!(unpin.title, "Unpin this message?");
438 assert_eq!(
439 unpin.body,
440 "The message will be unpinned for everyone who views the channel."
441 );
442 assert_eq!(unpin.confirm, "Unpin");
443 let pin = post_pin_dialog(true);
444 assert_eq!(pin.title, "Pin in channel");
445 assert_eq!(pin.confirm, "Pin");
446 assert_eq!(post_pin_notice(true), "Post pinned");
447 assert_eq!(post_pin_notice(false), "Post unpinned");
448 assert_eq!(post_pin_failure(true), "We couldn't pin the post.");
449 assert_eq!(post_pin_failure(false), "We couldn't unpin the post.");
450 }
451
452 #[test]
453 fn failures_use_teams_strings() {
454 assert_eq!(pin_failure(true), "We couldn't pin the channel.");
455 assert_eq!(pin_failure(false), "We couldn't unpin the channel.");
456 assert_eq!(
457 channel_visibility_failure(false),
458 "We couldn't hide the channel."
459 );
460 assert_eq!(team_visibility_failure(true), "We couldn't show the team.");
461 }
462 }
@@ -0,0 +1,462 @@
1use std::future::Future;
2
3use gpui_kit::*;
4
5use crate::app_state::AppState;
6use crate::sidebar_model::channel_shown;
7
8pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
9pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum ChannelMenuItem {
13 Notifications,
14 Pin,
15 Unpin,
16 Show,
17 Hide,
18 CopyLink,
19}
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum TeamMenuItem {
23 Show,
24 Hide,
25 CopyLink,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum MenuEntry<Item> {
30 Item(Item),
31 Separator,
32}
33
34impl ChannelMenuItem {
35 pub fn label(self) -> &'static str {
36 match self {
37 ChannelMenuItem::Notifications => "Notifications",
38 ChannelMenuItem::Pin => "Pin",
39 ChannelMenuItem::Unpin => "Unpin",
40 ChannelMenuItem::Show => "Show",
41 ChannelMenuItem::Hide => "Hide",
42 ChannelMenuItem::CopyLink => "Copy link",
43 }
44 }
45}
46
47impl TeamMenuItem {
48 pub fn label(self) -> &'static str {
49 match self {
50 TeamMenuItem::Show => "Show",
51 TeamMenuItem::Hide => "Hide",
52 TeamMenuItem::CopyLink => "Copy link",
53 }
54 }
55}
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct ChannelMenuState {
59 pub pinned: bool,
60 pub shown: bool,
61}
62
63impl ChannelMenuState {
64 pub fn disables(self, item: ChannelMenuItem) -> bool {
65 item == ChannelMenuItem::Hide && self.pinned
66 }
67}
68
69pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
70 vec![
71 MenuEntry::Item(ChannelMenuItem::Notifications),
72 MenuEntry::Item(if state.pinned {
73 ChannelMenuItem::Unpin
74 } else {
75 ChannelMenuItem::Pin
76 }),
77 MenuEntry::Item(if state.shown {
78 ChannelMenuItem::Hide
79 } else {
80 ChannelMenuItem::Show
81 }),
82 MenuEntry::Separator,
83 MenuEntry::Item(ChannelMenuItem::CopyLink),
84 ]
85}
86
87pub fn team_menu_entries(hidden: bool) -> Vec<MenuEntry<TeamMenuItem>> {
88 vec![
89 MenuEntry::Item(if hidden {
90 TeamMenuItem::Show
91 } else {
92 TeamMenuItem::Hide
93 }),
94 MenuEntry::Separator,
95 MenuEntry::Item(TeamMenuItem::CopyLink),
96 ]
97}
98
99pub fn pin_failure(pinned: bool) -> &'static str {
100 if pinned {
101 "We couldn't pin the channel."
102 } else {
103 "We couldn't unpin the channel."
104 }
105}
106
107pub fn channel_visibility_failure(shown: bool) -> &'static str {
108 if shown {
109 "We couldn't show the channel."
110 } else {
111 "We couldn't hide the channel."
112 }
113}
114
115pub fn team_visibility_failure(shown: bool) -> &'static str {
116 if shown {
117 "We couldn't show the team."
118 } else {
119 "We couldn't hide the team."
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub struct PostPinDialog {
125 pub title: &'static str,
126 pub body: &'static str,
127 pub confirm: &'static str,
128}
129
130pub fn post_pin_dialog(pin: bool) -> PostPinDialog {
131 if pin {
132 PostPinDialog {
133 title: "Pin in channel",
134 body: "The message will be pinned for everyone who views the channel.",
135 confirm: "Pin",
136 }
137 } else {
138 PostPinDialog {
139 title: "Unpin this message?",
140 body: "The message will be unpinned for everyone who views the channel.",
141 confirm: "Unpin",
142 }
143 }
144}
145
146pub fn post_pin_notice(pin: bool) -> &'static str {
147 if pin { "Post pinned" } else { "Post unpinned" }
148}
149
150pub fn post_pin_failure(pin: bool) -> &'static str {
151 if pin {
152 "We couldn't pin the post."
153 } else {
154 "We couldn't unpin the post."
155 }
156}
157
158impl AppState {
159 pub fn channel_menu_state(&self, channel_id: &str) -> ChannelMenuState {
160 ChannelMenuState {
161 pinned: self.channel_pinned(channel_id),
162 shown: self
163 .sidebar
164 .teams
165 .iter()
166 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
167 .is_none_or(|team| channel_shown(team, channel_id)),
168 }
169 }
170
171 pub fn channel_pinned(&self, channel_id: &str) -> bool {
172 self.directory
173 .pinned_channels
174 .iter()
175 .any(|id| id == channel_id)
176 }
177
178 pub fn set_channel_pinned(&mut self, channel_id: &str, pinned: bool, cx: &mut Context<Self>) {
179 if self.channel_pinned(channel_id) == pinned {
180 return;
181 }
182 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
183 return;
184 };
185 let previous = self.directory.pinned_channels.clone();
186 let mut changed = previous.clone();
187 changed.retain(|id| id != channel_id);
188 if pinned {
189 changed.push(channel_id.to_owned());
190 }
191 self.apply_pinned_channels(changed, cx);
192 let Some(engine) = engine_or_demo else {
193 return;
194 };
195 let owned_id = channel_id.to_owned();
196 self.run_channel_action(
197 pin_failure(pinned),
198 async move { engine.set_channel_pinned(&owned_id, pinned).await },
199 move |state, cx| state.apply_pinned_channels(previous, cx),
200 None,
201 cx,
202 );
203 }
204
205 fn apply_pinned_channels(&mut self, channel_ids: Vec<String>, cx: &mut Context<Self>) {
206 let _ = self.store.replace_pinned_channels(&channel_ids);
207 self.directory.pinned_channels = channel_ids;
208 cx.emit(crate::app_state::AppEvent::Sidebar);
209 cx.notify();
210 }
211
212 pub fn set_channel_shown(&mut self, channel_id: &str, shown: bool, cx: &mut Context<Self>) {
213 if !shown && self.channel_pinned(channel_id) {
214 self.raise_notice(PINNED_CHANNEL_CANNOT_HIDE.to_owned(), None, cx);
215 return;
216 }
217 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
218 return;
219 };
220 let _ = self.store.set_channel_hidden(channel_id, !shown);
221 self.reload_sidebar(cx);
222 let Some(engine) = engine_or_demo else {
223 return;
224 };
225 let owned_id = channel_id.to_owned();
226 let revert_id = owned_id.clone();
227 self.run_channel_action(
228 channel_visibility_failure(shown),
229 async move { engine.set_channel_shown(&owned_id, shown).await },
230 move |state, cx| {
231 let _ = state.store.set_channel_hidden(&revert_id, shown);
232 state.reload_sidebar(cx);
233 },
234 None,
235 cx,
236 );
237 }
238
239 pub fn set_team_shown(&mut self, team_id: &str, shown: bool, cx: &mut Context<Self>) {
240 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
241 return;
242 };
243 let _ = self.store.set_team_hidden(team_id, !shown);
244 self.reload_sidebar(cx);
245 let Some(engine) = engine_or_demo else {
246 return;
247 };
248 let owned_id = team_id.to_owned();
249 let revert_id = owned_id.clone();
250 self.run_channel_action(
251 team_visibility_failure(shown),
252 async move { engine.set_team_shown(&owned_id, shown).await },
253 move |state, cx| {
254 let _ = state.store.set_team_hidden(&revert_id, shown);
255 state.reload_sidebar(cx);
256 },
257 None,
258 cx,
259 );
260 }
261
262 pub fn copy_channel_link(&mut self, channel_id: &str, cx: &mut Context<Self>) {
263 let Some(engine) = self.engine.clone() else {
264 if self.mode.demo {
265 let link = teams_core::channel_link(&teams_core::ChannelAddress {
266 tenant_id: crate::demo::DEMO_TENANT_ID.to_owned(),
267 group_id: self.channel_team_id(channel_id).unwrap_or_default(),
268 channel_id: channel_id.to_owned(),
269 channel_name: self.channel_name(channel_id).unwrap_or_default(),
270 membership_type: None,
271 });
272 self.copy_link(link, cx);
273 }
274 return;
275 };
276 let owned_id = channel_id.to_owned();
277 self.copy_link_from(async move { engine.channel_link(&owned_id).await }, cx);
278 }
279
280 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
281 let Some(engine) = self.engine.clone() else {
282 if self.mode.demo {
283 let team_thread_id = self.store.team_thread_id(team_id).ok().flatten();
284 let link = teams_core::team_link(
285 team_thread_id.as_deref().unwrap_or(team_id),
286 team_id,
287 crate::demo::DEMO_TENANT_ID,
288 );
289 self.copy_link(link, cx);
290 }
291 return;
292 };
293 let owned_id = team_id.to_owned();
294 self.copy_link_from(async move { engine.team_link(&owned_id).await }, cx);
295 }
296
297 fn channel_team_id(&self, channel_id: &str) -> Option<String> {
298 self.sidebar.teams.iter().find_map(|team| {
299 team.channels
300 .iter()
301 .any(|channel| channel.id == channel_id)
302 .then(|| team.team.id.clone())
303 })
304 }
305
306 pub fn channel_name(&self, channel_id: &str) -> Option<String> {
307 self.sidebar
308 .teams
309 .iter()
310 .flat_map(|team| &team.channels)
311 .find(|channel| channel.id == channel_id)
312 .map(|channel| channel.name.clone())
313 }
314
315 fn copy_link(&mut self, link: String, cx: &mut Context<Self>) {
316 cx.write_to_clipboard(ClipboardItem::new_string(link));
317 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
318 }
319
320 fn copy_link_from(
321 &mut self,
322 call: impl Future<Output = teams_core::Result<String>> + Send + 'static,
323 cx: &mut Context<Self>,
324 ) {
325 let receiver = crate::runtime::spawn(call);
326 cx.spawn(async move |this, cx| {
327 let outcome = match receiver.await {
328 Ok(Ok(link)) => Ok(link),
329 Ok(Err(error)) => Err(crate::notice::short_error(&error)),
330 Err(_) => Err("cancelled".to_owned()),
331 };
332 this.update(cx, |state, cx| match outcome {
333 Ok(link) => state.copy_link(link, cx),
334 Err(reason) => state.raise_notice(format!("Copy link failed: {reason}"), None, cx),
335 })
336 .ok();
337 })
338 .detach();
339 }
340
341 pub(crate) fn run_channel_action(
342 &mut self,
343 failure: &'static str,
344 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
345 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
346 success: Option<&'static str>,
347 cx: &mut Context<Self>,
348 ) {
349 let receiver = crate::runtime::spawn(call);
350 cx.spawn(async move |this, cx| {
351 let failed = !matches!(receiver.await, Ok(Ok(())));
352 this.update(cx, |state, cx| {
353 if failed {
354 revert(state, cx);
355 state.raise_notice(failure.to_owned(), None, cx);
356 } else if let Some(text) = success {
357 state.raise_notice(text.to_owned(), None, cx);
358 }
359 })
360 .ok();
361 })
362 .detach();
363 }
364}
365
366#[cfg(test)]
367mod tests {
368 use super::{
369 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, channel_menu_entries,
370 channel_visibility_failure, pin_failure, post_pin_dialog, post_pin_failure,
371 post_pin_notice, team_menu_entries, team_visibility_failure,
372 };
373
374 fn labels<Item: Copy>(
375 entries: &[MenuEntry<Item>],
376 label: impl Fn(Item) -> &'static str,
377 ) -> Vec<&'static str> {
378 entries
379 .iter()
380 .map(|entry| match entry {
381 MenuEntry::Item(item) => label(*item),
382 MenuEntry::Separator => "-",
383 })
384 .collect()
385 }
386
387 #[test]
388 fn channel_menu_follows_teams_order() {
389 let shown = channel_menu_entries(ChannelMenuState {
390 pinned: false,
391 shown: true,
392 });
393 assert_eq!(
394 labels(&shown, ChannelMenuItem::label),
395 ["Notifications", "Pin", "Hide", "-", "Copy link"]
396 );
397 let hidden_pinned = channel_menu_entries(ChannelMenuState {
398 pinned: true,
399 shown: false,
400 });
401 assert_eq!(
402 labels(&hidden_pinned, ChannelMenuItem::label),
403 ["Notifications", "Unpin", "Show", "-", "Copy link"]
404 );
405 }
406
407 #[test]
408 fn pinned_channels_cannot_be_hidden() {
409 let pinned = ChannelMenuState {
410 pinned: true,
411 shown: true,
412 };
413 assert!(pinned.disables(ChannelMenuItem::Hide));
414 assert!(!pinned.disables(ChannelMenuItem::Unpin));
415 let unpinned = ChannelMenuState {
416 pinned: false,
417 shown: true,
418 };
419 assert!(!unpinned.disables(ChannelMenuItem::Hide));
420 }
421
422 #[test]
423 fn team_menu_switches_between_show_and_hide() {
424 assert_eq!(
425 labels(&team_menu_entries(false), TeamMenuItem::label),
426 ["Hide", "-", "Copy link"]
427 );
428 assert_eq!(
429 labels(&team_menu_entries(true), TeamMenuItem::label),
430 ["Show", "-", "Copy link"]
431 );
432 }
433
434 #[test]
435 fn post_pin_dialogs_and_notices_use_teams_strings() {
436 let unpin = post_pin_dialog(false);
437 assert_eq!(unpin.title, "Unpin this message?");
438 assert_eq!(
439 unpin.body,
440 "The message will be unpinned for everyone who views the channel."
441 );
442 assert_eq!(unpin.confirm, "Unpin");
443 let pin = post_pin_dialog(true);
444 assert_eq!(pin.title, "Pin in channel");
445 assert_eq!(pin.confirm, "Pin");
446 assert_eq!(post_pin_notice(true), "Post pinned");
447 assert_eq!(post_pin_notice(false), "Post unpinned");
448 assert_eq!(post_pin_failure(true), "We couldn't pin the post.");
449 assert_eq!(post_pin_failure(false), "We couldn't unpin the post.");
450 }
451
452 #[test]
453 fn failures_use_teams_strings() {
454 assert_eq!(pin_failure(true), "We couldn't pin the channel.");
455 assert_eq!(pin_failure(false), "We couldn't unpin the channel.");
456 assert_eq!(
457 channel_visibility_failure(false),
458 "We couldn't hide the channel."
459 );
460 assert_eq!(team_visibility_failure(true), "We couldn't show the team.");
461 }
462}
crates/app-state/src/chat_actions.rs +75 −6
@@ -1,8 +1,8 @@
1 1 use std::future::Future;
2 2
3 use chatsvc::HistoryShare;
3 4 use chrono::{DateTime, Duration, Local, Offset, Utc};
4 5 use gpui_kit::*;
5 use chatsvc::HistoryShare;
6 6 use store::{ChannelNotifications, ChatRecord, MemberRecord};
7 7 use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8 8
@@ -255,9 +255,7 @@ impl AppState {
255 255 };
256 256 let mut with_members = chat.clone();
257 257 merge_members(&mut with_members.members, &people);
258 let _ = self
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
258 let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
261 259 self.reload_sidebar(cx);
262 260 let Some(engine) = engine_or_demo else {
263 261 self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,26 +300,97 @@ impl AppState {
302 300 HistoryShare::Days(days) => SharedHistory::Days(days),
303 301 HistoryShare::All => SharedHistory::All,
304 302 },
303 topic: None,
305 304 };
305 self.store_demo_roster_line(chat_id, &event, cx);
306 }
307
308 fn store_demo_roster_line(
309 &mut self,
310 chat_id: &str,
311 event: &RosterEvent,
312 cx: &mut Context<Self>,
313 ) {
306 314 let now = Utc::now();
307 315 let record = crate::demo::roster_record(
308 316 chat_id,
309 317 &format!("demo-roster-{}", now.timestamp_millis()),
310 318 now,
311 &event,
319 event,
312 320 );
313 321 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 322 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 323 cx.notify();
316 324 }
317 325
326 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328 let Some(chat) = self.chat_record(chat_id) else {
329 return;
330 };
331 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332 return;
333 };
334 self.remove_chat_locally(chat_id, cx);
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 let owned_id = chat_id.to_owned();
339 self.run_chat_action(
340 "Remove chat history",
341 async move { engine.remove_chat_history(&owned_id).await },
342 move |state, cx| state.restore_chat_locally(&chat, cx),
343 |_, _| {},
344 cx,
345 );
346 }
347
348 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349 let Some(chat) = self.chat_record(chat_id) else {
350 return;
351 };
352 let topic = topic.trim().to_owned();
353 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354 return;
355 }
356 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357 return;
358 };
359 let mut renamed = chat.clone();
360 renamed.title = topic.clone();
361 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362 self.reload_sidebar(cx);
363 let Some(engine) = engine_or_demo else {
364 let me = self.directory.me.as_ref();
365 let event = RosterEvent {
366 change: RosterChange::Renamed,
367 initiator_id: me.map(|person| person.user_id.clone()),
368 initiator_name: me.map(|person| person.display_name.clone()),
369 member_ids: Vec::new(),
370 member_names: Vec::new(),
371 history: SharedHistory::None,
372 topic: (!topic.is_empty()).then(|| topic.clone()),
373 };
374 self.store_demo_roster_line(chat_id, &event, cx);
375 return;
376 };
377 let owned_id = chat_id.to_owned();
378 self.run_chat_action(
379 "Rename group chat",
380 async move { engine.rename_chat(&owned_id, &topic).await },
381 move |state, cx| state.restore_chat_locally(&chat, cx),
382 |_, _| {},
383 cx,
384 );
385 }
386
318 387 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 388 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 389 self.new_chat_people = people;
321 390 self.start_new_chat(cx);
322 391 }
323 392
324 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
393 pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
325 394 self.sidebar
326 395 .chats
327 396 .iter()
@@ -1,8 +1,8 @@
1use std::future::Future;
1use std::future::Future;
2
2
3use chatsvc::HistoryShare;
3use chrono::{DateTime, Duration, Local, Offset, Utc};
4use chrono::{DateTime, Duration, Local, Offset, Utc};
4use gpui_kit::*;
5use gpui_kit::*;
5use chatsvc::HistoryShare;
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
6use store::{ChannelNotifications, ChatRecord, MemberRecord};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
7use teams_core::roster_event::{RosterChange, RosterEvent, SharedHistory, merge_members};
8
8
@@ -255,9 +255,7 @@ impl AppState {
255 };
255 };
256 let mut with_members = chat.clone();
256 let mut with_members = chat.clone();
257 merge_members(&mut with_members.members, &people);
257 merge_members(&mut with_members.members, &people);
258 let _ = self
258 let _ = self.store.upsert_chats(std::slice::from_ref(&with_members));
259 .store
260 .upsert_chats(std::slice::from_ref(&with_members));
261 self.reload_sidebar(cx);
259 self.reload_sidebar(cx);
262 let Some(engine) = engine_or_demo else {
260 let Some(engine) = engine_or_demo else {
263 self.add_demo_roster_line(chat_id, &people, share, cx);
261 self.add_demo_roster_line(chat_id, &people, share, cx);
@@ -302,26 +300,97 @@ impl AppState {
302 HistoryShare::Days(days) => SharedHistory::Days(days),
300 HistoryShare::Days(days) => SharedHistory::Days(days),
303 HistoryShare::All => SharedHistory::All,
301 HistoryShare::All => SharedHistory::All,
304 },
302 },
303 topic: None,
305 };
304 };
305 self.store_demo_roster_line(chat_id, &event, cx);
306 }
307
308 fn store_demo_roster_line(
309 &mut self,
310 chat_id: &str,
311 event: &RosterEvent,
312 cx: &mut Context<Self>,
313 ) {
306 let now = Utc::now();
314 let now = Utc::now();
307 let record = crate::demo::roster_record(
315 let record = crate::demo::roster_record(
308 chat_id,
316 chat_id,
309 &format!("demo-roster-{}", now.timestamp_millis()),
317 &format!("demo-roster-{}", now.timestamp_millis()),
310 now,
318 now,
311 &event,
319 event,
312 );
320 );
313 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
321 let _ = self.store.upsert_messages(std::slice::from_ref(&record));
314 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
322 cx.emit(crate::app_state::AppEvent::Messages(chat_id.to_owned()));
315 cx.notify();
323 cx.notify();
316 }
324 }
317
325
326 /// Teams' "Remove chat history": hidden for me only until a newer message arrives.
327 pub fn remove_chat_history(&mut self, chat_id: &str, cx: &mut Context<Self>) {
328 let Some(chat) = self.chat_record(chat_id) else {
329 return;
330 };
331 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
332 return;
333 };
334 self.remove_chat_locally(chat_id, cx);
335 let Some(engine) = engine_or_demo else {
336 return;
337 };
338 let owned_id = chat_id.to_owned();
339 self.run_chat_action(
340 "Remove chat history",
341 async move { engine.remove_chat_history(&owned_id).await },
342 move |state, cx| state.restore_chat_locally(&chat, cx),
343 |_, _| {},
344 cx,
345 );
346 }
347
348 pub fn rename_chat(&mut self, chat_id: &str, topic: &str, cx: &mut Context<Self>) {
349 let Some(chat) = self.chat_record(chat_id) else {
350 return;
351 };
352 let topic = topic.trim().to_owned();
353 if topic == chat.title.trim() || chatsvc::topic_problem(&topic).is_some() {
354 return;
355 }
356 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
357 return;
358 };
359 let mut renamed = chat.clone();
360 renamed.title = topic.clone();
361 let _ = self.store.upsert_chats(std::slice::from_ref(&renamed));
362 self.reload_sidebar(cx);
363 let Some(engine) = engine_or_demo else {
364 let me = self.directory.me.as_ref();
365 let event = RosterEvent {
366 change: RosterChange::Renamed,
367 initiator_id: me.map(|person| person.user_id.clone()),
368 initiator_name: me.map(|person| person.display_name.clone()),
369 member_ids: Vec::new(),
370 member_names: Vec::new(),
371 history: SharedHistory::None,
372 topic: (!topic.is_empty()).then(|| topic.clone()),
373 };
374 self.store_demo_roster_line(chat_id, &event, cx);
375 return;
376 };
377 let owned_id = chat_id.to_owned();
378 self.run_chat_action(
379 "Rename group chat",
380 async move { engine.rename_chat(&owned_id, &topic).await },
381 move |state, cx| state.restore_chat_locally(&chat, cx),
382 |_, _| {},
383 cx,
384 );
385 }
386
318 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
387 /// Teams turns adding people to a 1:1 into a new group chat draft with everyone.
319 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
388 pub fn start_group_chat_with(&mut self, people: Vec<MemberRecord>, cx: &mut Context<Self>) {
320 self.new_chat_people = people;
389 self.new_chat_people = people;
321 self.start_new_chat(cx);
390 self.start_new_chat(cx);
322 }
391 }
323
392
324 fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
393 pub(crate) fn chat_record(&self, chat_id: &str) -> Option<ChatRecord> {
325 self.sidebar
394 self.sidebar
326 .chats
395 .chats
327 .iter()
396 .iter()
crates/app-state/src/chat_filter.rs added +376 −0
@@ -0,0 +1,376 @@
1 use std::collections::HashSet;
2
3 use store::ChatRecord;
4
5 use crate::activity::{Entry, Kind};
6 use crate::app_state::chat_title;
7 use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8
9 pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
10 pub const NO_MATCHES: &str = "We didn't find any matches.";
11 pub const CLEAR_FILTERS: &str = "Clear filters";
12 pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
13 pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
14 pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
15 pub const MORE_FILTERS: &str = "More filters";
16 pub const FEWER_FILTERS: &str = "Fewer filters";
17 const MEETING_KIND: &str = "meeting";
18
19 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20 pub enum ChatFilterPill {
21 Unread,
22 Mentions,
23 Chats,
24 Meetings,
25 Muted,
26 }
27
28 impl ChatFilterPill {
29 pub const PRIMARY: [ChatFilterPill; 3] = [
30 ChatFilterPill::Unread,
31 ChatFilterPill::Mentions,
32 ChatFilterPill::Chats,
33 ];
34 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Meetings, ChatFilterPill::Muted];
35
36 pub fn label(self) -> &'static str {
37 match self {
38 ChatFilterPill::Unread => "Unread",
39 ChatFilterPill::Mentions => "@Mentions",
40 ChatFilterPill::Chats => "Chats",
41 ChatFilterPill::Meetings => "Meeting chats",
42 ChatFilterPill::Muted => "Muted",
43 }
44 }
45
46 fn is_category(self) -> bool {
47 matches!(self, ChatFilterPill::Chats | ChatFilterPill::Meetings)
48 }
49
50 fn excludes(self) -> Option<ChatFilterPill> {
51 match self {
52 ChatFilterPill::Mentions => Some(ChatFilterPill::Muted),
53 ChatFilterPill::Muted => Some(ChatFilterPill::Mentions),
54 ChatFilterPill::Chats => Some(ChatFilterPill::Meetings),
55 ChatFilterPill::Meetings => Some(ChatFilterPill::Chats),
56 ChatFilterPill::Unread => None,
57 }
58 }
59
60 fn admits(self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
61 let meeting = chat.kind.eq_ignore_ascii_case(MEETING_KIND);
62 match self {
63 ChatFilterPill::Unread => chat.unread,
64 ChatFilterPill::Mentions => mentioned.contains(&chat.id),
65 ChatFilterPill::Chats => !meeting,
66 ChatFilterPill::Meetings => meeting,
67 ChatFilterPill::Muted => chat.muted,
68 }
69 }
70 }
71
72 #[derive(Debug, Clone, Default, PartialEq, Eq)]
73 pub struct ChatFilter {
74 pub text: String,
75 pub pills: Vec<ChatFilterPill>,
76 }
77
78 impl ChatFilter {
79 pub fn is_active(&self) -> bool {
80 !self.text.trim().is_empty() || !self.pills.is_empty()
81 }
82
83 pub fn has(&self, pill: ChatFilterPill) -> bool {
84 self.pills.contains(&pill)
85 }
86
87 pub fn is_disabled(&self, pill: ChatFilterPill) -> bool {
88 !self.has(pill)
89 && self
90 .pills
91 .iter()
92 .any(|active| active.excludes() == Some(pill))
93 }
94
95 pub fn toggle(&mut self, pill: ChatFilterPill) -> bool {
96 if self.has(pill) {
97 self.pills.retain(|active| *active != pill);
98 return true;
99 }
100 if self.is_disabled(pill) {
101 return false;
102 }
103 self.pills.push(pill);
104 true
105 }
106
107 pub fn clear(&mut self) {
108 self.text.clear();
109 self.pills.clear();
110 }
111
112 pub fn admits(&self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
113 if !name_matches(&self.text, &chat_title(chat)) {
114 return false;
115 }
116 let states_hold = self
117 .pills
118 .iter()
119 .filter(|pill| !pill.is_category())
120 .all(|pill| pill.admits(chat, mentioned));
121 let mut categories = self
122 .pills
123 .iter()
124 .filter(|pill| pill.is_category())
125 .peekable();
126 let category_holds =
127 categories.peek().is_none() || categories.any(|pill| pill.admits(chat, mentioned));
128 states_hold && category_holds
129 }
130 }
131
132 pub fn mentioned_conversations<'a>(entries: impl Iterator<Item = &'a Entry>) -> HashSet<String> {
133 entries
134 .filter(|entry| entry.kind == Kind::Mention)
135 .map(|entry| entry.conversation_id.clone())
136 .collect()
137 }
138
139 fn words(text: &str) -> Vec<String> {
140 text.to_lowercase()
141 .split(|character: char| character.is_whitespace() || character == ',')
142 .filter(|word| !word.is_empty())
143 .map(str::to_owned)
144 .collect()
145 }
146
147 pub fn name_matches(query: &str, title: &str) -> bool {
148 let query = query.trim().to_lowercase();
149 if query.is_empty() {
150 return true;
151 }
152 let title_lower = title.to_lowercase();
153 if title_lower.contains(&query) {
154 return true;
155 }
156 let title_words = words(&title_lower);
157 words(&query).iter().all(|word| {
158 title_words
159 .iter()
160 .any(|title_word| title_word.starts_with(word.as_str()))
161 })
162 }
163
164 pub fn filtered_sections(
165 input: &SectionInput<'_>,
166 filter: &ChatFilter,
167 mentioned: &HashSet<String>,
168 selected_id: Option<&str>,
169 ) -> Vec<Section> {
170 let chats: Vec<ChatRecord> = input
171 .chats
172 .iter()
173 .filter(|chat| Some(chat.id.as_str()) == selected_id || filter.admits(chat, mentioned))
174 .cloned()
175 .collect();
176 let every_list: HashSet<String> = input
177 .directory
178 .folders
179 .iter()
180 .map(|folder| folder.id.clone())
181 .chain([MUTED_ID.to_owned(), OTHERS_ID.to_owned()])
182 .collect();
183 let unpaged = SectionInput {
184 chats: &chats,
185 expanded_lists: &every_list,
186 ..*input
187 };
188 build_sections(&unpaged)
189 .into_iter()
190 .filter(|section| !section.items.is_empty())
191 .map(|section| Section {
192 hidden_count: 0,
193 list_expanded: false,
194 show_empty_hint: false,
195 ..section
196 })
197 .collect()
198 }
199
200 pub fn has_no_matches(sections: &[Section], selected_id: Option<&str>) -> bool {
201 sections
202 .iter()
203 .flat_map(|section| &section.items)
204 .all(|item| Some(item.id.as_str()) == selected_id)
205 }
206
207 #[cfg(test)]
208 mod tests {
209 use chrono::{FixedOffset, TimeZone, Utc};
210
211 use super::*;
212 use crate::data::{Directory, FolderInfo, FolderKind};
213 use crate::typing::TypingState;
214 use teams_core::ChatSection;
215
216 fn chat(id: &str, title: &str, kind: &str) -> ChatRecord {
217 ChatRecord {
218 id: id.into(),
219 kind: kind.into(),
220 title: title.into(),
221 ..Default::default()
222 }
223 }
224
225 fn admitted(filter: &ChatFilter, chats: &[ChatRecord], mentioned: &[&str]) -> Vec<String> {
226 let mentioned: HashSet<String> = mentioned.iter().map(|id| (*id).to_owned()).collect();
227 chats
228 .iter()
229 .filter(|chat| filter.admits(chat, &mentioned))
230 .map(|chat| chat.id.clone())
231 .collect()
232 }
233
234 #[test]
235 fn name_filter_matches_a_substring_or_every_word_prefix_like_teams() {
236 assert!(name_matches("", "Anything"));
237 assert!(name_matches("lind", "Mara Lindqvist"));
238 assert!(name_matches("ma li", "Mara Lindqvist"));
239 assert!(name_matches("LI, MA", "Mara Lindqvist"));
240 assert!(!name_matches("ma xo", "Mara Lindqvist"));
241 }
242
243 #[test]
244 fn state_pills_must_all_hold_and_category_pills_need_one() {
245 let chats = [
246 ChatRecord {
247 unread: true,
248 ..chat("unread", "Unread chat", "group")
249 },
250 ChatRecord {
251 unread: true,
252 ..chat("meeting", "Standup", "meeting")
253 },
254 ChatRecord {
255 muted: true,
256 ..chat("muted", "Muted chat", "group")
257 },
258 chat("plain", "Plain chat", "oneOnOne"),
259 ];
260 let mut filter = ChatFilter::default();
261 assert_eq!(admitted(&filter, &chats, &[]).len(), 4);
262 filter.toggle(ChatFilterPill::Unread);
263 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "meeting"]);
264 filter.toggle(ChatFilterPill::Meetings);
265 assert_eq!(admitted(&filter, &chats, &[]), ["meeting"]);
266 filter.toggle(ChatFilterPill::Unread);
267 filter.toggle(ChatFilterPill::Meetings);
268 filter.toggle(ChatFilterPill::Chats);
269 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "muted", "plain"]);
270 filter.toggle(ChatFilterPill::Mentions);
271 assert_eq!(admitted(&filter, &chats, &["plain"]), ["plain"]);
272 }
273
274 #[test]
275 fn exclusive_pills_disable_each_other() {
276 let mut filter = ChatFilter::default();
277 assert!(filter.toggle(ChatFilterPill::Chats));
278 assert!(filter.is_disabled(ChatFilterPill::Meetings));
279 assert!(!filter.toggle(ChatFilterPill::Meetings));
280 assert!(filter.toggle(ChatFilterPill::Muted));
281 assert!(filter.is_disabled(ChatFilterPill::Mentions));
282 assert!(!filter.is_disabled(ChatFilterPill::Unread));
283 assert!(filter.toggle(ChatFilterPill::Chats));
284 assert!(!filter.is_disabled(ChatFilterPill::Meetings));
285 filter.text = "x".into();
286 assert!(filter.is_active());
287 filter.clear();
288 assert!(!filter.is_active());
289 }
290
291 #[test]
292 fn text_combines_with_pills() {
293 let chats = [
294 ChatRecord {
295 unread: true,
296 ..chat("a", "Release crew", "group")
297 },
298 chat("b", "Release notes", "group"),
299 ];
300 let filter = ChatFilter {
301 text: "rel".into(),
302 pills: vec![ChatFilterPill::Unread],
303 };
304 assert_eq!(admitted(&filter, &chats, &[]), ["a"]);
305 }
306
307 static NO_TYPING: std::sync::LazyLock<TypingState> =
308 std::sync::LazyLock::new(TypingState::default);
309
310 #[test]
311 fn filtered_sections_keep_sections_drop_empty_ones_and_unpage_muted() {
312 let mut chats = vec![
313 chat("fav", "Favorite release", "group"),
314 chat("other", "Other release", "group"),
315 chat("quiet", "Quiet", "group"),
316 ];
317 chats.extend((0..7).map(|index| ChatRecord {
318 muted: true,
319 ..chat(
320 &format!("m{index}"),
321 &format!("Muted release {index}"),
322 "group",
323 )
324 }));
325 let mut directory = Directory {
326 folders: vec![
327 FolderInfo {
328 id: "favorites".into(),
329 name: "Favorites".into(),
330 kind: FolderKind::Favorites,
331 expanded: None,
332 conversation_ids: vec!["fav".into()],
333 },
334 FolderInfo {
335 id: "empty".into(),
336 name: "Empty".into(),
337 kind: FolderKind::UserCreated,
338 expanded: None,
339 conversation_ids: Vec::new(),
340 },
341 ],
342 ..Default::default()
343 };
344 directory.section_settings.set(ChatSection::Muted, true);
345 let collapsed = HashSet::new();
346 let expanded = HashSet::new();
347 let input = SectionInput {
348 chats: &chats,
349 directory: &directory,
350 collapsed: &collapsed,
351 expanded_lists: &expanded,
352 typing: &NO_TYPING,
353 now: Utc.with_ymd_and_hms(2026, 10, 17, 12, 0, 0).unwrap(),
354 offset: FixedOffset::east_opt(0).unwrap(),
355 };
356 let filter = ChatFilter {
357 text: "release".into(),
358 pills: Vec::new(),
359 };
360 let sections = filtered_sections(&input, &filter, &HashSet::new(), None);
361 let names: Vec<(&str, usize)> = sections
362 .iter()
363 .map(|section| (section.id.as_str(), section.items.len()))
364 .collect();
365 assert_eq!(names, [("favorites", 1), (OTHERS_ID, 1), (MUTED_ID, 7)]);
366 assert!(sections.iter().all(|section| section.hidden_count == 0
367 && !section.list_expanded
368 && !section.show_empty_hint));
369 let with_selection = filtered_sections(&input, &filter, &HashSet::new(), Some("quiet"));
370 assert!(
371 with_selection
372 .iter()
373 .any(|section| section.items.iter().any(|item| item.id == "quiet"))
374 );
375 }
376 }
@@ -0,0 +1,376 @@
1use std::collections::HashSet;
2
3use store::ChatRecord;
4
5use crate::activity::{Entry, Kind};
6use crate::app_state::chat_title;
7use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8
9pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
10pub const NO_MATCHES: &str = "We didn't find any matches.";
11pub const CLEAR_FILTERS: &str = "Clear filters";
12pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
13pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
14pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
15pub const MORE_FILTERS: &str = "More filters";
16pub const FEWER_FILTERS: &str = "Fewer filters";
17const MEETING_KIND: &str = "meeting";
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub enum ChatFilterPill {
21 Unread,
22 Mentions,
23 Chats,
24 Meetings,
25 Muted,
26}
27
28impl ChatFilterPill {
29 pub const PRIMARY: [ChatFilterPill; 3] = [
30 ChatFilterPill::Unread,
31 ChatFilterPill::Mentions,
32 ChatFilterPill::Chats,
33 ];
34 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Meetings, ChatFilterPill::Muted];
35
36 pub fn label(self) -> &'static str {
37 match self {
38 ChatFilterPill::Unread => "Unread",
39 ChatFilterPill::Mentions => "@Mentions",
40 ChatFilterPill::Chats => "Chats",
41 ChatFilterPill::Meetings => "Meeting chats",
42 ChatFilterPill::Muted => "Muted",
43 }
44 }
45
46 fn is_category(self) -> bool {
47 matches!(self, ChatFilterPill::Chats | ChatFilterPill::Meetings)
48 }
49
50 fn excludes(self) -> Option<ChatFilterPill> {
51 match self {
52 ChatFilterPill::Mentions => Some(ChatFilterPill::Muted),
53 ChatFilterPill::Muted => Some(ChatFilterPill::Mentions),
54 ChatFilterPill::Chats => Some(ChatFilterPill::Meetings),
55 ChatFilterPill::Meetings => Some(ChatFilterPill::Chats),
56 ChatFilterPill::Unread => None,
57 }
58 }
59
60 fn admits(self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
61 let meeting = chat.kind.eq_ignore_ascii_case(MEETING_KIND);
62 match self {
63 ChatFilterPill::Unread => chat.unread,
64 ChatFilterPill::Mentions => mentioned.contains(&chat.id),
65 ChatFilterPill::Chats => !meeting,
66 ChatFilterPill::Meetings => meeting,
67 ChatFilterPill::Muted => chat.muted,
68 }
69 }
70}
71
72#[derive(Debug, Clone, Default, PartialEq, Eq)]
73pub struct ChatFilter {
74 pub text: String,
75 pub pills: Vec<ChatFilterPill>,
76}
77
78impl ChatFilter {
79 pub fn is_active(&self) -> bool {
80 !self.text.trim().is_empty() || !self.pills.is_empty()
81 }
82
83 pub fn has(&self, pill: ChatFilterPill) -> bool {
84 self.pills.contains(&pill)
85 }
86
87 pub fn is_disabled(&self, pill: ChatFilterPill) -> bool {
88 !self.has(pill)
89 && self
90 .pills
91 .iter()
92 .any(|active| active.excludes() == Some(pill))
93 }
94
95 pub fn toggle(&mut self, pill: ChatFilterPill) -> bool {
96 if self.has(pill) {
97 self.pills.retain(|active| *active != pill);
98 return true;
99 }
100 if self.is_disabled(pill) {
101 return false;
102 }
103 self.pills.push(pill);
104 true
105 }
106
107 pub fn clear(&mut self) {
108 self.text.clear();
109 self.pills.clear();
110 }
111
112 pub fn admits(&self, chat: &ChatRecord, mentioned: &HashSet<String>) -> bool {
113 if !name_matches(&self.text, &chat_title(chat)) {
114 return false;
115 }
116 let states_hold = self
117 .pills
118 .iter()
119 .filter(|pill| !pill.is_category())
120 .all(|pill| pill.admits(chat, mentioned));
121 let mut categories = self
122 .pills
123 .iter()
124 .filter(|pill| pill.is_category())
125 .peekable();
126 let category_holds =
127 categories.peek().is_none() || categories.any(|pill| pill.admits(chat, mentioned));
128 states_hold && category_holds
129 }
130}
131
132pub fn mentioned_conversations<'a>(entries: impl Iterator<Item = &'a Entry>) -> HashSet<String> {
133 entries
134 .filter(|entry| entry.kind == Kind::Mention)
135 .map(|entry| entry.conversation_id.clone())
136 .collect()
137}
138
139fn words(text: &str) -> Vec<String> {
140 text.to_lowercase()
141 .split(|character: char| character.is_whitespace() || character == ',')
142 .filter(|word| !word.is_empty())
143 .map(str::to_owned)
144 .collect()
145}
146
147pub fn name_matches(query: &str, title: &str) -> bool {
148 let query = query.trim().to_lowercase();
149 if query.is_empty() {
150 return true;
151 }
152 let title_lower = title.to_lowercase();
153 if title_lower.contains(&query) {
154 return true;
155 }
156 let title_words = words(&title_lower);
157 words(&query).iter().all(|word| {
158 title_words
159 .iter()
160 .any(|title_word| title_word.starts_with(word.as_str()))
161 })
162}
163
164pub fn filtered_sections(
165 input: &SectionInput<'_>,
166 filter: &ChatFilter,
167 mentioned: &HashSet<String>,
168 selected_id: Option<&str>,
169) -> Vec<Section> {
170 let chats: Vec<ChatRecord> = input
171 .chats
172 .iter()
173 .filter(|chat| Some(chat.id.as_str()) == selected_id || filter.admits(chat, mentioned))
174 .cloned()
175 .collect();
176 let every_list: HashSet<String> = input
177 .directory
178 .folders
179 .iter()
180 .map(|folder| folder.id.clone())
181 .chain([MUTED_ID.to_owned(), OTHERS_ID.to_owned()])
182 .collect();
183 let unpaged = SectionInput {
184 chats: &chats,
185 expanded_lists: &every_list,
186 ..*input
187 };
188 build_sections(&unpaged)
189 .into_iter()
190 .filter(|section| !section.items.is_empty())
191 .map(|section| Section {
192 hidden_count: 0,
193 list_expanded: false,
194 show_empty_hint: false,
195 ..section
196 })
197 .collect()
198}
199
200pub fn has_no_matches(sections: &[Section], selected_id: Option<&str>) -> bool {
201 sections
202 .iter()
203 .flat_map(|section| &section.items)
204 .all(|item| Some(item.id.as_str()) == selected_id)
205}
206
207#[cfg(test)]
208mod tests {
209 use chrono::{FixedOffset, TimeZone, Utc};
210
211 use super::*;
212 use crate::data::{Directory, FolderInfo, FolderKind};
213 use crate::typing::TypingState;
214 use teams_core::ChatSection;
215
216 fn chat(id: &str, title: &str, kind: &str) -> ChatRecord {
217 ChatRecord {
218 id: id.into(),
219 kind: kind.into(),
220 title: title.into(),
221 ..Default::default()
222 }
223 }
224
225 fn admitted(filter: &ChatFilter, chats: &[ChatRecord], mentioned: &[&str]) -> Vec<String> {
226 let mentioned: HashSet<String> = mentioned.iter().map(|id| (*id).to_owned()).collect();
227 chats
228 .iter()
229 .filter(|chat| filter.admits(chat, &mentioned))
230 .map(|chat| chat.id.clone())
231 .collect()
232 }
233
234 #[test]
235 fn name_filter_matches_a_substring_or_every_word_prefix_like_teams() {
236 assert!(name_matches("", "Anything"));
237 assert!(name_matches("lind", "Mara Lindqvist"));
238 assert!(name_matches("ma li", "Mara Lindqvist"));
239 assert!(name_matches("LI, MA", "Mara Lindqvist"));
240 assert!(!name_matches("ma xo", "Mara Lindqvist"));
241 }
242
243 #[test]
244 fn state_pills_must_all_hold_and_category_pills_need_one() {
245 let chats = [
246 ChatRecord {
247 unread: true,
248 ..chat("unread", "Unread chat", "group")
249 },
250 ChatRecord {
251 unread: true,
252 ..chat("meeting", "Standup", "meeting")
253 },
254 ChatRecord {
255 muted: true,
256 ..chat("muted", "Muted chat", "group")
257 },
258 chat("plain", "Plain chat", "oneOnOne"),
259 ];
260 let mut filter = ChatFilter::default();
261 assert_eq!(admitted(&filter, &chats, &[]).len(), 4);
262 filter.toggle(ChatFilterPill::Unread);
263 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "meeting"]);
264 filter.toggle(ChatFilterPill::Meetings);
265 assert_eq!(admitted(&filter, &chats, &[]), ["meeting"]);
266 filter.toggle(ChatFilterPill::Unread);
267 filter.toggle(ChatFilterPill::Meetings);
268 filter.toggle(ChatFilterPill::Chats);
269 assert_eq!(admitted(&filter, &chats, &[]), ["unread", "muted", "plain"]);
270 filter.toggle(ChatFilterPill::Mentions);
271 assert_eq!(admitted(&filter, &chats, &["plain"]), ["plain"]);
272 }
273
274 #[test]
275 fn exclusive_pills_disable_each_other() {
276 let mut filter = ChatFilter::default();
277 assert!(filter.toggle(ChatFilterPill::Chats));
278 assert!(filter.is_disabled(ChatFilterPill::Meetings));
279 assert!(!filter.toggle(ChatFilterPill::Meetings));
280 assert!(filter.toggle(ChatFilterPill::Muted));
281 assert!(filter.is_disabled(ChatFilterPill::Mentions));
282 assert!(!filter.is_disabled(ChatFilterPill::Unread));
283 assert!(filter.toggle(ChatFilterPill::Chats));
284 assert!(!filter.is_disabled(ChatFilterPill::Meetings));
285 filter.text = "x".into();
286 assert!(filter.is_active());
287 filter.clear();
288 assert!(!filter.is_active());
289 }
290
291 #[test]
292 fn text_combines_with_pills() {
293 let chats = [
294 ChatRecord {
295 unread: true,
296 ..chat("a", "Release crew", "group")
297 },
298 chat("b", "Release notes", "group"),
299 ];
300 let filter = ChatFilter {
301 text: "rel".into(),
302 pills: vec![ChatFilterPill::Unread],
303 };
304 assert_eq!(admitted(&filter, &chats, &[]), ["a"]);
305 }
306
307 static NO_TYPING: std::sync::LazyLock<TypingState> =
308 std::sync::LazyLock::new(TypingState::default);
309
310 #[test]
311 fn filtered_sections_keep_sections_drop_empty_ones_and_unpage_muted() {
312 let mut chats = vec![
313 chat("fav", "Favorite release", "group"),
314 chat("other", "Other release", "group"),
315 chat("quiet", "Quiet", "group"),
316 ];
317 chats.extend((0..7).map(|index| ChatRecord {
318 muted: true,
319 ..chat(
320 &format!("m{index}"),
321 &format!("Muted release {index}"),
322 "group",
323 )
324 }));
325 let mut directory = Directory {
326 folders: vec![
327 FolderInfo {
328 id: "favorites".into(),
329 name: "Favorites".into(),
330 kind: FolderKind::Favorites,
331 expanded: None,
332 conversation_ids: vec!["fav".into()],
333 },
334 FolderInfo {
335 id: "empty".into(),
336 name: "Empty".into(),
337 kind: FolderKind::UserCreated,
338 expanded: None,
339 conversation_ids: Vec::new(),
340 },
341 ],
342 ..Default::default()
343 };
344 directory.section_settings.set(ChatSection::Muted, true);
345 let collapsed = HashSet::new();
346 let expanded = HashSet::new();
347 let input = SectionInput {
348 chats: &chats,
349 directory: &directory,
350 collapsed: &collapsed,
351 expanded_lists: &expanded,
352 typing: &NO_TYPING,
353 now: Utc.with_ymd_and_hms(2026, 10, 17, 12, 0, 0).unwrap(),
354 offset: FixedOffset::east_opt(0).unwrap(),
355 };
356 let filter = ChatFilter {
357 text: "release".into(),
358 pills: Vec::new(),
359 };
360 let sections = filtered_sections(&input, &filter, &HashSet::new(), None);
361 let names: Vec<(&str, usize)> = sections
362 .iter()
363 .map(|section| (section.id.as_str(), section.items.len()))
364 .collect();
365 assert_eq!(names, [("favorites", 1), (OTHERS_ID, 1), (MUTED_ID, 7)]);
366 assert!(sections.iter().all(|section| section.hidden_count == 0
367 && !section.list_expanded
368 && !section.show_empty_hint));
369 let with_selection = filtered_sections(&input, &filter, &HashSet::new(), Some("quiet"));
370 assert!(
371 with_selection
372 .iter()
373 .any(|section| section.items.iter().any(|item| item.id == "quiet"))
374 );
375 }
376}
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/default_reactions.rs added +127 −0
@@ -0,0 +1,127 @@
1 use gpui_kit::Context;
2
3 use crate::app_state::AppState;
4 use crate::emoticons;
5
6 pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {
7 reaction_ids
8 .iter()
9 .filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))
10 .map(|glyph| emoticons::with_tone(&glyph, skin_tone))
11 .collect()
12 }
13
14 pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {
15 chatsvc::reaction_key(&emoticons::without_tone(glyph))
16 }
17
18 pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {
19 let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);
20 (0..length)
21 .map(|index| reaction_ids.get(index).cloned())
22 .collect()
23 }
24
25 /// Teams' replace rule: an id already in another slot leaves that slot empty.
26 pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {
27 for slot in slots.iter_mut() {
28 if slot.as_deref() == Some(reaction_id.as_str()) {
29 *slot = None;
30 }
31 }
32 if let Some(slot) = slots.get_mut(index) {
33 *slot = Some(reaction_id);
34 }
35 }
36
37 pub fn filled(slots: &[Option<String>]) -> Vec<String> {
38 slots.iter().flatten().cloned().collect()
39 }
40
41 impl AppState {
42 pub fn default_reactions(&self) -> Vec<String> {
43 teams_core::default_reactions(&self.store)
44 }
45
46 pub fn quick_reactions(&self) -> Vec<String> {
47 quick_reaction_glyphs(
48 &self.default_reactions(),
49 teams_core::skin_tone(&self.store),
50 )
51 }
52
53 pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {
54 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
55 return;
56 };
57 let previous = self.default_reactions();
58 let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));
59 cx.notify();
60 let Some(engine) = engine_or_demo else {
61 return;
62 };
63 self.run_chat_action(
64 "Customising default reactions",
65 async move { engine.set_default_reactions(&reaction_ids).await },
66 move |state, cx| {
67 let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));
68 cx.notify();
69 },
70 |_, _| {},
71 cx,
72 );
73 }
74 }
75
76 #[cfg(test)]
77 mod tests {
78 use super::*;
79
80 fn ids(values: &[&str]) -> Vec<String> {
81 values.iter().map(|value| (*value).to_owned()).collect()
82 }
83
84 #[test]
85 fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {
86 let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);
87 assert_eq!(
88 quick_reaction_glyphs(&defaults, 0),
89 ["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]
90 );
91 assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");
92 assert_eq!(
93 chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),
94 Some("yes-tone2")
95 );
96 }
97
98 #[test]
99 fn unknown_ids_are_left_out() {
100 assert_eq!(
101 quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),
102 ["\u{2764}"]
103 );
104 }
105
106 #[test]
107 fn picked_glyphs_store_the_untoned_id() {
108 assert_eq!(
109 reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),
110 Some("like")
111 );
112 assert_eq!(
113 reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),
114 Some("heart")
115 );
116 }
117
118 #[test]
119 fn there_are_always_five_slots_and_a_repeat_moves() {
120 let mut slots = slots_for(&ids(&["like", "heart"]));
121 assert_eq!(slots.len(), 5);
122 place_in_slot(&mut slots, 3, "like".to_owned());
123 assert_eq!(filled(&slots), ["heart", "like"]);
124 assert_eq!(slots[0], None);
125 assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);
126 }
127 }
@@ -0,0 +1,127 @@
1use gpui_kit::Context;
2
3use crate::app_state::AppState;
4use crate::emoticons;
5
6pub fn quick_reaction_glyphs(reaction_ids: &[String], skin_tone: u8) -> Vec<String> {
7 reaction_ids
8 .iter()
9 .filter_map(|reaction_id| chatsvc::reaction_glyph_for_key(reaction_id))
10 .map(|glyph| emoticons::with_tone(&glyph, skin_tone))
11 .collect()
12}
13
14pub fn reaction_id_for_glyph(glyph: &str) -> Option<String> {
15 chatsvc::reaction_key(&emoticons::without_tone(glyph))
16}
17
18pub fn slots_for(reaction_ids: &[String]) -> Vec<Option<String>> {
19 let length = reaction_ids.len().max(teams_core::DEFAULT_REACTION_SLOTS);
20 (0..length)
21 .map(|index| reaction_ids.get(index).cloned())
22 .collect()
23}
24
25/// Teams' replace rule: an id already in another slot leaves that slot empty.
26pub fn place_in_slot(slots: &mut [Option<String>], index: usize, reaction_id: String) {
27 for slot in slots.iter_mut() {
28 if slot.as_deref() == Some(reaction_id.as_str()) {
29 *slot = None;
30 }
31 }
32 if let Some(slot) = slots.get_mut(index) {
33 *slot = Some(reaction_id);
34 }
35}
36
37pub fn filled(slots: &[Option<String>]) -> Vec<String> {
38 slots.iter().flatten().cloned().collect()
39}
40
41impl AppState {
42 pub fn default_reactions(&self) -> Vec<String> {
43 teams_core::default_reactions(&self.store)
44 }
45
46 pub fn quick_reactions(&self) -> Vec<String> {
47 quick_reaction_glyphs(
48 &self.default_reactions(),
49 teams_core::skin_tone(&self.store),
50 )
51 }
52
53 pub fn set_default_reactions(&mut self, reaction_ids: Vec<String>, cx: &mut Context<Self>) {
54 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
55 return;
56 };
57 let previous = self.default_reactions();
58 let _ = teams_core::store_account_default_reactions(&self.store, Some(&reaction_ids));
59 cx.notify();
60 let Some(engine) = engine_or_demo else {
61 return;
62 };
63 self.run_chat_action(
64 "Customising default reactions",
65 async move { engine.set_default_reactions(&reaction_ids).await },
66 move |state, cx| {
67 let _ = teams_core::store_account_default_reactions(&state.store, Some(&previous));
68 cx.notify();
69 },
70 |_, _| {},
71 cx,
72 );
73 }
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 fn ids(values: &[&str]) -> Vec<String> {
81 values.iter().map(|value| (*value).to_owned()).collect()
82 }
83
84 #[test]
85 fn teams_defaults_show_as_glyphs_and_like_takes_the_tone() {
86 let defaults = ids(&teams_core::TEAMS_DEFAULT_REACTIONS);
87 assert_eq!(
88 quick_reaction_glyphs(&defaults, 0),
89 ["\u{1F44D}", "\u{2764}", "\u{1F606}", "\u{1F62E}"]
90 );
91 assert_eq!(quick_reaction_glyphs(&defaults, 2)[0], "\u{1F44D}\u{1F3FC}");
92 assert_eq!(
93 chatsvc::reaction_key(&quick_reaction_glyphs(&defaults, 2)[0]).as_deref(),
94 Some("yes-tone2")
95 );
96 }
97
98 #[test]
99 fn unknown_ids_are_left_out() {
100 assert_eq!(
101 quick_reaction_glyphs(&ids(&["heart", "custom-gone"]), 0),
102 ["\u{2764}"]
103 );
104 }
105
106 #[test]
107 fn picked_glyphs_store_the_untoned_id() {
108 assert_eq!(
109 reaction_id_for_glyph("\u{1F44D}\u{1F3FC}").as_deref(),
110 Some("like")
111 );
112 assert_eq!(
113 reaction_id_for_glyph("\u{2764}\u{FE0F}").as_deref(),
114 Some("heart")
115 );
116 }
117
118 #[test]
119 fn there_are_always_five_slots_and_a_repeat_moves() {
120 let mut slots = slots_for(&ids(&["like", "heart"]));
121 assert_eq!(slots.len(), 5);
122 place_in_slot(&mut slots, 3, "like".to_owned());
123 assert_eq!(filled(&slots), ["heart", "like"]);
124 assert_eq!(slots[0], None);
125 assert_eq!(slots_for(&ids(&["a", "b", "c", "d", "e", "f"])).len(), 6);
126 }
127}
crates/app-state/src/demo.rs +11 −0
@@ -754,6 +754,16 @@ pub fn activity_entries() -> Vec<Entry> {
754 754 false,
755 755 ),
756 756 reaction,
757 entry(
758 "demo-chat-allhands",
759 Kind::Mention,
760 "demo-allhands-policy",
761 vec![actor(LEA_ID, "Lea Schneider")],
762 "@Dana please read the new vacation policy before Friday.",
763 1,
764 at(0, 9, 0),
765 false,
766 ),
757 767 entry(
758 768 "demo-chat-customer-3",
759 769 Kind::Messages,
@@ -1426,6 +1436,7 @@ fn settings_card() -> serde_json::Value {
1426 1436 })
1427 1437 }
1428 1438
1439 pub const DEMO_TENANT_ID: &str = "demo-tenant";
1429 1440 const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1430 1441
1431 1442 fn meeting_link_messages() -> Vec<MessageRecord> {
@@ -754,6 +754,16 @@ pub fn activity_entries() -> Vec<Entry> {
754 false,
754 false,
755 ),
755 ),
756 reaction,
756 reaction,
757 entry(
758 "demo-chat-allhands",
759 Kind::Mention,
760 "demo-allhands-policy",
761 vec![actor(LEA_ID, "Lea Schneider")],
762 "@Dana please read the new vacation policy before Friday.",
763 1,
764 at(0, 9, 0),
765 false,
766 ),
757 entry(
767 entry(
758 "demo-chat-customer-3",
768 "demo-chat-customer-3",
759 Kind::Messages,
769 Kind::Messages,
@@ -1426,6 +1436,7 @@ fn settings_card() -> serde_json::Value {
1426 })
1436 })
1427}
1437}
1428
1438
1439pub const DEMO_TENANT_ID: &str = "demo-tenant";
1429const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1440const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1430
1441
1431fn meeting_link_messages() -> Vec<MessageRecord> {
1442fn meeting_link_messages() -> Vec<MessageRecord> {
crates/app-state/src/find_in_chat.rs added +439 −0
@@ -0,0 +1,439 @@
1 use std::collections::HashSet;
2 use std::ops::Range;
3
4 use chatsvc::substrate_search::{MessageFilter, SearchMessage, split_highlights};
5 use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc};
6 use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, SearchHit};
7
8 pub const FIND_IN_CHAT: &str = "Find in chat";
9 pub const FIND_IN_CHANNEL: &str = "Find in channel";
10 pub const EMPTY_HINT: &str = "Find messages and links shared in this chat.";
11 pub const NO_RESULTS_CHAT: &str = "We couldn't find any results in this chat";
12 pub const NO_RESULTS_CHANNEL: &str = "We couldn't find any results in this channel";
13 pub const LOAD_ERROR: &str = "Something went wrong while loading the results.";
14 pub const LOADING: &str = "Fetching Data...";
15 pub const FROM_LABEL: &str = "From";
16 pub const DATE_LABEL: &str = "Date";
17 pub const HAS_ATTACHMENT_LABEL: &str = "Has attachment";
18 pub const MENTIONS_LABEL: &str = "@Mentions";
19 pub const THIS_MONTH: &str = "This month";
20 pub const LAST_MONTH: &str = "Last month";
21 const ORG_PREFIX: &str = "8:orgid:";
22
23 pub fn no_results_with_filters(search_term: &str) -> String {
24 format!("We couldn't find any results for '{search_term}' with the applied filters.")
25 }
26
27 #[derive(Debug, Clone, PartialEq, Eq)]
28 pub struct FindHit {
29 pub message_id: String,
30 pub sent_at: DateTime<Utc>,
31 pub sender_name: String,
32 pub sender_id: Option<String>,
33 pub text: String,
34 pub highlights: Vec<Range<usize>>,
35 pub mentions_me: bool,
36 pub has_attachment: bool,
37 }
38
39 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
40 pub enum DateRange {
41 Today,
42 Yesterday,
43 ThisWeek,
44 ThisMonth,
45 }
46
47 impl DateRange {
48 pub const ALL: [DateRange; 4] = [
49 DateRange::Today,
50 DateRange::Yesterday,
51 DateRange::ThisWeek,
52 DateRange::ThisMonth,
53 ];
54
55 pub fn label(self) -> &'static str {
56 match self {
57 DateRange::Today => "Today",
58 DateRange::Yesterday => "Yesterday",
59 DateRange::ThisWeek => "This week",
60 DateRange::ThisMonth => "This month",
61 }
62 }
63
64 pub fn contains(self, date: NaiveDate, today: NaiveDate) -> bool {
65 match self {
66 DateRange::Today => date == today,
67 DateRange::Yesterday => Some(date) == today.pred_opt(),
68 DateRange::ThisWeek => {
69 let week_start =
70 today - Duration::days(i64::from(today.weekday().num_days_from_monday()));
71 date >= week_start && date <= today
72 }
73 DateRange::ThisMonth => date.year() == today.year() && date.month() == today.month(),
74 }
75 }
76 }
77
78 #[derive(Debug, Clone, PartialEq, Eq)]
79 pub struct Sender {
80 pub user_id: String,
81 pub name: String,
82 }
83
84 #[derive(Debug, Clone, Default, PartialEq, Eq)]
85 pub struct FindFilters {
86 pub from: Option<Sender>,
87 pub date: Option<DateRange>,
88 pub has_attachment: bool,
89 pub mentions_me: bool,
90 }
91
92 impl FindFilters {
93 pub fn is_active(&self) -> bool {
94 self.from.is_some() || self.date.is_some() || self.has_attachment || self.mentions_me
95 }
96
97 pub fn admits(&self, hit: &FindHit, today: NaiveDate, offset: FixedOffset) -> bool {
98 let from_holds = self.from.as_ref().is_none_or(|sender| {
99 hit.sender_id
100 .as_deref()
101 .is_some_and(|sender_id| same_user(sender_id, &sender.user_id))
102 });
103 let date_holds = self.date.is_none_or(|range| {
104 range.contains(hit.sent_at.with_timezone(&offset).date_naive(), today)
105 });
106 from_holds
107 && date_holds
108 && (!self.has_attachment || hit.has_attachment)
109 && (!self.mentions_me || hit.mentions_me)
110 }
111
112 pub fn server_filters(&self, thread_id: &str) -> Vec<MessageFilter> {
113 let mut filters = vec![MessageFilter::InChat {
114 thread_id: thread_id.to_owned(),
115 }];
116 if let Some(sender) = &self.from {
117 filters.push(MessageFilter::FromSender {
118 mri: user_mri(&sender.user_id),
119 });
120 }
121 if self.has_attachment {
122 filters.push(MessageFilter::HasAttachment);
123 }
124 if self.mentions_me {
125 filters.push(MessageFilter::MentionsMe);
126 }
127 filters
128 }
129 }
130
131 fn bare_user_id(user_id: &str) -> String {
132 user_id
133 .strip_prefix(ORG_PREFIX)
134 .unwrap_or(user_id)
135 .to_ascii_lowercase()
136 }
137
138 pub fn same_user(first: &str, second: &str) -> bool {
139 bare_user_id(first) == bare_user_id(second)
140 }
141
142 pub fn user_mri(user_id: &str) -> String {
143 if user_id.contains(':') {
144 user_id.to_owned()
145 } else {
146 format!("{ORG_PREFIX}{user_id}")
147 }
148 }
149
150 fn parse_local_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
151 let mut text = String::with_capacity(snippet.len());
152 let mut highlights = Vec::new();
153 let mut start = None;
154 for character in snippet.chars() {
155 match character {
156 HIGHLIGHT_START => start = Some(text.len()),
157 HIGHLIGHT_END => {
158 if let Some(begin) = start.take() {
159 highlights.push(begin..text.len());
160 }
161 }
162 _ => text.push(character),
163 }
164 }
165 (text, highlights)
166 }
167
168 pub fn from_local(hit: &SearchHit, record: Option<&MessageRecord>, my_id: Option<&str>) -> FindHit {
169 let (text, highlights) = parse_local_snippet(&hit.snippet);
170 FindHit {
171 message_id: hit.message_id.clone(),
172 sent_at: hit.created_at,
173 sender_name: hit.sender_name.clone().unwrap_or_default(),
174 sender_id: record.and_then(|record| record.sender_id.clone()),
175 text,
176 highlights,
177 mentions_me: record.is_some_and(|record| mentions_user(record, my_id)),
178 has_attachment: record.is_some_and(has_attachment),
179 }
180 }
181
182 pub fn from_record(record: &MessageRecord, my_id: Option<&str>) -> FindHit {
183 FindHit {
184 message_id: record.message_id.clone(),
185 sent_at: record.created_at,
186 sender_name: record.sender_name.clone().unwrap_or_default(),
187 sender_id: record.sender_id.clone(),
188 text: teams_core::preview_text(&record.body_html).unwrap_or_default(),
189 highlights: Vec::new(),
190 mentions_me: mentions_user(record, my_id),
191 has_attachment: has_attachment(record),
192 }
193 }
194
195 pub fn from_server(message: &SearchMessage) -> Option<FindHit> {
196 let sent_at = message.sent_at?;
197 let highlighted = split_highlights(
198 message
199 .highlighted_summary
200 .as_deref()
201 .unwrap_or(&message.preview),
202 );
203 Some(FindHit {
204 message_id: message.message_id.clone(),
205 sent_at,
206 sender_name: message.sender_name.clone().unwrap_or_default(),
207 sender_id: message.sender_mri.clone(),
208 text: highlighted.text,
209 highlights: highlighted.hits,
210 mentions_me: message.is_mentioned,
211 has_attachment: message.has_attachments,
212 })
213 }
214
215 fn mentions_user(record: &MessageRecord, my_id: Option<&str>) -> bool {
216 let Some(my_id) = my_id else {
217 return false;
218 };
219 teams_core::mentions(record).iter().any(|mention| {
220 mention
221 .user_id
222 .as_deref()
223 .is_some_and(|user_id| same_user(user_id, my_id))
224 })
225 }
226
227 fn has_attachment(record: &MessageRecord) -> bool {
228 !teams_core::files(record).is_empty() || !teams_core::images(record).is_empty()
229 }
230
231 pub fn merge(local: Vec<FindHit>, server: Vec<FindHit>) -> Vec<FindHit> {
232 let mut seen = HashSet::new();
233 let mut hits: Vec<FindHit> = local
234 .into_iter()
235 .chain(server)
236 .filter(|hit| seen.insert(hit.message_id.clone()))
237 .collect();
238 hits.sort_by(|first, second| {
239 second
240 .sent_at
241 .cmp(&first.sent_at)
242 .then_with(|| second.message_id.cmp(&first.message_id))
243 });
244 hits
245 }
246
247 pub fn month_label(date: NaiveDate, today: NaiveDate) -> String {
248 let months = |date: NaiveDate| date.year() * 12 + date.month0() as i32;
249 match months(today) - months(date) {
250 0 => THIS_MONTH.to_owned(),
251 1 => LAST_MONTH.to_owned(),
252 _ => date.format("%B %Y").to_string(),
253 }
254 }
255
256 #[derive(Debug, Clone, PartialEq, Eq)]
257 pub struct MonthGroup {
258 pub label: String,
259 pub hits: Vec<FindHit>,
260 }
261
262 pub fn group_by_month(hits: &[FindHit], today: NaiveDate, offset: FixedOffset) -> Vec<MonthGroup> {
263 let mut groups: Vec<MonthGroup> = Vec::new();
264 for hit in hits {
265 let label = month_label(hit.sent_at.with_timezone(&offset).date_naive(), today);
266 match groups.last_mut() {
267 Some(group) if group.label == label => group.hits.push(hit.clone()),
268 _ => groups.push(MonthGroup {
269 label,
270 hits: vec![hit.clone()],
271 }),
272 }
273 }
274 groups
275 }
276
277 pub fn step_index(current: Option<usize>, count: usize, backwards: bool) -> Option<usize> {
278 if count == 0 {
279 return None;
280 }
281 Some(match (current, backwards) {
282 (None, false) => 0,
283 (None, true) => count - 1,
284 (Some(index), false) => (index + 1) % count,
285 (Some(index), true) => (index + count - 1) % count,
286 })
287 }
288
289 #[cfg(test)]
290 mod tests {
291 use chrono::TimeZone;
292
293 use super::*;
294
295 fn utc() -> FixedOffset {
296 FixedOffset::east_opt(0).unwrap()
297 }
298
299 fn hit(message_id: &str, day: u32, month: u32) -> FindHit {
300 FindHit {
301 message_id: message_id.into(),
302 sent_at: Utc.with_ymd_and_hms(2026, month, day, 10, 0, 0).unwrap(),
303 sender_name: "Lea".into(),
304 sender_id: Some("8:orgid:ABC".into()),
305 text: message_id.into(),
306 highlights: Vec::new(),
307 mentions_me: false,
308 has_attachment: false,
309 }
310 }
311
312 fn today() -> NaiveDate {
313 NaiveDate::from_ymd_opt(2026, 10, 17).unwrap()
314 }
315
316 #[test]
317 fn merge_dedupes_by_message_id_and_sorts_newest_first() {
318 let local = vec![hit("a", 1, 10), hit("b", 5, 10)];
319 let mut server_copy = hit("a", 1, 10);
320 server_copy.text = "server".into();
321 let server = vec![server_copy, hit("c", 3, 10)];
322 let merged = merge(local, server);
323 let ids: Vec<&str> = merged.iter().map(|hit| hit.message_id.as_str()).collect();
324 assert_eq!(ids, ["b", "c", "a"]);
325 assert_eq!(merged[2].text, "a");
326 }
327
328 #[test]
329 fn groups_follow_teams_month_labels() {
330 let hits = vec![
331 hit("a", 16, 10),
332 hit("b", 2, 10),
333 hit("c", 30, 9),
334 hit("d", 1, 7),
335 ];
336 let groups = group_by_month(&hits, today(), utc());
337 let labels: Vec<(&str, usize)> = groups
338 .iter()
339 .map(|group| (group.label.as_str(), group.hits.len()))
340 .collect();
341 assert_eq!(labels, [(THIS_MONTH, 2), (LAST_MONTH, 1), ("July 2026", 1)]);
342 assert_eq!(
343 month_label(NaiveDate::from_ymd_opt(2025, 10, 3).unwrap(), today()),
344 "October 2025"
345 );
346 }
347
348 #[test]
349 fn date_ranges_use_the_local_calendar() {
350 let saturday = today();
351 let day = |day: u32| NaiveDate::from_ymd_opt(2026, 10, day).unwrap();
352 assert!(DateRange::Today.contains(day(17), saturday));
353 assert!(DateRange::Yesterday.contains(day(16), saturday));
354 assert!(!DateRange::Yesterday.contains(day(17), saturday));
355 assert!(DateRange::ThisWeek.contains(day(12), saturday));
356 assert!(!DateRange::ThisWeek.contains(day(11), saturday));
357 assert!(DateRange::ThisMonth.contains(day(1), saturday));
358 assert!(
359 !DateRange::ThisMonth.contains(NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(), saturday)
360 );
361 }
362
363 #[test]
364 fn filters_admit_matching_hits_only() {
365 let mut matching = hit("a", 17, 10);
366 matching.has_attachment = true;
367 matching.mentions_me = true;
368 let plain = hit("b", 1, 10);
369 let filters = FindFilters {
370 from: Some(Sender {
371 user_id: "abc".into(),
372 name: "Lea".into(),
373 }),
374 date: Some(DateRange::Today),
375 has_attachment: true,
376 mentions_me: true,
377 };
378 assert!(filters.admits(&matching, today(), utc()));
379 assert!(!filters.admits(&plain, today(), utc()));
380 assert!(FindFilters::default().admits(&plain, today(), utc()));
381 let other_sender = FindFilters {
382 from: Some(Sender {
383 user_id: "8:orgid:other".into(),
384 name: "Other".into(),
385 }),
386 ..Default::default()
387 };
388 assert!(!other_sender.admits(&matching, today(), utc()));
389 }
390
391 #[test]
392 fn server_filters_scope_to_the_chat_and_map_chips() {
393 let filters = FindFilters {
394 from: Some(Sender {
395 user_id: "abc".into(),
396 name: "Lea".into(),
397 }),
398 date: Some(DateRange::Today),
399 has_attachment: true,
400 mentions_me: true,
401 };
402 assert_eq!(
403 filters.server_filters("19:chat@thread.v2"),
404 [
405 MessageFilter::InChat {
406 thread_id: "19:chat@thread.v2".into()
407 },
408 MessageFilter::FromSender {
409 mri: "8:orgid:abc".into()
410 },
411 MessageFilter::HasAttachment,
412 MessageFilter::MentionsMe,
413 ]
414 );
415 }
416
417 #[test]
418 fn local_snippet_markers_become_highlight_ranges() {
419 let search_hit = SearchHit {
420 conversation_id: "c".into(),
421 message_id: "m".into(),
422 sender_name: Some("Lea".into()),
423 created_at: Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap(),
424 snippet: format!("access is {HIGHLIGHT_START}ready{HIGHLIGHT_END} now"),
425 };
426 let found = from_local(&search_hit, None, None);
427 assert_eq!(found.text, "access is ready now");
428 assert_eq!(&found.text[found.highlights[0].clone()], "ready");
429 }
430
431 #[test]
432 fn stepping_wraps_in_both_directions() {
433 assert_eq!(step_index(None, 0, false), None);
434 assert_eq!(step_index(None, 3, false), Some(0));
435 assert_eq!(step_index(None, 3, true), Some(2));
436 assert_eq!(step_index(Some(2), 3, false), Some(0));
437 assert_eq!(step_index(Some(0), 3, true), Some(2));
438 }
439 }
@@ -0,0 +1,439 @@
1use std::collections::HashSet;
2use std::ops::Range;
3
4use chatsvc::substrate_search::{MessageFilter, SearchMessage, split_highlights};
5use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc};
6use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, SearchHit};
7
8pub const FIND_IN_CHAT: &str = "Find in chat";
9pub const FIND_IN_CHANNEL: &str = "Find in channel";
10pub const EMPTY_HINT: &str = "Find messages and links shared in this chat.";
11pub const NO_RESULTS_CHAT: &str = "We couldn't find any results in this chat";
12pub const NO_RESULTS_CHANNEL: &str = "We couldn't find any results in this channel";
13pub const LOAD_ERROR: &str = "Something went wrong while loading the results.";
14pub const LOADING: &str = "Fetching Data...";
15pub const FROM_LABEL: &str = "From";
16pub const DATE_LABEL: &str = "Date";
17pub const HAS_ATTACHMENT_LABEL: &str = "Has attachment";
18pub const MENTIONS_LABEL: &str = "@Mentions";
19pub const THIS_MONTH: &str = "This month";
20pub const LAST_MONTH: &str = "Last month";
21const ORG_PREFIX: &str = "8:orgid:";
22
23pub fn no_results_with_filters(search_term: &str) -> String {
24 format!("We couldn't find any results for '{search_term}' with the applied filters.")
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct FindHit {
29 pub message_id: String,
30 pub sent_at: DateTime<Utc>,
31 pub sender_name: String,
32 pub sender_id: Option<String>,
33 pub text: String,
34 pub highlights: Vec<Range<usize>>,
35 pub mentions_me: bool,
36 pub has_attachment: bool,
37}
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum DateRange {
41 Today,
42 Yesterday,
43 ThisWeek,
44 ThisMonth,
45}
46
47impl DateRange {
48 pub const ALL: [DateRange; 4] = [
49 DateRange::Today,
50 DateRange::Yesterday,
51 DateRange::ThisWeek,
52 DateRange::ThisMonth,
53 ];
54
55 pub fn label(self) -> &'static str {
56 match self {
57 DateRange::Today => "Today",
58 DateRange::Yesterday => "Yesterday",
59 DateRange::ThisWeek => "This week",
60 DateRange::ThisMonth => "This month",
61 }
62 }
63
64 pub fn contains(self, date: NaiveDate, today: NaiveDate) -> bool {
65 match self {
66 DateRange::Today => date == today,
67 DateRange::Yesterday => Some(date) == today.pred_opt(),
68 DateRange::ThisWeek => {
69 let week_start =
70 today - Duration::days(i64::from(today.weekday().num_days_from_monday()));
71 date >= week_start && date <= today
72 }
73 DateRange::ThisMonth => date.year() == today.year() && date.month() == today.month(),
74 }
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Sender {
80 pub user_id: String,
81 pub name: String,
82}
83
84#[derive(Debug, Clone, Default, PartialEq, Eq)]
85pub struct FindFilters {
86 pub from: Option<Sender>,
87 pub date: Option<DateRange>,
88 pub has_attachment: bool,
89 pub mentions_me: bool,
90}
91
92impl FindFilters {
93 pub fn is_active(&self) -> bool {
94 self.from.is_some() || self.date.is_some() || self.has_attachment || self.mentions_me
95 }
96
97 pub fn admits(&self, hit: &FindHit, today: NaiveDate, offset: FixedOffset) -> bool {
98 let from_holds = self.from.as_ref().is_none_or(|sender| {
99 hit.sender_id
100 .as_deref()
101 .is_some_and(|sender_id| same_user(sender_id, &sender.user_id))
102 });
103 let date_holds = self.date.is_none_or(|range| {
104 range.contains(hit.sent_at.with_timezone(&offset).date_naive(), today)
105 });
106 from_holds
107 && date_holds
108 && (!self.has_attachment || hit.has_attachment)
109 && (!self.mentions_me || hit.mentions_me)
110 }
111
112 pub fn server_filters(&self, thread_id: &str) -> Vec<MessageFilter> {
113 let mut filters = vec![MessageFilter::InChat {
114 thread_id: thread_id.to_owned(),
115 }];
116 if let Some(sender) = &self.from {
117 filters.push(MessageFilter::FromSender {
118 mri: user_mri(&sender.user_id),
119 });
120 }
121 if self.has_attachment {
122 filters.push(MessageFilter::HasAttachment);
123 }
124 if self.mentions_me {
125 filters.push(MessageFilter::MentionsMe);
126 }
127 filters
128 }
129}
130
131fn bare_user_id(user_id: &str) -> String {
132 user_id
133 .strip_prefix(ORG_PREFIX)
134 .unwrap_or(user_id)
135 .to_ascii_lowercase()
136}
137
138pub fn same_user(first: &str, second: &str) -> bool {
139 bare_user_id(first) == bare_user_id(second)
140}
141
142pub fn user_mri(user_id: &str) -> String {
143 if user_id.contains(':') {
144 user_id.to_owned()
145 } else {
146 format!("{ORG_PREFIX}{user_id}")
147 }
148}
149
150fn parse_local_snippet(snippet: &str) -> (String, Vec<Range<usize>>) {
151 let mut text = String::with_capacity(snippet.len());
152 let mut highlights = Vec::new();
153 let mut start = None;
154 for character in snippet.chars() {
155 match character {
156 HIGHLIGHT_START => start = Some(text.len()),
157 HIGHLIGHT_END => {
158 if let Some(begin) = start.take() {
159 highlights.push(begin..text.len());
160 }
161 }
162 _ => text.push(character),
163 }
164 }
165 (text, highlights)
166}
167
168pub fn from_local(hit: &SearchHit, record: Option<&MessageRecord>, my_id: Option<&str>) -> FindHit {
169 let (text, highlights) = parse_local_snippet(&hit.snippet);
170 FindHit {
171 message_id: hit.message_id.clone(),
172 sent_at: hit.created_at,
173 sender_name: hit.sender_name.clone().unwrap_or_default(),
174 sender_id: record.and_then(|record| record.sender_id.clone()),
175 text,
176 highlights,
177 mentions_me: record.is_some_and(|record| mentions_user(record, my_id)),
178 has_attachment: record.is_some_and(has_attachment),
179 }
180}
181
182pub fn from_record(record: &MessageRecord, my_id: Option<&str>) -> FindHit {
183 FindHit {
184 message_id: record.message_id.clone(),
185 sent_at: record.created_at,
186 sender_name: record.sender_name.clone().unwrap_or_default(),
187 sender_id: record.sender_id.clone(),
188 text: teams_core::preview_text(&record.body_html).unwrap_or_default(),
189 highlights: Vec::new(),
190 mentions_me: mentions_user(record, my_id),
191 has_attachment: has_attachment(record),
192 }
193}
194
195pub fn from_server(message: &SearchMessage) -> Option<FindHit> {
196 let sent_at = message.sent_at?;
197 let highlighted = split_highlights(
198 message
199 .highlighted_summary
200 .as_deref()
201 .unwrap_or(&message.preview),
202 );
203 Some(FindHit {
204 message_id: message.message_id.clone(),
205 sent_at,
206 sender_name: message.sender_name.clone().unwrap_or_default(),
207 sender_id: message.sender_mri.clone(),
208 text: highlighted.text,
209 highlights: highlighted.hits,
210 mentions_me: message.is_mentioned,
211 has_attachment: message.has_attachments,
212 })
213}
214
215fn mentions_user(record: &MessageRecord, my_id: Option<&str>) -> bool {
216 let Some(my_id) = my_id else {
217 return false;
218 };
219 teams_core::mentions(record).iter().any(|mention| {
220 mention
221 .user_id
222 .as_deref()
223 .is_some_and(|user_id| same_user(user_id, my_id))
224 })
225}
226
227fn has_attachment(record: &MessageRecord) -> bool {
228 !teams_core::files(record).is_empty() || !teams_core::images(record).is_empty()
229}
230
231pub fn merge(local: Vec<FindHit>, server: Vec<FindHit>) -> Vec<FindHit> {
232 let mut seen = HashSet::new();
233 let mut hits: Vec<FindHit> = local
234 .into_iter()
235 .chain(server)
236 .filter(|hit| seen.insert(hit.message_id.clone()))
237 .collect();
238 hits.sort_by(|first, second| {
239 second
240 .sent_at
241 .cmp(&first.sent_at)
242 .then_with(|| second.message_id.cmp(&first.message_id))
243 });
244 hits
245}
246
247pub fn month_label(date: NaiveDate, today: NaiveDate) -> String {
248 let months = |date: NaiveDate| date.year() * 12 + date.month0() as i32;
249 match months(today) - months(date) {
250 0 => THIS_MONTH.to_owned(),
251 1 => LAST_MONTH.to_owned(),
252 _ => date.format("%B %Y").to_string(),
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct MonthGroup {
258 pub label: String,
259 pub hits: Vec<FindHit>,
260}
261
262pub fn group_by_month(hits: &[FindHit], today: NaiveDate, offset: FixedOffset) -> Vec<MonthGroup> {
263 let mut groups: Vec<MonthGroup> = Vec::new();
264 for hit in hits {
265 let label = month_label(hit.sent_at.with_timezone(&offset).date_naive(), today);
266 match groups.last_mut() {
267 Some(group) if group.label == label => group.hits.push(hit.clone()),
268 _ => groups.push(MonthGroup {
269 label,
270 hits: vec![hit.clone()],
271 }),
272 }
273 }
274 groups
275}
276
277pub fn step_index(current: Option<usize>, count: usize, backwards: bool) -> Option<usize> {
278 if count == 0 {
279 return None;
280 }
281 Some(match (current, backwards) {
282 (None, false) => 0,
283 (None, true) => count - 1,
284 (Some(index), false) => (index + 1) % count,
285 (Some(index), true) => (index + count - 1) % count,
286 })
287}
288
289#[cfg(test)]
290mod tests {
291 use chrono::TimeZone;
292
293 use super::*;
294
295 fn utc() -> FixedOffset {
296 FixedOffset::east_opt(0).unwrap()
297 }
298
299 fn hit(message_id: &str, day: u32, month: u32) -> FindHit {
300 FindHit {
301 message_id: message_id.into(),
302 sent_at: Utc.with_ymd_and_hms(2026, month, day, 10, 0, 0).unwrap(),
303 sender_name: "Lea".into(),
304 sender_id: Some("8:orgid:ABC".into()),
305 text: message_id.into(),
306 highlights: Vec::new(),
307 mentions_me: false,
308 has_attachment: false,
309 }
310 }
311
312 fn today() -> NaiveDate {
313 NaiveDate::from_ymd_opt(2026, 10, 17).unwrap()
314 }
315
316 #[test]
317 fn merge_dedupes_by_message_id_and_sorts_newest_first() {
318 let local = vec![hit("a", 1, 10), hit("b", 5, 10)];
319 let mut server_copy = hit("a", 1, 10);
320 server_copy.text = "server".into();
321 let server = vec![server_copy, hit("c", 3, 10)];
322 let merged = merge(local, server);
323 let ids: Vec<&str> = merged.iter().map(|hit| hit.message_id.as_str()).collect();
324 assert_eq!(ids, ["b", "c", "a"]);
325 assert_eq!(merged[2].text, "a");
326 }
327
328 #[test]
329 fn groups_follow_teams_month_labels() {
330 let hits = vec![
331 hit("a", 16, 10),
332 hit("b", 2, 10),
333 hit("c", 30, 9),
334 hit("d", 1, 7),
335 ];
336 let groups = group_by_month(&hits, today(), utc());
337 let labels: Vec<(&str, usize)> = groups
338 .iter()
339 .map(|group| (group.label.as_str(), group.hits.len()))
340 .collect();
341 assert_eq!(labels, [(THIS_MONTH, 2), (LAST_MONTH, 1), ("July 2026", 1)]);
342 assert_eq!(
343 month_label(NaiveDate::from_ymd_opt(2025, 10, 3).unwrap(), today()),
344 "October 2025"
345 );
346 }
347
348 #[test]
349 fn date_ranges_use_the_local_calendar() {
350 let saturday = today();
351 let day = |day: u32| NaiveDate::from_ymd_opt(2026, 10, day).unwrap();
352 assert!(DateRange::Today.contains(day(17), saturday));
353 assert!(DateRange::Yesterday.contains(day(16), saturday));
354 assert!(!DateRange::Yesterday.contains(day(17), saturday));
355 assert!(DateRange::ThisWeek.contains(day(12), saturday));
356 assert!(!DateRange::ThisWeek.contains(day(11), saturday));
357 assert!(DateRange::ThisMonth.contains(day(1), saturday));
358 assert!(
359 !DateRange::ThisMonth.contains(NaiveDate::from_ymd_opt(2026, 9, 30).unwrap(), saturday)
360 );
361 }
362
363 #[test]
364 fn filters_admit_matching_hits_only() {
365 let mut matching = hit("a", 17, 10);
366 matching.has_attachment = true;
367 matching.mentions_me = true;
368 let plain = hit("b", 1, 10);
369 let filters = FindFilters {
370 from: Some(Sender {
371 user_id: "abc".into(),
372 name: "Lea".into(),
373 }),
374 date: Some(DateRange::Today),
375 has_attachment: true,
376 mentions_me: true,
377 };
378 assert!(filters.admits(&matching, today(), utc()));
379 assert!(!filters.admits(&plain, today(), utc()));
380 assert!(FindFilters::default().admits(&plain, today(), utc()));
381 let other_sender = FindFilters {
382 from: Some(Sender {
383 user_id: "8:orgid:other".into(),
384 name: "Other".into(),
385 }),
386 ..Default::default()
387 };
388 assert!(!other_sender.admits(&matching, today(), utc()));
389 }
390
391 #[test]
392 fn server_filters_scope_to_the_chat_and_map_chips() {
393 let filters = FindFilters {
394 from: Some(Sender {
395 user_id: "abc".into(),
396 name: "Lea".into(),
397 }),
398 date: Some(DateRange::Today),
399 has_attachment: true,
400 mentions_me: true,
401 };
402 assert_eq!(
403 filters.server_filters("19:chat@thread.v2"),
404 [
405 MessageFilter::InChat {
406 thread_id: "19:chat@thread.v2".into()
407 },
408 MessageFilter::FromSender {
409 mri: "8:orgid:abc".into()
410 },
411 MessageFilter::HasAttachment,
412 MessageFilter::MentionsMe,
413 ]
414 );
415 }
416
417 #[test]
418 fn local_snippet_markers_become_highlight_ranges() {
419 let search_hit = SearchHit {
420 conversation_id: "c".into(),
421 message_id: "m".into(),
422 sender_name: Some("Lea".into()),
423 created_at: Utc.with_ymd_and_hms(2026, 10, 17, 9, 0, 0).unwrap(),
424 snippet: format!("access is {HIGHLIGHT_START}ready{HIGHLIGHT_END} now"),
425 };
426 let found = from_local(&search_hit, None, None);
427 assert_eq!(found.text, "access is ready now");
428 assert_eq!(&found.text[found.highlights[0].clone()], "ready");
429 }
430
431 #[test]
432 fn stepping_wraps_in_both_directions() {
433 assert_eq!(step_index(None, 0, false), None);
434 assert_eq!(step_index(None, 3, false), Some(0));
435 assert_eq!(step_index(None, 3, true), Some(2));
436 assert_eq!(step_index(Some(2), 3, false), Some(0));
437 assert_eq!(step_index(Some(0), 3, true), Some(2));
438 }
439}
crates/app-state/src/lib.rs +5 −0
@@ -9,10 +9,15 @@ pub mod card_actions;
9 9 pub mod card_inputs;
10 10 pub mod card_refresh;
11 11 pub mod card_state;
12 pub mod channel_menu;
12 13 pub mod chat_actions;
14 pub mod chat_filter;
15 pub mod find_in_chat;
13 16 pub mod chat_members;
17 pub mod chat_settings_actions;
14 18 pub mod connection_banner;
15 19 pub mod data;
20 pub mod default_reactions;
16 21 pub mod delivery_options;
17 22 pub mod demo;
18 23 pub mod demo_meetings;
@@ -9,10 +9,15 @@ pub mod card_actions;
9pub mod card_inputs;
9pub mod card_inputs;
10pub mod card_refresh;
10pub mod card_refresh;
11pub mod card_state;
11pub mod card_state;
12pub mod channel_menu;
12pub mod chat_actions;
13pub mod chat_actions;
14pub mod chat_filter;
15pub mod find_in_chat;
13pub mod chat_members;
16pub mod chat_members;
17pub mod chat_settings_actions;
14pub mod connection_banner;
18pub mod connection_banner;
15pub mod data;
19pub mod data;
20pub mod default_reactions;
16pub mod delivery_options;
21pub mod delivery_options;
17pub mod demo;
22pub mod demo;
18pub mod demo_meetings;
23pub mod demo_meetings;
crates/app-state/src/message_actions.rs +34 −15
@@ -6,6 +6,7 @@ use store::MessageRecord;
6 6 use teams_core::{PinnedMessage, SavedMessage};
7 7
8 8 use crate::app_state::{AppEvent, AppState, Selection, selection_for};
9 use crate::channel_menu::{post_pin_failure, post_pin_notice};
9 10 use crate::format;
10 11 use crate::image_view_gallery::ViewerRequest;
11 12 use crate::notice::short_error;
@@ -229,6 +230,7 @@ impl AppState {
229 230 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
230 231 return;
231 232 };
233 let channel = self.channel_name(chat_id).is_some();
232 234 let previous = self.pinned_messages(chat_id).to_vec();
233 235 let parent_id = previous
234 236 .iter()
@@ -251,6 +253,9 @@ impl AppState {
251 253 }
252 254 self.store_pins(chat_id, updated, cx);
253 255 let Some(engine) = engine_or_demo else {
256 if channel {
257 self.raise_notice(post_pin_notice(pinned).to_owned(), None, cx);
258 }
254 259 return;
255 260 };
256 261 let (owned_chat, owned_message, revert_chat) = (
@@ -258,21 +263,35 @@ impl AppState {
258 263 message_id.to_owned(),
259 264 chat_id.to_owned(),
260 265 );
261 self.run_chat_action(
262 if pinned { "Pin" } else { "Unpin" },
263 async move {
264 if pinned {
265 engine.pin_message(&owned_chat, &owned_message).await
266 } else {
267 engine
268 .unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
269 .await
270 }
271 },
272 move |state, cx| state.store_pins(&revert_chat, previous, cx),
273 |_, _| {},
274 cx,
275 );
266 let call = async move {
267 if pinned {
268 engine.pin_message(&owned_chat, &owned_message).await
269 } else {
270 engine
271 .unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
272 .await
273 }
274 };
275 let revert = move |state: &mut Self, cx: &mut Context<Self>| {
276 state.store_pins(&revert_chat, previous, cx)
277 };
278 if channel {
279 self.run_channel_action(
280 post_pin_failure(pinned),
281 call,
282 revert,
283 Some(post_pin_notice(pinned)),
284 cx,
285 );
286 } else {
287 self.run_chat_action(
288 if pinned { "Pin" } else { "Unpin" },
289 call,
290 revert,
291 |_, _| {},
292 cx,
293 );
294 }
276 295 }
277 296
278 297 pub fn copy_message_link(
@@ -6,6 +6,7 @@ use store::MessageRecord;
6use teams_core::{PinnedMessage, SavedMessage};
6use teams_core::{PinnedMessage, SavedMessage};
7
7
8use crate::app_state::{AppEvent, AppState, Selection, selection_for};
8use crate::app_state::{AppEvent, AppState, Selection, selection_for};
9use crate::channel_menu::{post_pin_failure, post_pin_notice};
9use crate::format;
10use crate::format;
10use crate::image_view_gallery::ViewerRequest;
11use crate::image_view_gallery::ViewerRequest;
11use crate::notice::short_error;
12use crate::notice::short_error;
@@ -229,6 +230,7 @@ impl AppState {
229 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
230 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
230 return;
231 return;
231 };
232 };
233 let channel = self.channel_name(chat_id).is_some();
232 let previous = self.pinned_messages(chat_id).to_vec();
234 let previous = self.pinned_messages(chat_id).to_vec();
233 let parent_id = previous
235 let parent_id = previous
234 .iter()
236 .iter()
@@ -251,6 +253,9 @@ impl AppState {
251 }
253 }
252 self.store_pins(chat_id, updated, cx);
254 self.store_pins(chat_id, updated, cx);
253 let Some(engine) = engine_or_demo else {
255 let Some(engine) = engine_or_demo else {
256 if channel {
257 self.raise_notice(post_pin_notice(pinned).to_owned(), None, cx);
258 }
254 return;
259 return;
255 };
260 };
256 let (owned_chat, owned_message, revert_chat) = (
261 let (owned_chat, owned_message, revert_chat) = (
@@ -258,21 +263,35 @@ impl AppState {
258 message_id.to_owned(),
263 message_id.to_owned(),
259 chat_id.to_owned(),
264 chat_id.to_owned(),
260 );
265 );
261 self.run_chat_action(
266 let call = async move {
262 if pinned { "Pin" } else { "Unpin" },
267 if pinned {
263 async move {
268 engine.pin_message(&owned_chat, &owned_message).await
264 if pinned {
269 } else {
265 engine.pin_message(&owned_chat, &owned_message).await
270 engine
266 } else {
271 .unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
267 engine
272 .await
268 .unpin_message(&owned_chat, &owned_message, parent_id.as_deref())
273 }
269 .await
274 };
270 }
275 let revert = move |state: &mut Self, cx: &mut Context<Self>| {
271 },
276 state.store_pins(&revert_chat, previous, cx)
272 move |state, cx| state.store_pins(&revert_chat, previous, cx),
277 };
273 |_, _| {},
278 if channel {
274 cx,
279 self.run_channel_action(
275 );
280 post_pin_failure(pinned),
281 call,
282 revert,
283 Some(post_pin_notice(pinned)),
284 cx,
285 );
286 } else {
287 self.run_chat_action(
288 if pinned { "Pin" } else { "Unpin" },
289 call,
290 revert,
291 |_, _| {},
292 cx,
293 );
294 }
276 }
295 }
277
296
278 pub fn copy_message_link(
297 pub fn copy_message_link(
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,11 +172,33 @@ pub fn build_incoming(
171 172 mentions_me: mentions_me(record, my_user_id),
172 173 muted: is_muted_chat(sidebar, &record.conversation_id),
173 174 signals,
175 chat,
174 176 created_at: record.created_at,
175 177 importance: record.importance,
176 178 })
177 179 }
178 180
181 fn chat_signals(
182 store: &Store,
183 sidebar: &Sidebar,
184 conversation_id: &str,
185 my_user_id: Option<&str>,
186 ) -> ChatSignals {
187 let meeting = sidebar
188 .chats
189 .iter()
190 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));
191 let participated = meeting
192 && store
193 .messages(conversation_id, None, RECENT_WINDOW)
194 .is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));
195 ChatSignals {
196 meeting,
197 participated,
198 ..ChatSignals::default()
199 }
200 }
201
179 202 fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
180 203 sidebar
181 204 .chats
@@ -390,6 +413,27 @@ mod tests {
390 413 assert!(!build(&sidebar()).muted);
391 414 }
392 415
416 #[test]
417 fn meeting_chats_know_whether_i_took_part() {
418 let mut with_meeting = sidebar();
419 with_meeting.chats[1].kind = "meeting".into();
420 let store = Store::open_in_memory().unwrap();
421 let message = record("group", "u1", Utc::now(), "hi");
422 let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
423 assert!(first.chat.meeting);
424 assert!(!first.chat.participated);
425 let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");
426 store.upsert_messages(&[own]).unwrap();
427 let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
428 assert!(later.chat.participated);
429 assert!(
430 !build_incoming(&message, &store, &sidebar(), Some("me"))
431 .unwrap()
432 .chat
433 .meeting
434 );
435 }
436
393 437 #[test]
394 438 fn history_before_start_is_ignored() {
395 439 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,11 +172,33 @@ pub fn build_incoming(
171 mentions_me: mentions_me(record, my_user_id),
172 mentions_me: mentions_me(record, my_user_id),
172 muted: is_muted_chat(sidebar, &record.conversation_id),
173 muted: is_muted_chat(sidebar, &record.conversation_id),
173 signals,
174 signals,
175 chat,
174 created_at: record.created_at,
176 created_at: record.created_at,
175 importance: record.importance,
177 importance: record.importance,
176 })
178 })
177}
179}
178
180
181fn chat_signals(
182 store: &Store,
183 sidebar: &Sidebar,
184 conversation_id: &str,
185 my_user_id: Option<&str>,
186) -> ChatSignals {
187 let meeting = sidebar
188 .chats
189 .iter()
190 .any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case("meeting"));
191 let participated = meeting
192 && store
193 .messages(conversation_id, None, RECENT_WINDOW)
194 .is_ok_and(|records| records.iter().any(|record| is_own(record, my_user_id)));
195 ChatSignals {
196 meeting,
197 participated,
198 ..ChatSignals::default()
199 }
200}
201
179fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
202fn is_muted_chat(sidebar: &Sidebar, conversation_id: &str) -> bool {
180 sidebar
203 sidebar
181 .chats
204 .chats
@@ -390,6 +413,27 @@ mod tests {
390 assert!(!build(&sidebar()).muted);
413 assert!(!build(&sidebar()).muted);
391 }
414 }
392
415
416 #[test]
417 fn meeting_chats_know_whether_i_took_part() {
418 let mut with_meeting = sidebar();
419 with_meeting.chats[1].kind = "meeting".into();
420 let store = Store::open_in_memory().unwrap();
421 let message = record("group", "u1", Utc::now(), "hi");
422 let first = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
423 assert!(first.chat.meeting);
424 assert!(!first.chat.participated);
425 let own = record("group", "me", Utc::now() - Duration::minutes(1), "hello");
426 store.upsert_messages(&[own]).unwrap();
427 let later = build_incoming(&message, &store, &with_meeting, Some("me")).unwrap();
428 assert!(later.chat.participated);
429 assert!(
430 !build_incoming(&message, &store, &sidebar(), Some("me"))
431 .unwrap()
432 .chat
433 .meeting
434 );
435 }
436
393 #[test]
437 #[test]
394 fn history_before_start_is_ignored() {
438 fn history_before_start_is_ignored() {
395 let start = Utc::now();
439 let start = Utc::now();
crates/app-state/src/notify/rules.rs +127 −28
@@ -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, MessageImportance};
7 use teams_core::{
8 DesktopNotifications, MeetingChatNotifications, NotificationAccountSettings, NotificationPreset,
9 };
7 10
8 11 use super::sound_settings::SoundSettings;
9 12 use super::sounds::Ringtone;
@@ -69,8 +72,7 @@ impl Corner {
69 72
70 73 #[derive(Debug, Clone, PartialEq, Eq)]
71 74 pub struct Settings {
72 pub mentions_only: bool,
73 pub preview: bool,
75 pub account: NotificationAccountSettings,
74 76 pub corner: Corner,
75 77 pub flash: bool,
76 78 pub close_to_tray: bool,
@@ -82,8 +84,7 @@ pub struct Settings {
82 84 impl Default for Settings {
83 85 fn default() -> Self {
84 86 Settings {
85 mentions_only: false,
86 preview: true,
87 account: NotificationAccountSettings::default(),
87 88 corner: Corner::BottomRight,
88 89 flash: true,
89 90 close_to_tray: true,
@@ -116,6 +117,13 @@ pub struct ChannelSignals {
116 117 pub notifications: ChannelNotifications,
117 118 }
118 119
120 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
121 pub struct ChatSignals {
122 pub meeting: bool,
123 pub participated: bool,
124 pub desktop: DesktopNotifications,
125 }
126
119 127 #[derive(Debug, Clone, PartialEq, Eq)]
120 128 pub struct Incoming {
121 129 pub conversation_id: String,
@@ -128,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 pub importance: MessageImportance,
133 142 }
@@ -207,6 +216,36 @@ fn channel_toasts(incoming: &Incoming) -> bool {
207 216 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
208 217 }
209 218
219 fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {
220 if matches!(incoming.kind, ChatKind::Channel { .. }) {
221 return if incoming.mentions_me {
222 account.personal_mentions.shows_banner()
223 } else {
224 account.preset != NotificationPreset::MentionsAndReplies
225 || incoming.signals.in_my_thread
226 };
227 }
228 let chat = incoming.chat;
229 if chat.desktop == DesktopNotifications::Off {
230 return false;
231 }
232 if incoming.mentions_me {
233 return account.personal_mentions.shows_banner();
234 }
235 let meeting_muted = chat.meeting
236 && match account.meeting_chats {
237 MeetingChatNotifications::Mute => true,
238 MeetingChatNotifications::MuteUntilJoin => !chat.participated,
239 MeetingChatNotifications::Unmute => false,
240 };
241 !meeting_muted
242 && (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())
243 }
244
245 pub fn shows_preview(settings: &Settings) -> bool {
246 settings.account.show_preview
247 }
248
210 249 const SILENT: Decision = Decision {
211 250 toast: false,
212 251 sound: false,
@@ -223,7 +262,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
223 262 || (environment.own_do_not_disturb && !urgent)
224 263 || settings.do_not_disturb
225 264 || (settings.mute_in_calls && environment.in_call)
226 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct() && !urgent);
265 || (!urgent && !account_toasts(&settings.account, incoming));
227 266 if suppressed {
228 267 return SILENT;
229 268 }
@@ -278,6 +317,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)
278 317 #[cfg(test)]
279 318 mod tests {
280 319 use calling::{CallState, EndReason};
320 use teams_core::ActivityAlert;
281 321
282 322 use super::*;
283 323
@@ -293,6 +333,7 @@ mod tests {
293 333 mentions_me: false,
294 334 muted: false,
295 335 signals: ChannelSignals::default(),
336 chat: ChatSignals::default(),
296 337 created_at: Utc::now(),
297 338 importance: Default::default(),
298 339 }
@@ -360,7 +401,7 @@ mod tests {
360 401 }
361 402
362 403 #[test]
363 fn urgent_passes_do_not_disturb_and_mentions_only_with_the_urgent_sound() {
404 fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {
364 405 let dnd = Environment {
365 406 own_do_not_disturb: true,
366 407 ..Default::default()
@@ -373,11 +414,9 @@ mod tests {
373 414 urgent_sound: true,
374 415 }
375 416 );
376 let mentions_only = Settings {
377 mentions_only: true,
378 ..Default::default()
379 };
380 assert!(decide(&mentions_only, &urgent(), Environment::default()).toast);
417 let mut chat_off = urgent();
418 chat_off.chat.desktop = DesktopNotifications::Off;
419 assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);
381 420 let foreground = Environment {
382 421 chat_in_foreground: true,
383 422 ..Default::default()
@@ -553,24 +592,84 @@ mod tests {
553 592 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
554 593 }
555 594
595 fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {
596 let mut settings = Settings::default();
597 change(&mut settings.account);
598 settings
599 }
600
601 fn toasts(settings: &Settings, incoming: &Incoming) -> bool {
602 decide(settings, incoming, Environment::default()).toast
603 }
604
605 fn mention(mut incoming: Incoming) -> Incoming {
606 incoming.mentions_me = true;
607 incoming
608 }
609
556 610 #[test]
557 fn mentions_only_keeps_direct_and_mentions() {
558 let settings = Settings {
559 mentions_only: true,
560 ..Default::default()
561 };
562 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
563 assert!(
564 decide(
565 &settings,
566 &incoming(ChatKind::Direct),
567 Environment::default()
568 )
569 .toast
570 );
571 let mut mention = group();
572 mention.mentions_me = true;
573 assert!(decide(&settings, &mention, Environment::default()).toast);
611 fn chat_message_notifications_off_keeps_personal_mentions() {
612 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
613 assert!(!toasts(&settings, &group()));
614 assert!(!toasts(&settings, &incoming(ChatKind::Direct)));
615 assert!(toasts(&settings, &mention(group())));
616 }
617
618 #[test]
619 fn personal_mentions_only_in_activity_give_no_banner() {
620 let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);
621 assert!(!toasts(&settings, &mention(group())));
622 assert!(!toasts(&settings, &mention(channel())));
623 assert!(toasts(&settings, &group()));
624 }
625
626 #[test]
627 fn mentions_and_replies_preset_drops_plain_channel_posts() {
628 let settings =
629 with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);
630 let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
631 assert!(!toasts(&settings, &post));
632 post.signals.in_my_thread = true;
633 assert!(toasts(&settings, &post));
634 assert!(toasts(&settings, &mention(channel())));
635 assert!(toasts(&settings, &group()));
636 }
637
638 fn meeting_chat(participated: bool) -> Incoming {
639 let mut message = group();
640 message.chat.meeting = true;
641 message.chat.participated = participated;
642 message
643 }
644
645 #[test]
646 fn meeting_chats_stay_quiet_until_i_take_part() {
647 let settings = Settings::default();
648 assert!(!toasts(&settings, &meeting_chat(false)));
649 assert!(toasts(&settings, &meeting_chat(true)));
650 assert!(toasts(&settings, &mention(meeting_chat(false))));
651 }
652
653 #[test]
654 fn meeting_chat_mute_and_unmute() {
655 let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);
656 assert!(!toasts(&muted, &meeting_chat(true)));
657 assert!(toasts(&muted, &mention(meeting_chat(true))));
658 let unmuted =
659 with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);
660 assert!(toasts(&unmuted, &meeting_chat(false)));
661 }
662
663 #[test]
664 fn per_chat_desktop_preference_overrides_the_account() {
665 let mut silenced = group();
666 silenced.chat.desktop = DesktopNotifications::Off;
667 assert!(!toasts(&Settings::default(), &silenced));
668 assert!(!toasts(&Settings::default(), &mention(silenced)));
669 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
670 let mut selected = group();
671 selected.chat.desktop = DesktopNotifications::On;
672 assert!(toasts(&settings, &selected));
574 673 }
575 674
576 675 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, MessageImportance};
6use store::{ChannelNotificationLevel, ChannelNotifications, MessageImportance};
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 pub importance: MessageImportance,
141 pub importance: MessageImportance,
133}
142}
@@ -207,6 +216,36 @@ fn channel_toasts(incoming: &Incoming) -> bool {
207 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
216 || signals.notifications.level == ChannelNotificationLevel::BannerAndFeed
208}
217}
209
218
219fn account_toasts(account: &NotificationAccountSettings, incoming: &Incoming) -> bool {
220 if matches!(incoming.kind, ChatKind::Channel { .. }) {
221 return if incoming.mentions_me {
222 account.personal_mentions.shows_banner()
223 } else {
224 account.preset != NotificationPreset::MentionsAndReplies
225 || incoming.signals.in_my_thread
226 };
227 }
228 let chat = incoming.chat;
229 if chat.desktop == DesktopNotifications::Off {
230 return false;
231 }
232 if incoming.mentions_me {
233 return account.personal_mentions.shows_banner();
234 }
235 let meeting_muted = chat.meeting
236 && match account.meeting_chats {
237 MeetingChatNotifications::Mute => true,
238 MeetingChatNotifications::MuteUntilJoin => !chat.participated,
239 MeetingChatNotifications::Unmute => false,
240 };
241 !meeting_muted
242 && (chat.desktop == DesktopNotifications::On || account.chat_messages.shows_banner())
243}
244
245pub fn shows_preview(settings: &Settings) -> bool {
246 settings.account.show_preview
247}
248
210const SILENT: Decision = Decision {
249const SILENT: Decision = Decision {
211 toast: false,
250 toast: false,
212 sound: false,
251 sound: false,
@@ -223,7 +262,7 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
223 || (environment.own_do_not_disturb && !urgent)
262 || (environment.own_do_not_disturb && !urgent)
224 || settings.do_not_disturb
263 || settings.do_not_disturb
225 || (settings.mute_in_calls && environment.in_call)
264 || (settings.mute_in_calls && environment.in_call)
226 || (settings.mentions_only && !incoming.mentions_me && !incoming.is_direct() && !urgent);
265 || (!urgent && !account_toasts(&settings.account, incoming));
227 if suppressed {
266 if suppressed {
228 return SILENT;
267 return SILENT;
229 }
268 }
@@ -278,6 +317,7 @@ pub fn should_flash(settings: &Settings, toast_shown: bool, window_active: bool)
278#[cfg(test)]
317#[cfg(test)]
279mod tests {
318mod tests {
280 use calling::{CallState, EndReason};
319 use calling::{CallState, EndReason};
320 use teams_core::ActivityAlert;
281
321
282 use super::*;
322 use super::*;
283
323
@@ -293,6 +333,7 @@ mod tests {
293 mentions_me: false,
333 mentions_me: false,
294 muted: false,
334 muted: false,
295 signals: ChannelSignals::default(),
335 signals: ChannelSignals::default(),
336 chat: ChatSignals::default(),
296 created_at: Utc::now(),
337 created_at: Utc::now(),
297 importance: Default::default(),
338 importance: Default::default(),
298 }
339 }
@@ -360,7 +401,7 @@ mod tests {
360 }
401 }
361
402
362 #[test]
403 #[test]
363 fn urgent_passes_do_not_disturb_and_mentions_only_with_the_urgent_sound() {
404 fn urgent_passes_do_not_disturb_and_the_account_rules_with_the_urgent_sound() {
364 let dnd = Environment {
405 let dnd = Environment {
365 own_do_not_disturb: true,
406 own_do_not_disturb: true,
366 ..Default::default()
407 ..Default::default()
@@ -373,11 +414,9 @@ mod tests {
373 urgent_sound: true,
414 urgent_sound: true,
374 }
415 }
375 );
416 );
376 let mentions_only = Settings {
417 let mut chat_off = urgent();
377 mentions_only: true,
418 chat_off.chat.desktop = DesktopNotifications::Off;
378 ..Default::default()
419 assert!(decide(&Settings::default(), &chat_off, Environment::default()).toast);
379 };
380 assert!(decide(&mentions_only, &urgent(), Environment::default()).toast);
381 let foreground = Environment {
420 let foreground = Environment {
382 chat_in_foreground: true,
421 chat_in_foreground: true,
383 ..Default::default()
422 ..Default::default()
@@ -553,24 +592,84 @@ mod tests {
553 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
592 assert!(decide(&Settings::default(), &muted, Environment::default()).toast);
554 }
593 }
555
594
595 fn with_account(change: impl FnOnce(&mut NotificationAccountSettings)) -> Settings {
596 let mut settings = Settings::default();
597 change(&mut settings.account);
598 settings
599 }
600
601 fn toasts(settings: &Settings, incoming: &Incoming) -> bool {
602 decide(settings, incoming, Environment::default()).toast
603 }
604
605 fn mention(mut incoming: Incoming) -> Incoming {
606 incoming.mentions_me = true;
607 incoming
608 }
609
556 #[test]
610 #[test]
557 fn mentions_only_keeps_direct_and_mentions() {
611 fn chat_message_notifications_off_keeps_personal_mentions() {
558 let settings = Settings {
612 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
559 mentions_only: true,
613 assert!(!toasts(&settings, &group()));
560 ..Default::default()
614 assert!(!toasts(&settings, &incoming(ChatKind::Direct)));
561 };
615 assert!(toasts(&settings, &mention(group())));
562 assert_eq!(decide(&settings, &group(), Environment::default()), SILENT);
616 }
563 assert!(
617
564 decide(
618 #[test]
565 &settings,
619 fn personal_mentions_only_in_activity_give_no_banner() {
566 &incoming(ChatKind::Direct),
620 let settings = with_account(|account| account.personal_mentions = ActivityAlert::OnlyFeed);
567 Environment::default()
621 assert!(!toasts(&settings, &mention(group())));
568 )
622 assert!(!toasts(&settings, &mention(channel())));
569 .toast
623 assert!(toasts(&settings, &group()));
570 );
624 }
571 let mut mention = group();
625
572 mention.mentions_me = true;
626 #[test]
573 assert!(decide(&settings, &mention, Environment::default()).toast);
627 fn mentions_and_replies_preset_drops_plain_channel_posts() {
628 let settings =
629 with_account(|account| account.preset = NotificationPreset::MentionsAndReplies);
630 let mut post = channel_with(ChannelNotificationLevel::BannerAndFeed, true);
631 assert!(!toasts(&settings, &post));
632 post.signals.in_my_thread = true;
633 assert!(toasts(&settings, &post));
634 assert!(toasts(&settings, &mention(channel())));
635 assert!(toasts(&settings, &group()));
636 }
637
638 fn meeting_chat(participated: bool) -> Incoming {
639 let mut message = group();
640 message.chat.meeting = true;
641 message.chat.participated = participated;
642 message
643 }
644
645 #[test]
646 fn meeting_chats_stay_quiet_until_i_take_part() {
647 let settings = Settings::default();
648 assert!(!toasts(&settings, &meeting_chat(false)));
649 assert!(toasts(&settings, &meeting_chat(true)));
650 assert!(toasts(&settings, &mention(meeting_chat(false))));
651 }
652
653 #[test]
654 fn meeting_chat_mute_and_unmute() {
655 let muted = with_account(|account| account.meeting_chats = MeetingChatNotifications::Mute);
656 assert!(!toasts(&muted, &meeting_chat(true)));
657 assert!(toasts(&muted, &mention(meeting_chat(true))));
658 let unmuted =
659 with_account(|account| account.meeting_chats = MeetingChatNotifications::Unmute);
660 assert!(toasts(&unmuted, &meeting_chat(false)));
661 }
662
663 #[test]
664 fn per_chat_desktop_preference_overrides_the_account() {
665 let mut silenced = group();
666 silenced.chat.desktop = DesktopNotifications::Off;
667 assert!(!toasts(&Settings::default(), &silenced));
668 assert!(!toasts(&Settings::default(), &mention(silenced)));
669 let settings = with_account(|account| account.chat_messages = ActivityAlert::Off);
670 let mut selected = group();
671 selected.chat.desktop = DesktopNotifications::On;
672 assert!(toasts(&settings, &selected));
574 }
673 }
575
674
576 fn channel_with(level: ChannelNotificationLevel, include_replies: bool) -> Incoming {
675 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
@@ -426,6 +426,7 @@ mod tests {
426 426 mentions_me: mention,
427 427 muted: false,
428 428 signals: Default::default(),
429 chat: Default::default(),
429 430 created_at: chrono::Utc::now(),
430 431 importance: Default::default(),
431 432 }
@@ -426,6 +426,7 @@ mod tests {
426 mentions_me: mention,
426 mentions_me: mention,
427 muted: false,
427 muted: false,
428 signals: Default::default(),
428 signals: Default::default(),
429 chat: Default::default(),
429 created_at: chrono::Utc::now(),
430 created_at: chrono::Utc::now(),
430 importance: Default::default(),
431 importance: Default::default(),
431 }
432 }
crates/app-state/src/notify/urgent_repeat.rs +1 −0
@@ -105,6 +105,7 @@ mod tests {
105 105 mentions_me: false,
106 106 muted: false,
107 107 signals: Default::default(),
108 chat: Default::default(),
108 109 created_at: sent_at(),
109 110 importance,
110 111 }
@@ -105,6 +105,7 @@ mod tests {
105 mentions_me: false,
105 mentions_me: false,
106 muted: false,
106 muted: false,
107 signals: Default::default(),
107 signals: Default::default(),
108 chat: Default::default(),
108 created_at: sent_at(),
109 created_at: sent_at(),
109 importance,
110 importance,
110 }
111 }
crates/app-state/src/profile_state.rs +24 −2
@@ -120,11 +120,33 @@ impl AppState {
120 120 }
121 121
122 122 pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
123 self.with_one_on_one(user_id, cx, |state, chat_id, cx| {
124 state.select(Selection::Chat(chat_id.to_owned()), cx)
125 });
126 }
127
128 /// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.
129 pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {
130 self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {
131 if with_video {
132 state.start_chat_video_call(chat_id, cx);
133 } else {
134 state.start_chat_call(chat_id, cx);
135 }
136 });
137 }
138
139 fn with_one_on_one(
140 &mut self,
141 user_id: &str,
142 cx: &mut Context<Self>,
143 then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,
144 ) {
123 145 let existing =
124 146 existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
125 147 .map(|chat| chat.id.clone());
126 148 if let Some(chat_id) = existing {
127 self.select(Selection::Chat(chat_id), cx);
149 then(self, &chat_id, cx);
128 150 return;
129 151 }
130 152 if self.mode.read_only {
@@ -149,7 +171,7 @@ impl AppState {
149 171 this.update(cx, |state, cx| match outcome {
150 172 Ok(chat_id) => {
151 173 state.reload_sidebar(cx);
152 state.select(Selection::Chat(chat_id), cx);
174 then(state, &chat_id, cx);
153 175 }
154 176 Err(reason) => {
155 177 state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
@@ -120,11 +120,33 @@ impl AppState {
120 }
120 }
121
121
122 pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
122 pub fn open_chat_with(&mut self, user_id: &str, cx: &mut Context<Self>) {
123 self.with_one_on_one(user_id, cx, |state, chat_id, cx| {
124 state.select(Selection::Chat(chat_id.to_owned()), cx)
125 });
126 }
127
128 /// Teams starts a 1:1 call from the profile card; the 1:1 chat is the call thread.
129 pub fn call_person(&mut self, user_id: &str, with_video: bool, cx: &mut Context<Self>) {
130 self.with_one_on_one(user_id, cx, move |state, chat_id, cx| {
131 if with_video {
132 state.start_chat_video_call(chat_id, cx);
133 } else {
134 state.start_chat_call(chat_id, cx);
135 }
136 });
137 }
138
139 fn with_one_on_one(
140 &mut self,
141 user_id: &str,
142 cx: &mut Context<Self>,
143 then: impl FnOnce(&mut Self, &str, &mut Context<Self>) + 'static,
144 ) {
123 let existing =
145 let existing =
124 existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
146 existing_one_on_one(&self.sidebar.chats, self.directory.me.as_ref(), user_id)
125 .map(|chat| chat.id.clone());
147 .map(|chat| chat.id.clone());
126 if let Some(chat_id) = existing {
148 if let Some(chat_id) = existing {
127 self.select(Selection::Chat(chat_id), cx);
149 then(self, &chat_id, cx);
128 return;
150 return;
129 }
151 }
130 if self.mode.read_only {
152 if self.mode.read_only {
@@ -149,7 +171,7 @@ impl AppState {
149 this.update(cx, |state, cx| match outcome {
171 this.update(cx, |state, cx| match outcome {
150 Ok(chat_id) => {
172 Ok(chat_id) => {
151 state.reload_sidebar(cx);
173 state.reload_sidebar(cx);
152 state.select(Selection::Chat(chat_id), cx);
174 then(state, &chat_id, cx);
153 }
175 }
154 Err(reason) => {
176 Err(reason) => {
155 state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
177 state.raise_notice(format!("Chat could not be opened: {reason}"), None, cx)
crates/app-ui-kit/src/lib.rs +4 −0
@@ -2,9 +2,13 @@ pub mod card_chart;
2 2 pub mod channel_tabs;
3 3 pub mod draft_style;
4 4 pub mod layout;
5 pub mod long_press;
5 6 pub mod reaction_proposal_pill;
6 7 pub mod render;
7 8 pub mod scroll_edge;
8 9 pub mod settings_controls;
9 10 pub mod spinner;
10 11 pub mod widgets;
12
13 #[cfg(test)]
14 mod touch_scroll;
@@ -2,9 +2,13 @@ pub mod card_chart;
2pub mod channel_tabs;
2pub mod channel_tabs;
3pub mod draft_style;
3pub mod draft_style;
4pub mod layout;
4pub mod layout;
5pub mod long_press;
5pub mod reaction_proposal_pill;
6pub mod reaction_proposal_pill;
6pub mod render;
7pub mod render;
7pub mod scroll_edge;
8pub mod scroll_edge;
8pub mod settings_controls;
9pub mod settings_controls;
9pub mod spinner;
10pub mod spinner;
10pub mod widgets;
11pub mod widgets;
12
13#[cfg(test)]
14mod touch_scroll;
crates/app-ui-kit/src/long_press.rs added +40 −0
@@ -0,0 +1,40 @@
1 use gpui_kit::*;
2
3 pub fn long_press_right_click() -> impl IntoElement {
4 canvas(
5 |_, _, _| {},
6 |_, _, window, _| {
7 window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {
8 if phase != DispatchPhase::Bubble
9 || event.phase != TouchPhase::Started
10 || window.default_prevented()
11 {
12 return;
13 }
14 window.prevent_default();
15 let position = event.start_position;
16 window.defer(cx, move |window, cx| {
17 window.dispatch_event(
18 PlatformInput::MouseDown(MouseDownEvent {
19 button: MouseButton::Right,
20 position,
21 modifiers: Modifiers::default(),
22 click_count: 1,
23 first_mouse: false,
24 }),
25 cx,
26 );
27 window.dispatch_event(
28 PlatformInput::MouseUp(MouseUpEvent {
29 button: MouseButton::Right,
30 position,
31 modifiers: Modifiers::default(),
32 click_count: 1,
33 }),
34 cx,
35 );
36 });
37 });
38 },
39 )
40 }
@@ -0,0 +1,40 @@
1use gpui_kit::*;
2
3pub fn long_press_right_click() -> impl IntoElement {
4 canvas(
5 |_, _, _| {},
6 |_, _, window, _| {
7 window.on_mouse_event(|event: &LongPressEvent, phase, window, cx| {
8 if phase != DispatchPhase::Bubble
9 || event.phase != TouchPhase::Started
10 || window.default_prevented()
11 {
12 return;
13 }
14 window.prevent_default();
15 let position = event.start_position;
16 window.defer(cx, move |window, cx| {
17 window.dispatch_event(
18 PlatformInput::MouseDown(MouseDownEvent {
19 button: MouseButton::Right,
20 position,
21 modifiers: Modifiers::default(),
22 click_count: 1,
23 first_mouse: false,
24 }),
25 cx,
26 );
27 window.dispatch_event(
28 PlatformInput::MouseUp(MouseUpEvent {
29 button: MouseButton::Right,
30 position,
31 modifiers: Modifiers::default(),
32 click_count: 1,
33 }),
34 cx,
35 );
36 });
37 });
38 },
39 )
40}
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/touch_scroll.rs added +223 −0
@@ -0,0 +1,223 @@
1 use std::cell::Cell;
2 use std::rc::Rc;
3 use std::time::Duration;
4
5 use crate::long_press::long_press_right_click;
6 use gpui_kit::{
7 Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,
8 ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,
9 TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,
10 px,
11 };
12
13 const ROW_HEIGHT: f32 = 40.;
14 const ROW_COUNT: usize = 60;
15
16 #[derive(Clone, Default)]
17 struct Clicks {
18 left: Rc<Cell<usize>>,
19 right: Rc<Cell<usize>>,
20 }
21
22 struct ScrollContainer {
23 scroll_handle: ScrollHandle,
24 clicks: Clicks,
25 }
26
27 impl Render for ScrollContainer {
28 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
29 let clicks = self.clicks.clone();
30 div().size_full().child(long_press_right_click()).child(
31 div()
32 .id("scroll-container")
33 .size_full()
34 .overflow_y_scroll()
35 .track_scroll(&self.scroll_handle)
36 .children((0..ROW_COUNT).map(|row_index| {
37 let left = clicks.left.clone();
38 let right = clicks.right.clone();
39 div()
40 .id(row_index)
41 .h(px(ROW_HEIGHT))
42 .flex_none()
43 .w_full()
44 .on_click(move |_, _, _| left.set(left.get() + 1))
45 .on_mouse_down(MouseButton::Right, move |_, _, _| {
46 right.set(right.get() + 1)
47 })
48 })),
49 )
50 }
51 }
52
53 struct VirtualList {
54 list_state: ListState,
55 }
56
57 impl Render for VirtualList {
58 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
59 list(self.list_state.clone(), |row_index, _, _| {
60 div()
61 .id(row_index)
62 .h(px(ROW_HEIGHT))
63 .flex_none()
64 .w_full()
65 .into_any_element()
66 })
67 .size_full()
68 }
69 }
70
71 struct Finger<'a> {
72 window_cx: &'a mut VisualTestContext,
73 touch_id: TouchId,
74 }
75
76 impl Finger<'_> {
77 fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {
78 self.window_cx.simulate_event(TouchEvent {
79 id: self.touch_id,
80 phase,
81 position: point(px(x), px(y)),
82 predicted_position: None,
83 force: None,
84 });
85 self.window_cx
86 .executor()
87 .advance_clock(Duration::from_millis(8));
88 }
89
90 fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {
91 self.touch(TouchPhase::Started, 100., from_y);
92 for step in 1..=steps {
93 let progress = step as f32 / steps as f32;
94 self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);
95 }
96 self.touch(TouchPhase::Ended, 100., to_y);
97 }
98
99 fn tap(&mut self, x: f32, y: f32) {
100 self.touch(TouchPhase::Started, x, y);
101 self.touch(TouchPhase::Ended, x, y);
102 self.window_cx
103 .executor()
104 .advance_clock(Duration::from_millis(500));
105 }
106 }
107
108 fn open_scroll_container(
109 cx: &mut TestAppContext,
110 ) -> (ScrollHandle, Clicks, &mut VisualTestContext) {
111 cx.update(gpui_kit::init);
112 let scroll_handle = ScrollHandle::new();
113 let clicks = Clicks::default();
114 let (_, window_cx) = cx.add_window_view({
115 let scroll_handle = scroll_handle.clone();
116 let clicks = clicks.clone();
117 move |_, _| ScrollContainer {
118 scroll_handle,
119 clicks,
120 }
121 });
122 window_cx.update(|window, cx| window.draw(cx).clear(cx));
123 (scroll_handle, clicks, window_cx)
124 }
125
126 fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {
127 for _ in 0..frame_count {
128 window_cx
129 .executor()
130 .advance_clock(Duration::from_millis(16));
131 window_cx.update(|window, cx| {
132 window.simulate_next_frame(cx);
133 window.draw(cx).clear(cx);
134 });
135 }
136 }
137
138 #[gpui_kit::test]
139 fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {
140 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
141 let mut finger = Finger {
142 window_cx,
143 touch_id: TouchId(1),
144 };
145 finger.pan(300., 180., 30);
146 let offset_y = f32::from(scroll_handle.offset().y);
147 assert!(
148 (-120.5..=-100.).contains(&offset_y),
149 "a 120 px slow pan scrolls about 120 px, got {offset_y}"
150 );
151 assert_eq!(clicks.left.get(), 0, "a pan never clicks");
152 }
153
154 #[gpui_kit::test]
155 fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {
156 let (scroll_handle, _, window_cx) = open_scroll_container(cx);
157 let mut finger = Finger {
158 window_cx,
159 touch_id: TouchId(1),
160 };
161 finger.pan(300., 100., 5);
162 let released_at = f32::from(scroll_handle.offset().y);
163 run_frames(finger.window_cx, 30);
164 let coasted_to = f32::from(scroll_handle.offset().y);
165 assert!(
166 coasted_to < released_at - 50.,
167 "momentum continues the scroll after release: {released_at} -> {coasted_to}"
168 );
169 }
170
171 #[gpui_kit::test]
172 fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {
173 let (_, clicks, window_cx) = open_scroll_container(cx);
174 let mut finger = Finger {
175 window_cx,
176 touch_id: TouchId(1),
177 };
178 finger.tap(100., 60.);
179 assert_eq!(clicks.left.get(), 1);
180 }
181
182 #[gpui_kit::test]
183 fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {
184 cx.update(gpui_kit::init);
185 let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));
186 let (_, window_cx) = cx.add_window_view({
187 let list_state = list_state.clone();
188 move |_, _| VirtualList { list_state }
189 });
190 window_cx.update(|window, cx| window.draw(cx).clear(cx));
191 let mut finger = Finger {
192 window_cx,
193 touch_id: TouchId(1),
194 };
195 finger.pan(300., 100., 30);
196 let scroll_top = list_state.logical_scroll_top();
197 let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);
198 assert!(
199 (180.0..=200.5).contains(&scrolled),
200 "a 200 px slow pan scrolls the list about 200 px, got {scrolled}"
201 );
202 }
203
204 #[gpui_kit::test]
205 fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {
206 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
207 let mut finger = Finger {
208 window_cx,
209 touch_id: TouchId(1),
210 };
211 finger.touch(TouchPhase::Started, 100., 60.);
212 finger
213 .window_cx
214 .executor()
215 .advance_clock(Duration::from_millis(600));
216 finger.window_cx.run_until_parked();
217 finger.touch(TouchPhase::Moved, 100., 20.);
218 finger.touch(TouchPhase::Ended, 100., 20.);
219 finger.window_cx.run_until_parked();
220 assert_eq!(clicks.right.get(), 1);
221 assert_eq!(clicks.left.get(), 0);
222 assert_eq!(f32::from(scroll_handle.offset().y), 0.);
223 }
@@ -0,0 +1,223 @@
1use std::cell::Cell;
2use std::rc::Rc;
3use std::time::Duration;
4
5use crate::long_press::long_press_right_click;
6use gpui_kit::{
7 Context, InteractiveElement as _, IntoElement, ListAlignment, ListState, MouseButton,
8 ParentElement as _, Render, ScrollHandle, StatefulInteractiveElement as _, Styled as _,
9 TestAppContext, TouchEvent, TouchId, TouchPhase, VisualTestContext, Window, div, list, point,
10 px,
11};
12
13const ROW_HEIGHT: f32 = 40.;
14const ROW_COUNT: usize = 60;
15
16#[derive(Clone, Default)]
17struct Clicks {
18 left: Rc<Cell<usize>>,
19 right: Rc<Cell<usize>>,
20}
21
22struct ScrollContainer {
23 scroll_handle: ScrollHandle,
24 clicks: Clicks,
25}
26
27impl Render for ScrollContainer {
28 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
29 let clicks = self.clicks.clone();
30 div().size_full().child(long_press_right_click()).child(
31 div()
32 .id("scroll-container")
33 .size_full()
34 .overflow_y_scroll()
35 .track_scroll(&self.scroll_handle)
36 .children((0..ROW_COUNT).map(|row_index| {
37 let left = clicks.left.clone();
38 let right = clicks.right.clone();
39 div()
40 .id(row_index)
41 .h(px(ROW_HEIGHT))
42 .flex_none()
43 .w_full()
44 .on_click(move |_, _, _| left.set(left.get() + 1))
45 .on_mouse_down(MouseButton::Right, move |_, _, _| {
46 right.set(right.get() + 1)
47 })
48 })),
49 )
50 }
51}
52
53struct VirtualList {
54 list_state: ListState,
55}
56
57impl Render for VirtualList {
58 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
59 list(self.list_state.clone(), |row_index, _, _| {
60 div()
61 .id(row_index)
62 .h(px(ROW_HEIGHT))
63 .flex_none()
64 .w_full()
65 .into_any_element()
66 })
67 .size_full()
68 }
69}
70
71struct Finger<'a> {
72 window_cx: &'a mut VisualTestContext,
73 touch_id: TouchId,
74}
75
76impl Finger<'_> {
77 fn touch(&mut self, phase: TouchPhase, x: f32, y: f32) {
78 self.window_cx.simulate_event(TouchEvent {
79 id: self.touch_id,
80 phase,
81 position: point(px(x), px(y)),
82 predicted_position: None,
83 force: None,
84 });
85 self.window_cx
86 .executor()
87 .advance_clock(Duration::from_millis(8));
88 }
89
90 fn pan(&mut self, from_y: f32, to_y: f32, steps: usize) {
91 self.touch(TouchPhase::Started, 100., from_y);
92 for step in 1..=steps {
93 let progress = step as f32 / steps as f32;
94 self.touch(TouchPhase::Moved, 100., from_y + (to_y - from_y) * progress);
95 }
96 self.touch(TouchPhase::Ended, 100., to_y);
97 }
98
99 fn tap(&mut self, x: f32, y: f32) {
100 self.touch(TouchPhase::Started, x, y);
101 self.touch(TouchPhase::Ended, x, y);
102 self.window_cx
103 .executor()
104 .advance_clock(Duration::from_millis(500));
105 }
106}
107
108fn open_scroll_container(
109 cx: &mut TestAppContext,
110) -> (ScrollHandle, Clicks, &mut VisualTestContext) {
111 cx.update(gpui_kit::init);
112 let scroll_handle = ScrollHandle::new();
113 let clicks = Clicks::default();
114 let (_, window_cx) = cx.add_window_view({
115 let scroll_handle = scroll_handle.clone();
116 let clicks = clicks.clone();
117 move |_, _| ScrollContainer {
118 scroll_handle,
119 clicks,
120 }
121 });
122 window_cx.update(|window, cx| window.draw(cx).clear(cx));
123 (scroll_handle, clicks, window_cx)
124}
125
126fn run_frames(window_cx: &mut VisualTestContext, frame_count: usize) {
127 for _ in 0..frame_count {
128 window_cx
129 .executor()
130 .advance_clock(Duration::from_millis(16));
131 window_cx.update(|window, cx| {
132 window.simulate_next_frame(cx);
133 window.draw(cx).clear(cx);
134 });
135 }
136}
137
138#[gpui_kit::test]
139fn finger_pan_scrolls_the_container_under_the_finger_by_pixels(cx: &mut TestAppContext) {
140 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
141 let mut finger = Finger {
142 window_cx,
143 touch_id: TouchId(1),
144 };
145 finger.pan(300., 180., 30);
146 let offset_y = f32::from(scroll_handle.offset().y);
147 assert!(
148 (-120.5..=-100.).contains(&offset_y),
149 "a 120 px slow pan scrolls about 120 px, got {offset_y}"
150 );
151 assert_eq!(clicks.left.get(), 0, "a pan never clicks");
152}
153
154#[gpui_kit::test]
155fn fling_keeps_scrolling_after_release(cx: &mut TestAppContext) {
156 let (scroll_handle, _, window_cx) = open_scroll_container(cx);
157 let mut finger = Finger {
158 window_cx,
159 touch_id: TouchId(1),
160 };
161 finger.pan(300., 100., 5);
162 let released_at = f32::from(scroll_handle.offset().y);
163 run_frames(finger.window_cx, 30);
164 let coasted_to = f32::from(scroll_handle.offset().y);
165 assert!(
166 coasted_to < released_at - 50.,
167 "momentum continues the scroll after release: {released_at} -> {coasted_to}"
168 );
169}
170
171#[gpui_kit::test]
172fn tap_clicks_the_row_under_the_finger(cx: &mut TestAppContext) {
173 let (_, clicks, window_cx) = open_scroll_container(cx);
174 let mut finger = Finger {
175 window_cx,
176 touch_id: TouchId(1),
177 };
178 finger.tap(100., 60.);
179 assert_eq!(clicks.left.get(), 1);
180}
181
182#[gpui_kit::test]
183fn finger_pan_scrolls_a_virtual_list(cx: &mut TestAppContext) {
184 cx.update(gpui_kit::init);
185 let list_state = ListState::new(ROW_COUNT, ListAlignment::Top, px(200.));
186 let (_, window_cx) = cx.add_window_view({
187 let list_state = list_state.clone();
188 move |_, _| VirtualList { list_state }
189 });
190 window_cx.update(|window, cx| window.draw(cx).clear(cx));
191 let mut finger = Finger {
192 window_cx,
193 touch_id: TouchId(1),
194 };
195 finger.pan(300., 100., 30);
196 let scroll_top = list_state.logical_scroll_top();
197 let scrolled = scroll_top.item_ix as f32 * ROW_HEIGHT + f32::from(scroll_top.offset_in_item);
198 assert!(
199 (180.0..=200.5).contains(&scrolled),
200 "a 200 px slow pan scrolls the list about 200 px, got {scrolled}"
201 );
202}
203
204#[gpui_kit::test]
205fn long_press_without_a_handler_right_clicks_instead_of_click_or_scroll(cx: &mut TestAppContext) {
206 let (scroll_handle, clicks, window_cx) = open_scroll_container(cx);
207 let mut finger = Finger {
208 window_cx,
209 touch_id: TouchId(1),
210 };
211 finger.touch(TouchPhase::Started, 100., 60.);
212 finger
213 .window_cx
214 .executor()
215 .advance_clock(Duration::from_millis(600));
216 finger.window_cx.run_until_parked();
217 finger.touch(TouchPhase::Moved, 100., 20.);
218 finger.touch(TouchPhase::Ended, 100., 20.);
219 finger.window_cx.run_until_parked();
220 assert_eq!(clicks.right.get(), 1);
221 assert_eq!(clicks.left.get(), 0);
222 assert_eq!(f32::from(scroll_handle.offset().y), 0.);
223}
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 +457 −11
@@ -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;
@@ -184,10 +185,16 @@ mod frames {
184 185 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
185 186 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
186 187 };
187 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
188 use crate::views::conversation::{
189 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
190 CHANNEL_DETAILS_TAG,
191 };
188 192 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
189 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG};
190 use crate::views::pin_banner::PIN_BANNER_TAG;
193 use crate::views::find_panel::{
194 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
195 };
196 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
197 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
191 198 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
192 199 use crate::views::reaction_proposal_pill::REACTION_PILL;
193 200 use crate::views::recap_tab::RECAP_REGION;
@@ -195,10 +202,28 @@ mod frames {
195 202 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
196 203 };
197 204 use crate::views::shortcuts::{
198 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
205 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
206 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
199 207 };
200 208 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
209 use crate::views::sidebar::chat_row_selector;
210 use crate::views::sidebar::chat_filter_bar::{
211 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
212 };
201 213 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
214 use crate::views::widgets::{
215 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
216 count_badge,
217 };
218 use gpui_kit::MouseButton;
219 use gpui_kit::component::fluent::{
220 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
221 OPTION_CHECK_INSET,
222 };
223 use gpui_kit::component::menu::selectors::{
224 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
225 label_selector as menu_label_selector,
226 };
202 227
203 228 const GUARDED: &[&str] = &[
204 229 "shell",
@@ -220,6 +245,14 @@ mod frames {
220 245 "shell/islands/main/call-controls/leave",
221 246 ];
222 247 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
248 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
249 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
250 const FIND_TAGS: &[&str] = &[
251 FIND_PANEL_TAG,
252 FIND_DIVIDER_TAG,
253 FIND_INPUT_TAG,
254 FIND_RESULTS_TAG,
255 ];
223 256 const CALLS_TAGS: &[&str] = &[
224 257 "shell/islands/sidebar/calls-actions",
225 258 "shell/islands/sidebar/calls-actions/meet-now",
@@ -260,7 +293,6 @@ mod frames {
260 293 const REACTION_CHAT: &str = "demo-chat-mara";
261 294 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
262 295 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
263 const IMPORTANCE_LABEL_INSET_TOP: f32 = 8.;
264 296 const AGENT_TAGS: [&str; 4] = [
265 297 PROPOSAL_CARD,
266 298 PROPOSAL_THUMBNAILS,
@@ -563,6 +595,9 @@ mod frames {
563 595 .iter()
564 596 .chain(CALL_GUARDED)
565 597 .chain(CALLS_TAGS)
598 .chain(CHAT_FILTER_TAGS)
599 .chain(CHAT_FILTER_OPEN_TAGS)
600 .chain(FIND_TAGS)
566 601 .chain(PREJOIN_TAGS)
567 602 .chain(SHARE_GUARDED)
568 603 .chain(CONSULT_GUARDED)
@@ -773,7 +808,26 @@ mod frames {
773 808 size: size(px(width), px(height)),
774 809 };
775 810 let screens = [
776 Screen::Tab("chats", None),
811 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
812 Screen::Tab(
813 "chat-filter",
814 Some(|visual| {
815 visual.dispatch_action(OpenChatsTab);
816 visual.dispatch_action(OpenChatFilter);
817 visual.dispatch_action(FilterMutedChats);
818 visual.run_until_parked();
819 visual.simulate_input("zzz");
820 }),
821 ),
822 Screen::Tab(
823 "find",
824 Some(|visual| {
825 visual.dispatch_action(OpenChatsTab);
826 visual.dispatch_action(FindInChat);
827 visual.run_until_parked();
828 visual.simulate_input("access");
829 }),
830 ),
777 831 Screen::Tab(
778 832 "activity",
779 833 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -906,6 +960,12 @@ mod frames {
906 960 expected.push(MENU);
907 961 }
908 962 match screen_name {
963 "chats" => expected.extend(CHAT_FILTER_TAGS),
964 "chat-filter" => {
965 expected.extend(CHAT_FILTER_TAGS);
966 expected.extend(CHAT_FILTER_OPEN_TAGS);
967 }
968 "find" => expected.extend(FIND_TAGS),
909 969 "calls" => expected.extend(CALLS_TAGS),
910 970 "agents" => expected.push(AGENTS_LIST),
911 971 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -945,6 +1005,15 @@ mod frames {
945 1005 })
946 1006 });
947 1007 }
1008 if screen_name == "find" {
1009 visual.dispatch_action(gpui_kit::component::input::Escape);
1010 visual.run_until_parked();
1011 }
1012 if screen_name == "chat-filter" {
1013 visual.dispatch_action(ClearChatFilters);
1014 visual.dispatch_action(OpenChatFilter);
1015 visual.run_until_parked();
1016 }
948 1017 if screen_name == "prejoin" {
949 1018 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
950 1019 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
@@ -1433,6 +1502,343 @@ mod frames {
1433 1502 }
1434 1503 }
1435 1504
1505 const MENU_ITEMS_SCANNED: usize = 40;
1506 const MENU_CHAT: &str = "demo-chat-release";
1507 const THEME_SELECT: &str = "settings-theme";
1508
1509 struct MenuRow {
1510 index: usize,
1511 item: Bounds<Pixels>,
1512 icon: Option<Bounds<Pixels>>,
1513 label: Option<Bounds<Pixels>>,
1514 }
1515
1516 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1517 (0..MENU_ITEMS_SCANNED)
1518 .filter_map(|index| {
1519 let item =
1520 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1521 Some(MenuRow {
1522 index,
1523 item,
1524 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1525 label: visual
1526 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1527 })
1528 })
1529 .collect()
1530 }
1531
1532 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1533 let mut found = Vec::new();
1534 for row in rows {
1535 let Some(icon) = row.icon else {
1536 continue;
1537 };
1538 let key = format!("{MENU}/item-{}", row.index);
1539 if let Some(label) = row.label {
1540 let gap = f32::from(label.left() - icon.right());
1541 if (gap - expected_gap).abs() > TOLERANCE {
1542 found.push((
1543 format!("{key}:icon-gap"),
1544 format!(
1545 "icon {} to label {} is {gap} px, expected {expected_gap}",
1546 describe(icon),
1547 describe(label)
1548 ),
1549 ));
1550 }
1551 }
1552 let offset = f32::from(icon.center().y - row.item.center().y);
1553 if offset.abs() > TOLERANCE {
1554 found.push((
1555 format!("{key}:icon-off-centre"),
1556 format!(
1557 "icon {} sits {offset} px off the centre of item {}",
1558 describe(icon),
1559 describe(row.item)
1560 ),
1561 ));
1562 }
1563 }
1564 found
1565 }
1566
1567 fn listbox_violations(
1568 trigger: Bounds<Pixels>,
1569 menu: Bounds<Pixels>,
1570 items: Bounds<Pixels>,
1571 rows: &[MenuRow],
1572 ) -> Vec<(String, String)> {
1573 let mut found = Vec::new();
1574 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1575 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1576 found.push((
1577 format!("{MENU}:not-aligned-to-trigger"),
1578 format!(
1579 "list {} must start at the trigger's left edge {}",
1580 describe(menu),
1581 describe(trigger)
1582 ),
1583 ));
1584 }
1585 if !near(
1586 f32::from(menu.top() - trigger.bottom()),
1587 f32::from(DROPDOWN_OFFSET),
1588 ) {
1589 found.push((
1590 format!("{MENU}:trigger-offset"),
1591 format!(
1592 "list {} must open {} px below the trigger {}",
1593 describe(menu),
1594 f32::from(DROPDOWN_OFFSET),
1595 describe(trigger)
1596 ),
1597 ));
1598 }
1599 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1600 found.push((
1601 format!("{MENU}:narrower-than-trigger"),
1602 format!(
1603 "list {} is narrower than the trigger {}",
1604 describe(menu),
1605 describe(trigger)
1606 ),
1607 ));
1608 }
1609 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1610 let top = f32::from(first.item.top() - items.top());
1611 let bottom = f32::from(items.bottom() - last.item.bottom());
1612 let padding = f32::from(MENU_LIST_PADDING);
1613 if !near(top, padding) || !near(bottom, padding) {
1614 found.push((
1615 format!("{MENU}:uneven-padding"),
1616 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1617 ));
1618 }
1619 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1620 match first.icon {
1621 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1622 check => found.push((
1623 format!("{MENU}:check-inset"),
1624 format!(
1625 "check column {check:?} must start {expected_inset} px inside the list {}",
1626 describe(menu)
1627 ),
1628 )),
1629 }
1630 }
1631 found
1632 }
1633
1634 #[test]
1635 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1636 let row =
1637 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1638 index,
1639 item: rectangle(4., item_top, 120., 32.),
1640 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1641 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1642 };
1643 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1644 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1645 .into_iter()
1646 .map(|(key, _)| key)
1647 .collect();
1648 assert_eq!(
1649 keys,
1650 [
1651 "popup-menu/item-1:icon-gap",
1652 "popup-menu/item-1:icon-off-centre"
1653 ]
1654 );
1655
1656 let trigger = rectangle(100., 50., 216., 32.);
1657 let option = |index: usize, top: f32| MenuRow {
1658 index,
1659 item: rectangle(104., top, 208., 32.),
1660 icon: Some(rectangle(110., top + 8., 16., 16.)),
1661 label: Some(rectangle(132., top + 6., 80., 20.)),
1662 };
1663 let aligned = [option(0, 88.), option(1, 122.)];
1664 let menu = rectangle(100., 84., 216., 74.);
1665 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1666 let shifted = rectangle(96., 90., 200., 80.);
1667 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1668 .into_iter()
1669 .map(|(key, _)| key)
1670 .collect();
1671 assert_eq!(
1672 keys,
1673 [
1674 "popup-menu:not-aligned-to-trigger",
1675 "popup-menu:trigger-offset",
1676 "popup-menu:narrower-than-trigger",
1677 "popup-menu:uneven-padding",
1678 "popup-menu:check-inset",
1679 ]
1680 );
1681 }
1682
1683 #[gpui_kit::test]
1684 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1685 let (handle, _) = mount(cx);
1686 let mut visual = VisualTestContext::from_window(handle, cx);
1687 visual.simulate_resize(size(px(1280.), px(800.)));
1688 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1689 collect(&mut visual, Some(chat_row));
1690 let mut found = Vec::new();
1691 let own_status = visual
1692 .debug_bounds(OWN_STATUS)
1693 .expect("own status button rendered");
1694 visual.simulate_click(own_status.center(), Default::default());
1695 collect(&mut visual, Some(MENU));
1696 let status_rows = menu_rows(&mut visual);
1697 assert!(
1698 status_rows.iter().any(|row| row.icon.is_some()),
1699 "status menu shows icons"
1700 );
1701 found.extend(menu_row_violations(
1702 &status_rows,
1703 f32::from(MENU_ICON_LABEL_GAP),
1704 ));
1705 visual.simulate_keystrokes("escape");
1706 collect(&mut visual, None);
1707 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1708 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1709 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1710 collect(&mut visual, Some(MENU));
1711 let chat_rows = menu_rows(&mut visual);
1712 assert!(
1713 chat_rows.iter().any(|row| row.icon.is_some()),
1714 "chat menu shows icons"
1715 );
1716 found.extend(menu_row_violations(
1717 &chat_rows,
1718 f32::from(MENU_ICON_LABEL_GAP),
1719 ));
1720 let found: Vec<String> = found
1721 .into_iter()
1722 .map(|(key, message)| format!("{key}: {message}"))
1723 .collect();
1724 assert!(found.is_empty(), "{}", found.join("\n"));
1725 }
1726
1727 #[gpui_kit::test]
1728 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1729 let (handle, state) = mount(cx);
1730 let mut visual = VisualTestContext::from_window(handle, cx);
1731 visual.simulate_resize(size(px(1280.), px(800.)));
1732 visual.update(|_, cx| {
1733 state.update(cx, |state, cx| {
1734 state.open_settings(SettingsSection::Appearance, cx)
1735 })
1736 });
1737 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1738 collect(&mut visual, Some(select));
1739 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1740 visual.simulate_click(trigger.center(), Default::default());
1741 collect(&mut visual, Some(MENU));
1742 let menu = visual.debug_bounds(MENU).expect("list rendered");
1743 let items = visual
1744 .debug_bounds(ITEMS_SELECTOR)
1745 .expect("list items rendered");
1746 let rows = menu_rows(&mut visual);
1747 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1748 .into_iter()
1749 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1750 .map(|(key, message)| format!("{key}: {message}"))
1751 .collect();
1752 assert!(found.is_empty(), "{}", found.join("\n"));
1753 }
1754
1755 const BADGE_SAMPLES: [(u32, bool); 5] =
1756 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1757
1758 struct BadgeSamples;
1759
1760 impl gpui_kit::Render for BadgeSamples {
1761 fn render(
1762 &mut self,
1763 _: &mut gpui_kit::Window,
1764 _: &mut gpui_kit::Context<Self>,
1765 ) -> impl gpui_kit::IntoElement {
1766 use gpui_kit::{ParentElement as _, Styled as _};
1767 gpui_kit::div()
1768 .flex()
1769 .gap(px(12.))
1770 .p(px(12.))
1771 .children(BADGE_SAMPLES.map(|(count, rail)| {
1772 if rail {
1773 badge_pill(
1774 count,
1775 RAIL_BADGE,
1776 crate::theme::accent(),
1777 crate::theme::on_accent(),
1778 )
1779 } else {
1780 count_badge(count, false)
1781 }
1782 }))
1783 }
1784 }
1785
1786 fn badge_violation(
1787 text: &str,
1788 pill: Bounds<Pixels>,
1789 label: Bounds<Pixels>,
1790 ink_offset: (f32, f32),
1791 ) -> Option<(String, String)> {
1792 let ink_x = f32::from(label.center().x) + ink_offset.0;
1793 let ink_y = f32::from(label.center().y) + ink_offset.1;
1794 let off_x = ink_x - f32::from(pill.center().x);
1795 let off_y = ink_y - f32::from(pill.center().y);
1796 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1797 (
1798 format!("count-badge/{text}:off-centre"),
1799 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1800 )
1801 })
1802 }
1803
1804 #[test]
1805 fn badge_rule_flags_off_centre_text() {
1806 let pill = rectangle(0., 0., 18., 18.);
1807 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1808 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1809 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1810 }
1811
1812 #[gpui_kit::test]
1813 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1814 cx.update(gpui_kit::init);
1815 cx.update(crate::theme::apply);
1816 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1817 collect(visual, None);
1818 let mut found = Vec::new();
1819 for (count, rail) in BADGE_SAMPLES {
1820 let text = crate::format::badge_text(count);
1821 let pill = visual
1822 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1823 .expect("badge rendered");
1824 let label = visual
1825 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1826 .expect("badge text rendered");
1827 let font_size = if rail {
1828 RAIL_BADGE.font_size
1829 } else {
1830 COUNT_BADGE.font_size
1831 };
1832 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1833 found.extend(badge_violation(&text, pill, label, offset));
1834 }
1835 let found: Vec<String> = found
1836 .into_iter()
1837 .map(|(key, message)| format!("{key}: {message}"))
1838 .collect();
1839 assert!(found.is_empty(), "{}", found.join("\n"));
1840 }
1841
1436 1842 const PINNED_CHAT: &str = "demo-chat-release";
1437 1843 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1438 1844
@@ -1459,12 +1865,13 @@ mod frames {
1459 1865 ("below divider", f32::from(banner.top() - divider.bottom())),
1460 1866 ];
1461 1867 let side = gaps[1].1;
1462 if gaps
1463 .iter()
1464 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1868 if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1869 || gaps
1870 .iter()
1871 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1465 1872 {
1466 1873 found.push(format!(
1467 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1874 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1468 1875 ));
1469 1876 }
1470 1877 }
@@ -1516,6 +1923,45 @@ mod frames {
1516 1923 );
1517 1924 }
1518 1925
1926 #[gpui_kit::test]
1927 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1928 let (handle, state) = mount(cx);
1929 let mut visual = VisualTestContext::from_window(handle, cx);
1930 visual.simulate_resize(size(px(1280.), px(800.)));
1931 visual.update(|_, cx| {
1932 state.update(cx, |state, cx| {
1933 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1934 })
1935 });
1936 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1937 let button = visual
1938 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1939 .expect("channel details button");
1940 visual.simulate_click(button.center(), Default::default());
1941 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1942 let pane = visual
1943 .debug_bounds(CHANNEL_DETAILS_TAG)
1944 .expect("details pane");
1945 let pinned = visual
1946 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1947 .expect("pinned section");
1948 let shared = visual
1949 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1950 .expect("shared section");
1951 assert!(
1952 pinned.bottom() <= shared.top(),
1953 "pinned {pinned:?} must come before shared {shared:?}"
1954 );
1955 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1956 let left = f32::from(section.left() - pane.left());
1957 let right = f32::from(pane.right() - section.right());
1958 assert!(
1959 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1960 "{name} section insets left {left} right {right} must match"
1961 );
1962 }
1963 }
1964
1519 1965 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1520 1966 collect(visual, Some(COMPOSER_SEND_TAG));
1521 1967 let mut bounds_of = |path: &'static str| {
@@ -1742,7 +2188,7 @@ mod frames {
1742 2188 let top = inset(bubble, label, Edge::Top);
1743 2189 assert!(
1744 2190 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
1745 && (top - IMPORTANCE_LABEL_INSET_TOP).abs() <= TOLERANCE,
2191 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
1746 2192 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
1747 2193 describe(bubble)
1748 2194 );
@@ -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;
@@ -184,10 +185,16 @@ mod frames {
184 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
185 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
185 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
186 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
186 };
187 };
187 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
188 use crate::views::conversation::{
189 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
190 CHANNEL_DETAILS_TAG,
191 };
188 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
192 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
189 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG};
193 use crate::views::find_panel::{
190 use crate::views::pin_banner::PIN_BANNER_TAG;
194 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
195 };
196 use crate::views::message_row::{BUBBLE_TAGS, IMPORTANCE_LABEL_TAG, bubble_padding_y};
197 use crate::views::pin_banner::{BANNER_INSET, PIN_BANNER_TAG};
191 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
198 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
192 use crate::views::reaction_proposal_pill::REACTION_PILL;
199 use crate::views::reaction_proposal_pill::REACTION_PILL;
193 use crate::views::recap_tab::RECAP_REGION;
200 use crate::views::recap_tab::RECAP_REGION;
@@ -195,10 +202,28 @@ mod frames {
195 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
202 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
196 };
203 };
197 use crate::views::shortcuts::{
204 use crate::views::shortcuts::{
198 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
205 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
206 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
199 };
207 };
200 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
208 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
209 use crate::views::sidebar::chat_row_selector;
210 use crate::views::sidebar::chat_filter_bar::{
211 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
212 };
201 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
213 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
214 use crate::views::widgets::{
215 COUNT_BADGE, RAIL_BADGE, badge_ink_offset, badge_pill, badge_selector, badge_text_selector,
216 count_badge,
217 };
218 use gpui_kit::MouseButton;
219 use gpui_kit::component::fluent::{
220 DROPDOWN_OFFSET, MENU_ICON_LABEL_GAP, MENU_LIST_PADDING, OPTION_CHECK_GAP,
221 OPTION_CHECK_INSET,
222 };
223 use gpui_kit::component::menu::selectors::{
224 ITEMS_SELECTOR, icon_selector, item_selector as menu_item_selector,
225 label_selector as menu_label_selector,
226 };
202
227
203 const GUARDED: &[&str] = &[
228 const GUARDED: &[&str] = &[
204 "shell",
229 "shell",
@@ -220,6 +245,14 @@ mod frames {
220 "shell/islands/main/call-controls/leave",
245 "shell/islands/main/call-controls/leave",
221 ];
246 ];
222 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
247 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
248 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
249 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
250 const FIND_TAGS: &[&str] = &[
251 FIND_PANEL_TAG,
252 FIND_DIVIDER_TAG,
253 FIND_INPUT_TAG,
254 FIND_RESULTS_TAG,
255 ];
223 const CALLS_TAGS: &[&str] = &[
256 const CALLS_TAGS: &[&str] = &[
224 "shell/islands/sidebar/calls-actions",
257 "shell/islands/sidebar/calls-actions",
225 "shell/islands/sidebar/calls-actions/meet-now",
258 "shell/islands/sidebar/calls-actions/meet-now",
@@ -260,7 +293,6 @@ mod frames {
260 const REACTION_CHAT: &str = "demo-chat-mara";
293 const REACTION_CHAT: &str = "demo-chat-mara";
261 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
294 const IMPORTANCE_CHATS: [&str; 2] = ["demo-chat-priya", "demo-chat-atlas"];
262 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
295 const IMPORTANCE_LABEL_INSET_X: f32 = 12.;
263 const IMPORTANCE_LABEL_INSET_TOP: f32 = 8.;
264 const AGENT_TAGS: [&str; 4] = [
296 const AGENT_TAGS: [&str; 4] = [
265 PROPOSAL_CARD,
297 PROPOSAL_CARD,
266 PROPOSAL_THUMBNAILS,
298 PROPOSAL_THUMBNAILS,
@@ -563,6 +595,9 @@ mod frames {
563 .iter()
595 .iter()
564 .chain(CALL_GUARDED)
596 .chain(CALL_GUARDED)
565 .chain(CALLS_TAGS)
597 .chain(CALLS_TAGS)
598 .chain(CHAT_FILTER_TAGS)
599 .chain(CHAT_FILTER_OPEN_TAGS)
600 .chain(FIND_TAGS)
566 .chain(PREJOIN_TAGS)
601 .chain(PREJOIN_TAGS)
567 .chain(SHARE_GUARDED)
602 .chain(SHARE_GUARDED)
568 .chain(CONSULT_GUARDED)
603 .chain(CONSULT_GUARDED)
@@ -773,7 +808,26 @@ mod frames {
773 size: size(px(width), px(height)),
808 size: size(px(width), px(height)),
774 };
809 };
775 let screens = [
810 let screens = [
776 Screen::Tab("chats", None),
811 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
812 Screen::Tab(
813 "chat-filter",
814 Some(|visual| {
815 visual.dispatch_action(OpenChatsTab);
816 visual.dispatch_action(OpenChatFilter);
817 visual.dispatch_action(FilterMutedChats);
818 visual.run_until_parked();
819 visual.simulate_input("zzz");
820 }),
821 ),
822 Screen::Tab(
823 "find",
824 Some(|visual| {
825 visual.dispatch_action(OpenChatsTab);
826 visual.dispatch_action(FindInChat);
827 visual.run_until_parked();
828 visual.simulate_input("access");
829 }),
830 ),
777 Screen::Tab(
831 Screen::Tab(
778 "activity",
832 "activity",
779 Some(|visual| visual.dispatch_action(OpenActivity)),
833 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -906,6 +960,12 @@ mod frames {
906 expected.push(MENU);
960 expected.push(MENU);
907 }
961 }
908 match screen_name {
962 match screen_name {
963 "chats" => expected.extend(CHAT_FILTER_TAGS),
964 "chat-filter" => {
965 expected.extend(CHAT_FILTER_TAGS);
966 expected.extend(CHAT_FILTER_OPEN_TAGS);
967 }
968 "find" => expected.extend(FIND_TAGS),
909 "calls" => expected.extend(CALLS_TAGS),
969 "calls" => expected.extend(CALLS_TAGS),
910 "agents" => expected.push(AGENTS_LIST),
970 "agents" => expected.push(AGENTS_LIST),
911 "prejoin" => expected.extend(PREJOIN_TAGS),
971 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -945,6 +1005,15 @@ mod frames {
945 })
1005 })
946 });
1006 });
947 }
1007 }
1008 if screen_name == "find" {
1009 visual.dispatch_action(gpui_kit::component::input::Escape);
1010 visual.run_until_parked();
1011 }
1012 if screen_name == "chat-filter" {
1013 visual.dispatch_action(ClearChatFilters);
1014 visual.dispatch_action(OpenChatFilter);
1015 visual.run_until_parked();
1016 }
948 if screen_name == "prejoin" {
1017 if screen_name == "prejoin" {
949 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
1018 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
950 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
1019 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
@@ -1433,6 +1502,343 @@ mod frames {
1433 }
1502 }
1434 }
1503 }
1435
1504
1505 const MENU_ITEMS_SCANNED: usize = 40;
1506 const MENU_CHAT: &str = "demo-chat-release";
1507 const THEME_SELECT: &str = "settings-theme";
1508
1509 struct MenuRow {
1510 index: usize,
1511 item: Bounds<Pixels>,
1512 icon: Option<Bounds<Pixels>>,
1513 label: Option<Bounds<Pixels>>,
1514 }
1515
1516 fn menu_rows(visual: &mut VisualTestContext) -> Vec<MenuRow> {
1517 (0..MENU_ITEMS_SCANNED)
1518 .filter_map(|index| {
1519 let item =
1520 visual.debug_bounds(Box::leak(menu_item_selector(index).into_boxed_str()))?;
1521 Some(MenuRow {
1522 index,
1523 item,
1524 icon: visual.debug_bounds(Box::leak(icon_selector(index).into_boxed_str())),
1525 label: visual
1526 .debug_bounds(Box::leak(menu_label_selector(index).into_boxed_str())),
1527 })
1528 })
1529 .collect()
1530 }
1531
1532 fn menu_row_violations(rows: &[MenuRow], expected_gap: f32) -> Vec<(String, String)> {
1533 let mut found = Vec::new();
1534 for row in rows {
1535 let Some(icon) = row.icon else {
1536 continue;
1537 };
1538 let key = format!("{MENU}/item-{}", row.index);
1539 if let Some(label) = row.label {
1540 let gap = f32::from(label.left() - icon.right());
1541 if (gap - expected_gap).abs() > TOLERANCE {
1542 found.push((
1543 format!("{key}:icon-gap"),
1544 format!(
1545 "icon {} to label {} is {gap} px, expected {expected_gap}",
1546 describe(icon),
1547 describe(label)
1548 ),
1549 ));
1550 }
1551 }
1552 let offset = f32::from(icon.center().y - row.item.center().y);
1553 if offset.abs() > TOLERANCE {
1554 found.push((
1555 format!("{key}:icon-off-centre"),
1556 format!(
1557 "icon {} sits {offset} px off the centre of item {}",
1558 describe(icon),
1559 describe(row.item)
1560 ),
1561 ));
1562 }
1563 }
1564 found
1565 }
1566
1567 fn listbox_violations(
1568 trigger: Bounds<Pixels>,
1569 menu: Bounds<Pixels>,
1570 items: Bounds<Pixels>,
1571 rows: &[MenuRow],
1572 ) -> Vec<(String, String)> {
1573 let mut found = Vec::new();
1574 let near = |value: f32, expected: f32| (value - expected).abs() <= TOLERANCE;
1575 if !near(f32::from(menu.left() - trigger.left()), 0.) {
1576 found.push((
1577 format!("{MENU}:not-aligned-to-trigger"),
1578 format!(
1579 "list {} must start at the trigger's left edge {}",
1580 describe(menu),
1581 describe(trigger)
1582 ),
1583 ));
1584 }
1585 if !near(
1586 f32::from(menu.top() - trigger.bottom()),
1587 f32::from(DROPDOWN_OFFSET),
1588 ) {
1589 found.push((
1590 format!("{MENU}:trigger-offset"),
1591 format!(
1592 "list {} must open {} px below the trigger {}",
1593 describe(menu),
1594 f32::from(DROPDOWN_OFFSET),
1595 describe(trigger)
1596 ),
1597 ));
1598 }
1599 if menu.size.width < trigger.size.width - px(TOLERANCE) {
1600 found.push((
1601 format!("{MENU}:narrower-than-trigger"),
1602 format!(
1603 "list {} is narrower than the trigger {}",
1604 describe(menu),
1605 describe(trigger)
1606 ),
1607 ));
1608 }
1609 if let (Some(first), Some(last)) = (rows.first(), rows.last()) {
1610 let top = f32::from(first.item.top() - items.top());
1611 let bottom = f32::from(items.bottom() - last.item.bottom());
1612 let padding = f32::from(MENU_LIST_PADDING);
1613 if !near(top, padding) || !near(bottom, padding) {
1614 found.push((
1615 format!("{MENU}:uneven-padding"),
1616 format!("list padding top {top} / bottom {bottom}, both must be {padding}"),
1617 ));
1618 }
1619 let expected_inset = f32::from(MENU_LIST_PADDING + OPTION_CHECK_INSET);
1620 match first.icon {
1621 Some(check) if near(f32::from(check.left() - menu.left()), expected_inset) => {}
1622 check => found.push((
1623 format!("{MENU}:check-inset"),
1624 format!(
1625 "check column {check:?} must start {expected_inset} px inside the list {}",
1626 describe(menu)
1627 ),
1628 )),
1629 }
1630 }
1631 found
1632 }
1633
1634 #[test]
1635 fn menu_rules_flag_gaps_offsets_and_misaligned_lists() {
1636 let row =
1637 |index: usize, item_top: f32, icon_left: f32, icon_top: f32, label_left: f32| MenuRow {
1638 index,
1639 item: rectangle(4., item_top, 120., 32.),
1640 icon: Some(rectangle(icon_left, icon_top, 20., 20.)),
1641 label: Some(rectangle(label_left, item_top + 6., 60., 20.)),
1642 };
1643 let rows = [row(0, 4., 10., 10., 36.), row(1, 38., 10., 46., 32.)];
1644 let keys: Vec<String> = menu_row_violations(&rows, f32::from(MENU_ICON_LABEL_GAP))
1645 .into_iter()
1646 .map(|(key, _)| key)
1647 .collect();
1648 assert_eq!(
1649 keys,
1650 [
1651 "popup-menu/item-1:icon-gap",
1652 "popup-menu/item-1:icon-off-centre"
1653 ]
1654 );
1655
1656 let trigger = rectangle(100., 50., 216., 32.);
1657 let option = |index: usize, top: f32| MenuRow {
1658 index,
1659 item: rectangle(104., top, 208., 32.),
1660 icon: Some(rectangle(110., top + 8., 16., 16.)),
1661 label: Some(rectangle(132., top + 6., 80., 20.)),
1662 };
1663 let aligned = [option(0, 88.), option(1, 122.)];
1664 let menu = rectangle(100., 84., 216., 74.);
1665 assert!(listbox_violations(trigger, menu, menu, &aligned).is_empty());
1666 let shifted = rectangle(96., 90., 200., 80.);
1667 let keys: Vec<String> = listbox_violations(trigger, shifted, shifted, &aligned)
1668 .into_iter()
1669 .map(|(key, _)| key)
1670 .collect();
1671 assert_eq!(
1672 keys,
1673 [
1674 "popup-menu:not-aligned-to-trigger",
1675 "popup-menu:trigger-offset",
1676 "popup-menu:narrower-than-trigger",
1677 "popup-menu:uneven-padding",
1678 "popup-menu:check-inset",
1679 ]
1680 );
1681 }
1682
1683 #[gpui_kit::test]
1684 fn menu_items_keep_one_icon_gap_and_centred_icons(cx: &mut TestAppContext) {
1685 let (handle, _) = mount(cx);
1686 let mut visual = VisualTestContext::from_window(handle, cx);
1687 visual.simulate_resize(size(px(1280.), px(800.)));
1688 let chat_row: &'static str = Box::leak(chat_row_selector(MENU_CHAT).into_boxed_str());
1689 collect(&mut visual, Some(chat_row));
1690 let mut found = Vec::new();
1691 let own_status = visual
1692 .debug_bounds(OWN_STATUS)
1693 .expect("own status button rendered");
1694 visual.simulate_click(own_status.center(), Default::default());
1695 collect(&mut visual, Some(MENU));
1696 let status_rows = menu_rows(&mut visual);
1697 assert!(
1698 status_rows.iter().any(|row| row.icon.is_some()),
1699 "status menu shows icons"
1700 );
1701 found.extend(menu_row_violations(
1702 &status_rows,
1703 f32::from(MENU_ICON_LABEL_GAP),
1704 ));
1705 visual.simulate_keystrokes("escape");
1706 collect(&mut visual, None);
1707 let row = visual.debug_bounds(chat_row).expect("chat row rendered");
1708 visual.simulate_mouse_down(row.center(), MouseButton::Right, Default::default());
1709 visual.simulate_mouse_up(row.center(), MouseButton::Right, Default::default());
1710 collect(&mut visual, Some(MENU));
1711 let chat_rows = menu_rows(&mut visual);
1712 assert!(
1713 chat_rows.iter().any(|row| row.icon.is_some()),
1714 "chat menu shows icons"
1715 );
1716 found.extend(menu_row_violations(
1717 &chat_rows,
1718 f32::from(MENU_ICON_LABEL_GAP),
1719 ));
1720 let found: Vec<String> = found
1721 .into_iter()
1722 .map(|(key, message)| format!("{key}: {message}"))
1723 .collect();
1724 assert!(found.is_empty(), "{}", found.join("\n"));
1725 }
1726
1727 #[gpui_kit::test]
1728 fn settings_select_list_lines_up_with_its_trigger(cx: &mut TestAppContext) {
1729 let (handle, state) = mount(cx);
1730 let mut visual = VisualTestContext::from_window(handle, cx);
1731 visual.simulate_resize(size(px(1280.), px(800.)));
1732 visual.update(|_, cx| {
1733 state.update(cx, |state, cx| {
1734 state.open_settings(SettingsSection::Appearance, cx)
1735 })
1736 });
1737 let select: &'static str = Box::leak(select_selector(THEME_SELECT).into_boxed_str());
1738 collect(&mut visual, Some(select));
1739 let trigger = visual.debug_bounds(select).expect("theme select rendered");
1740 visual.simulate_click(trigger.center(), Default::default());
1741 collect(&mut visual, Some(MENU));
1742 let menu = visual.debug_bounds(MENU).expect("list rendered");
1743 let items = visual
1744 .debug_bounds(ITEMS_SELECTOR)
1745 .expect("list items rendered");
1746 let rows = menu_rows(&mut visual);
1747 let found: Vec<String> = listbox_violations(trigger, menu, items, &rows)
1748 .into_iter()
1749 .chain(menu_row_violations(&rows, f32::from(OPTION_CHECK_GAP)))
1750 .map(|(key, message)| format!("{key}: {message}"))
1751 .collect();
1752 assert!(found.is_empty(), "{}", found.join("\n"));
1753 }
1754
1755 const BADGE_SAMPLES: [(u32, bool); 5] =
1756 [(1, false), (42, false), (120, false), (7, true), (15, true)];
1757
1758 struct BadgeSamples;
1759
1760 impl gpui_kit::Render for BadgeSamples {
1761 fn render(
1762 &mut self,
1763 _: &mut gpui_kit::Window,
1764 _: &mut gpui_kit::Context<Self>,
1765 ) -> impl gpui_kit::IntoElement {
1766 use gpui_kit::{ParentElement as _, Styled as _};
1767 gpui_kit::div()
1768 .flex()
1769 .gap(px(12.))
1770 .p(px(12.))
1771 .children(BADGE_SAMPLES.map(|(count, rail)| {
1772 if rail {
1773 badge_pill(
1774 count,
1775 RAIL_BADGE,
1776 crate::theme::accent(),
1777 crate::theme::on_accent(),
1778 )
1779 } else {
1780 count_badge(count, false)
1781 }
1782 }))
1783 }
1784 }
1785
1786 fn badge_violation(
1787 text: &str,
1788 pill: Bounds<Pixels>,
1789 label: Bounds<Pixels>,
1790 ink_offset: (f32, f32),
1791 ) -> Option<(String, String)> {
1792 let ink_x = f32::from(label.center().x) + ink_offset.0;
1793 let ink_y = f32::from(label.center().y) + ink_offset.1;
1794 let off_x = ink_x - f32::from(pill.center().x);
1795 let off_y = ink_y - f32::from(pill.center().y);
1796 (off_x.abs() > TOLERANCE || off_y.abs() > TOLERANCE).then(|| {
1797 (
1798 format!("count-badge/{text}:off-centre"),
1799 format!("text ink of {text:?} sits ({off_x:.2}, {off_y:.2}) px off the centre of its circle {}", describe(pill)),
1800 )
1801 })
1802 }
1803
1804 #[test]
1805 fn badge_rule_flags_off_centre_text() {
1806 let pill = rectangle(0., 0., 18., 18.);
1807 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., 0.)).is_none());
1808 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (1., 0.)).is_some());
1809 assert!(badge_violation("1", pill, rectangle(6., 0., 6., 18.), (0., -1.)).is_some());
1810 }
1811
1812 #[gpui_kit::test]
1813 fn count_badge_text_sits_in_the_centre_of_its_circle(cx: &mut TestAppContext) {
1814 cx.update(gpui_kit::init);
1815 cx.update(crate::theme::apply);
1816 let (_, visual) = cx.add_window_view(|_, _| BadgeSamples);
1817 collect(visual, None);
1818 let mut found = Vec::new();
1819 for (count, rail) in BADGE_SAMPLES {
1820 let text = crate::format::badge_text(count);
1821 let pill = visual
1822 .debug_bounds(Box::leak(badge_selector(&text).into_boxed_str()))
1823 .expect("badge rendered");
1824 let label = visual
1825 .debug_bounds(Box::leak(badge_text_selector(&text).into_boxed_str()))
1826 .expect("badge text rendered");
1827 let font_size = if rail {
1828 RAIL_BADGE.font_size
1829 } else {
1830 COUNT_BADGE.font_size
1831 };
1832 let offset = visual.update(|window, _| badge_ink_offset(window, &text, font_size));
1833 found.extend(badge_violation(&text, pill, label, offset));
1834 }
1835 let found: Vec<String> = found
1836 .into_iter()
1837 .map(|(key, message)| format!("{key}: {message}"))
1838 .collect();
1839 assert!(found.is_empty(), "{}", found.join("\n"));
1840 }
1841
1436 const PINNED_CHAT: &str = "demo-chat-release";
1842 const PINNED_CHAT: &str = "demo-chat-release";
1437 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1843 const PINNED_CHANNEL: &str = "demo-channel-1-1";
1438
1844
@@ -1459,12 +1865,13 @@ mod frames {
1459 ("below divider", f32::from(banner.top() - divider.bottom())),
1865 ("below divider", f32::from(banner.top() - divider.bottom())),
1460 ];
1866 ];
1461 let side = gaps[1].1;
1867 let side = gaps[1].1;
1462 if gaps
1868 if (side - BANNER_INSET).abs() > INSET_TOLERANCE
1463 .iter()
1869 || gaps
1464 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1870 .iter()
1871 .any(|(_, gap)| (gap - side).abs() > INSET_TOLERANCE)
1465 {
1872 {
1466 found.push(format!(
1873 found.push(format!(
1467 "pin banner@{width}x{height}: gaps {gaps:?} must match"
1874 "pin banner@{width}x{height}: gaps {gaps:?} must all be {BANNER_INSET}"
1468 ));
1875 ));
1469 }
1876 }
1470 }
1877 }
@@ -1516,6 +1923,45 @@ mod frames {
1516 );
1923 );
1517 }
1924 }
1518
1925
1926 #[gpui_kit::test]
1927 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1928 let (handle, state) = mount(cx);
1929 let mut visual = VisualTestContext::from_window(handle, cx);
1930 visual.simulate_resize(size(px(1280.), px(800.)));
1931 visual.update(|_, cx| {
1932 state.update(cx, |state, cx| {
1933 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1934 })
1935 });
1936 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1937 let button = visual
1938 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1939 .expect("channel details button");
1940 visual.simulate_click(button.center(), Default::default());
1941 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1942 let pane = visual
1943 .debug_bounds(CHANNEL_DETAILS_TAG)
1944 .expect("details pane");
1945 let pinned = visual
1946 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1947 .expect("pinned section");
1948 let shared = visual
1949 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1950 .expect("shared section");
1951 assert!(
1952 pinned.bottom() <= shared.top(),
1953 "pinned {pinned:?} must come before shared {shared:?}"
1954 );
1955 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1956 let left = f32::from(section.left() - pane.left());
1957 let right = f32::from(pane.right() - section.right());
1958 assert!(
1959 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1960 "{name} section insets left {left} right {right} must match"
1961 );
1962 }
1963 }
1964
1519 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1965 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1520 collect(visual, Some(COMPOSER_SEND_TAG));
1966 collect(visual, Some(COMPOSER_SEND_TAG));
1521 let mut bounds_of = |path: &'static str| {
1967 let mut bounds_of = |path: &'static str| {
@@ -1742,7 +2188,7 @@ mod frames {
1742 let top = inset(bubble, label, Edge::Top);
2188 let top = inset(bubble, label, Edge::Top);
1743 assert!(
2189 assert!(
1744 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
2190 (left - IMPORTANCE_LABEL_INSET_X).abs() <= TOLERANCE
1745 && (top - IMPORTANCE_LABEL_INSET_TOP).abs() <= TOLERANCE,
2191 && (top - bubble_padding_y(false)).abs() <= TOLERANCE,
1746 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
2192 "{chat}@{width}x{height}: label inset left {left} top {top} in {}",
1747 describe(bubble)
2193 describe(bubble)
1748 );
2194 );
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};
@@ -108,7 +108,8 @@ impl NotificationCenter {
108 108 window: &mut Window,
109 109 cx: &mut Context<Self>,
110 110 ) -> Self {
111 let settings = settings::load(&app.read(cx).store);
111 let mut settings = settings::load(&app.read(cx).store);
112 settings.account = app.read(cx).account_chat_settings().notifications;
112 113 let app_icon = active_appearance::current(cx).app_icon;
113 114 let tray = if app.read(cx).mode.demo {
114 115 None
@@ -275,13 +276,19 @@ impl NotificationCenter {
275 276 self.sync_tray();
276 277 if self.settings.sounds != previous {
277 278 let updated = self.settings.sounds.clone();
278 self.app
279 .update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
279 self.app.update(cx, |state, cx| {
280 state.save_sound_settings(previous, updated, cx)
281 });
280 282 self.prefetch_sounds(cx);
281 283 }
282 284 cx.notify();
283 285 }
284 286
287 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
288 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
289 cx.notify();
290 }
291
285 292 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
286 293 let Some(account) = self.app.read(cx).account_sounds.clone() else {
287 294 return;
@@ -336,6 +343,7 @@ impl NotificationCenter {
336 343 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
337 344 AppEvent::Call => self.sync_call_sounds(cx),
338 345 AppEvent::SoundSettings => self.on_account_sounds(cx),
346 AppEvent::ChatSettings => self.on_account_notifications(cx),
339 347 _ => {}
340 348 }
341 349 }
@@ -399,7 +407,11 @@ impl NotificationCenter {
399 407 .unwrap_or(false)
400 408 }
401 409
402 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
410 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
411 incoming.chat.desktop = self
412 .app
413 .read(cx)
414 .chat_desktop_notifications(&incoming.conversation_id);
403 415 let bubble_text = match &incoming.preview {
404 416 Preview::Text(text) => text.replace('\n', " "),
405 417 Preview::Image => "Sent a picture".to_owned(),
@@ -576,7 +588,9 @@ impl NotificationCenter {
576 588 .map(|toast| {
577 589 let lines = match &toast.agent {
578 590 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
579 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
591 None => {
592 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
593 }
580 594 };
581 595 layout::toast_height(toast, lines)
582 596 })
@@ -726,7 +740,12 @@ impl NotificationCenter {
726 740 let reconnecting =
727 741 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
728 742 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
729 sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
743 sync_loop(
744 &mut self.reconnecting,
745 reconnecting,
746 CallTone::Reconnecting,
747 cx,
748 );
730 749 }
731 750
732 751 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -1166,6 +1185,7 @@ impl NotificationCenter {
1166 1185 mentions_me: false,
1167 1186 muted: false,
1168 1187 signals: Default::default(),
1188 chat: Default::default(),
1169 1189 created_at: Utc::now(),
1170 1190 importance: Default::default(),
1171 1191 };
@@ -1338,6 +1358,7 @@ fn demo_incoming() -> Vec<Incoming> {
1338 1358 mentions_me: mention,
1339 1359 muted: false,
1340 1360 signals: Default::default(),
1361 chat: Default::default(),
1341 1362 created_at: Utc::now(),
1342 1363 importance: Default::default(),
1343 1364 };
@@ -1415,7 +1436,10 @@ mod tests {
1415 1436 scale: 1.,
1416 1437 };
1417 1438 let options = popup_options(slot, area);
1418 assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1439 assert_eq!(
1440 options.window_background,
1441 WindowBackgroundAppearance::Transparent
1442 );
1419 1443 assert_eq!(options.kind, WindowKind::PopUp);
1420 1444 }
1421 1445
@@ -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};
@@ -108,7 +108,8 @@ impl NotificationCenter {
108 window: &mut Window,
108 window: &mut Window,
109 cx: &mut Context<Self>,
109 cx: &mut Context<Self>,
110 ) -> Self {
110 ) -> Self {
111 let settings = settings::load(&app.read(cx).store);
111 let mut settings = settings::load(&app.read(cx).store);
112 settings.account = app.read(cx).account_chat_settings().notifications;
112 let app_icon = active_appearance::current(cx).app_icon;
113 let app_icon = active_appearance::current(cx).app_icon;
113 let tray = if app.read(cx).mode.demo {
114 let tray = if app.read(cx).mode.demo {
114 None
115 None
@@ -275,13 +276,19 @@ impl NotificationCenter {
275 self.sync_tray();
276 self.sync_tray();
276 if self.settings.sounds != previous {
277 if self.settings.sounds != previous {
277 let updated = self.settings.sounds.clone();
278 let updated = self.settings.sounds.clone();
278 self.app
279 self.app.update(cx, |state, cx| {
279 .update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
280 state.save_sound_settings(previous, updated, cx)
281 });
280 self.prefetch_sounds(cx);
282 self.prefetch_sounds(cx);
281 }
283 }
282 cx.notify();
284 cx.notify();
283 }
285 }
284
286
287 fn on_account_notifications(&mut self, cx: &mut Context<Self>) {
288 self.settings.account = self.app.read(cx).account_chat_settings().notifications;
289 cx.notify();
290 }
291
285 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
292 fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
286 let Some(account) = self.app.read(cx).account_sounds.clone() else {
293 let Some(account) = self.app.read(cx).account_sounds.clone() else {
287 return;
294 return;
@@ -336,6 +343,7 @@ impl NotificationCenter {
336 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
343 AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
337 AppEvent::Call => self.sync_call_sounds(cx),
344 AppEvent::Call => self.sync_call_sounds(cx),
338 AppEvent::SoundSettings => self.on_account_sounds(cx),
345 AppEvent::SoundSettings => self.on_account_sounds(cx),
346 AppEvent::ChatSettings => self.on_account_notifications(cx),
339 _ => {}
347 _ => {}
340 }
348 }
341 }
349 }
@@ -399,7 +407,11 @@ impl NotificationCenter {
399 .unwrap_or(false)
407 .unwrap_or(false)
400 }
408 }
401
409
402 pub fn handle_incoming(&mut self, incoming: Incoming, cx: &mut Context<Self>) {
410 pub fn handle_incoming(&mut self, mut incoming: Incoming, cx: &mut Context<Self>) {
411 incoming.chat.desktop = self
412 .app
413 .read(cx)
414 .chat_desktop_notifications(&incoming.conversation_id);
403 let bubble_text = match &incoming.preview {
415 let bubble_text = match &incoming.preview {
404 Preview::Text(text) => text.replace('\n', " "),
416 Preview::Text(text) => text.replace('\n', " "),
405 Preview::Image => "Sent a picture".to_owned(),
417 Preview::Image => "Sent a picture".to_owned(),
@@ -576,7 +588,9 @@ impl NotificationCenter {
576 .map(|toast| {
588 .map(|toast| {
577 let lines = match &toast.agent {
589 let lines = match &toast.agent {
578 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
590 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
579 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
591 None => {
592 preview_lines(&describe(toast, shows_preview(&self.settings)).preview, cx)
593 }
580 };
594 };
581 layout::toast_height(toast, lines)
595 layout::toast_height(toast, lines)
582 })
596 })
@@ -726,7 +740,12 @@ impl NotificationCenter {
726 let reconnecting =
740 let reconnecting =
727 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
741 model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
728 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
742 sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
729 sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
743 sync_loop(
744 &mut self.reconnecting,
745 reconnecting,
746 CallTone::Reconnecting,
747 cx,
748 );
730 }
749 }
731
750
732 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
751 fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -1166,6 +1185,7 @@ impl NotificationCenter {
1166 mentions_me: false,
1185 mentions_me: false,
1167 muted: false,
1186 muted: false,
1168 signals: Default::default(),
1187 signals: Default::default(),
1188 chat: Default::default(),
1169 created_at: Utc::now(),
1189 created_at: Utc::now(),
1170 importance: Default::default(),
1190 importance: Default::default(),
1171 };
1191 };
@@ -1338,6 +1358,7 @@ fn demo_incoming() -> Vec<Incoming> {
1338 mentions_me: mention,
1358 mentions_me: mention,
1339 muted: false,
1359 muted: false,
1340 signals: Default::default(),
1360 signals: Default::default(),
1361 chat: Default::default(),
1341 created_at: Utc::now(),
1362 created_at: Utc::now(),
1342 importance: Default::default(),
1363 importance: Default::default(),
1343 };
1364 };
@@ -1415,7 +1436,10 @@ mod tests {
1415 scale: 1.,
1436 scale: 1.,
1416 };
1437 };
1417 let options = popup_options(slot, area);
1438 let options = popup_options(slot, area);
1418 assert_eq!(options.window_background, WindowBackgroundAppearance::Transparent);
1439 assert_eq!(
1440 options.window_background,
1441 WindowBackgroundAppearance::Transparent
1442 );
1419 assert_eq!(options.kind, WindowKind::PopUp);
1443 assert_eq!(options.kind, WindowKind::PopUp);
1420 }
1444 }
1421
1445
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/activity_panel.rs +4 −0
@@ -45,6 +45,10 @@ pub struct ActivityPanel {
45 45 impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
46 46
47 47 impl ActivityPanel {
48 pub fn activity(&self) -> Entity<ActivityCenter> {
49 self.activity.clone()
50 }
51
48 52 pub fn new(
49 53 app: Entity<AppState>,
50 54 activity: Entity<ActivityCenter>,
@@ -45,6 +45,10 @@ pub struct ActivityPanel {
45impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
45impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
46
46
47impl ActivityPanel {
47impl ActivityPanel {
48 pub fn activity(&self) -> Entity<ActivityCenter> {
49 self.activity.clone()
50 }
51
48 pub fn new(
52 pub fn new(
49 app: Entity<AppState>,
53 app: Entity<AppState>,
50 activity: Entity<ActivityCenter>,
54 activity: Entity<ActivityCenter>,
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 pub(crate) mod delivery;
@@ -121,6 +122,7 @@ pub enum ComposerEvent {
121 122 send_at: DateTime<Utc>,
122 123 },
123 124 EditLast,
125 FocusMessages,
124 126 Typing(bool),
125 127 }
126 128
@@ -233,6 +235,19 @@ pub struct Composer {
233 235
234 236 impl EventEmitter<ComposerEvent> for Composer {}
235 237
238 /// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.
239 pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {
240 behavior == EnterKeyBehavior::NewLine && !shift && !secondary
241 }
242
243 pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {
244 match behavior {
245 UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),
246 UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),
247 UpArrowBehavior::StayInCompose => None,
248 }
249 }
250
236 251 pub fn is_plain_enter(event: &InputEvent) -> bool {
237 252 matches!(event, InputEvent::PressEnter { shift: false, .. })
238 253 }
@@ -541,7 +556,10 @@ impl Composer {
541 556 return;
542 557 }
543 558 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
544 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
559 if typed.is_some()
560 && !self.app.read(cx).markdown_mode
561 && self.convert_markdown(cursor, window, cx)
562 {
545 563 return;
546 564 }
547 565 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
@@ -1712,12 +1730,15 @@ impl Composer {
1712 1730 draft.replace(range, glyph);
1713 1731 draft.take_edits();
1714 1732 }
1715 let mentions = state
1733 let mentions: Vec<MentionInput> = state
1716 1734 .tokens()
1717 1735 .iter()
1718 1736 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1719 1737 .cloned()
1720 1738 .collect();
1739 if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {
1740 draft = Draft::from_markdown(draft.text());
1741 }
1721 1742 Outgoing {
1722 1743 draft,
1723 1744 subject: None,
@@ -2434,7 +2455,10 @@ impl Composer {
2434 2455
2435 2456 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2436 2457 let composer = cx.entity().downgrade();
2437 let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();
2458 let floating = focused
2459 && self.toolbar_requested(cx)
2460 && !self.format_bar_open()
2461 && !self.app.read(cx).markdown_mode;
2438 2462 if self.link_editor.is_none() && !floating {
2439 2463 return None;
2440 2464 }
@@ -2737,36 +2761,39 @@ impl Render for Composer {
2737 2761 ))
2738 2762 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2739 2763 });
2740 let format_open = self.format_bar_open();
2741 let format_toggle = div()
2742 .id("composer-format")
2743 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2744 .size(px(COMPOSER_BUTTON_SIZE))
2745 .flex_none()
2746 .flex()
2747 .items_center()
2748 .justify_center()
2749 .rounded(px(8.))
2750 .cursor_pointer()
2751 .when(format_open, |button| button.bg(theme::popup_hover()))
2752 .hover(|button| button.bg(theme::popup_hover()))
2753 .tooltip(move |window, cx| {
2754 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2755 })
2756 .child(symbol(
2757 format_toolbar::toggle_symbol(format_open),
2758 COMPOSER_ICON_SIZE,
2759 if format_open {
2760 theme::accent_soft()
2761 } else {
2762 theme::text_muted()
2763 },
2764 ))
2765 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2766 window.prevent_default();
2767 cx.stop_propagation();
2768 })
2769 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)));
2764 let markdown_mode = self.app.read(cx).markdown_mode;
2765 let format_open = self.format_bar_open() && !markdown_mode;
2766 let format_toggle = (!markdown_mode).then(|| {
2767 div()
2768 .id("composer-format")
2769 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2770 .size(px(COMPOSER_BUTTON_SIZE))
2771 .flex_none()
2772 .flex()
2773 .items_center()
2774 .justify_center()
2775 .rounded(px(8.))
2776 .cursor_pointer()
2777 .when(format_open, |button| button.bg(theme::popup_hover()))
2778 .hover(|button| button.bg(theme::popup_hover()))
2779 .tooltip(move |window, cx| {
2780 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2781 })
2782 .child(symbol(
2783 format_toolbar::toggle_symbol(format_open),
2784 COMPOSER_ICON_SIZE,
2785 if format_open {
2786 theme::accent_soft()
2787 } else {
2788 theme::text_muted()
2789 },
2790 ))
2791 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2792 window.prevent_default();
2793 cx.stop_propagation();
2794 })
2795 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
2796 });
2770 2797 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2771 2798 let composer = cx.weak_entity();
2772 2799 let tokens_composer = composer.clone();
@@ -2987,8 +3014,12 @@ impl Render for Composer {
2987 3014 } else if this.popup_is_open() {
2988 3015 this.move_highlight(-1, cx);
2989 3016 cx.stop_propagation();
2990 } else if this.editing.is_none() && this.is_empty(cx) {
2991 cx.emit(ComposerEvent::EditLast);
3017 } else if this.editing.is_none()
3018 && this.is_empty(cx)
3019 && let Some(event) =
3020 up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3021 {
3022 cx.emit(event);
2992 3023 cx.stop_propagation();
2993 3024 }
2994 3025 }))
@@ -3034,6 +3065,19 @@ impl Render for Composer {
3034 3065 } else if this.popup_is_open() {
3035 3066 this.accept_popup(window, cx);
3036 3067 cx.stop_propagation();
3068 } else if enter_starts_line(
3069 this.app.read(cx).account_chat_settings().enter_key,
3070 action.shift,
3071 action.secondary,
3072 ) {
3073 cx.stop_propagation();
3074 window.dispatch_action(
3075 Box::new(Enter {
3076 secondary: false,
3077 shift: true,
3078 }),
3079 cx,
3080 );
3037 3081 } else if this.break_line(action.shift, window, cx) {
3038 3082 cx.stop_propagation();
3039 3083 }
@@ -3165,7 +3209,7 @@ impl Render for Composer {
3165 3209 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3166 3210 .flex_none()
3167 3211 .gap(px(COMPOSER_BUTTON_INSET))
3168 .child(format_toggle)
3212 .children(format_toggle)
3169 3213 .children(self.render_delivery_button(cx))
3170 3214 .children(fun)
3171 3215 .children(attach),
@@ -3206,7 +3250,31 @@ impl Render for Composer {
3206 3250
3207 3251 #[cfg(test)]
3208 3252 mod tests {
3209 use super::{active_mention, submitted_text};
3253 use super::{
3254 ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,
3255 submitted_text, up_arrow_event,
3256 };
3257
3258 #[test]
3259 fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3260 assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3261 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3262 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3263 assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3264 }
3265
3266 #[test]
3267 fn up_arrow_follows_the_account_setting() {
3268 assert!(matches!(
3269 up_arrow_event(UpArrowBehavior::EditLastMessage),
3270 Some(ComposerEvent::EditLast)
3271 ));
3272 assert!(matches!(
3273 up_arrow_event(UpArrowBehavior::NavigateToMessages),
3274 Some(ComposerEvent::FocusMessages)
3275 ));
3276 assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3277 }
3210 3278 use gpui_kit::component::input::InputEvent;
3211 3279
3212 3280 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
32pub(crate) mod delivery;
33pub(crate) mod delivery;
@@ -121,6 +122,7 @@ pub enum ComposerEvent {
121 send_at: DateTime<Utc>,
122 send_at: DateTime<Utc>,
122 },
123 },
123 EditLast,
124 EditLast,
125 FocusMessages,
124 Typing(bool),
126 Typing(bool),
125}
127}
126
128
@@ -233,6 +235,19 @@ pub struct Composer {
233
235
234impl EventEmitter<ComposerEvent> for Composer {}
236impl EventEmitter<ComposerEvent> for Composer {}
235
237
238/// With "Start a new line", plain Enter breaks the line and only Ctrl+Enter sends.
239pub fn enter_starts_line(behavior: EnterKeyBehavior, shift: bool, secondary: bool) -> bool {
240 behavior == EnterKeyBehavior::NewLine && !shift && !secondary
241}
242
243pub fn up_arrow_event(behavior: UpArrowBehavior) -> Option<ComposerEvent> {
244 match behavior {
245 UpArrowBehavior::EditLastMessage => Some(ComposerEvent::EditLast),
246 UpArrowBehavior::NavigateToMessages => Some(ComposerEvent::FocusMessages),
247 UpArrowBehavior::StayInCompose => None,
248 }
249}
250
236pub fn is_plain_enter(event: &InputEvent) -> bool {
251pub fn is_plain_enter(event: &InputEvent) -> bool {
237 matches!(event, InputEvent::PressEnter { shift: false, .. })
252 matches!(event, InputEvent::PressEnter { shift: false, .. })
238}
253}
@@ -541,7 +556,10 @@ impl Composer {
541 return;
556 return;
542 }
557 }
543 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
558 let typed = emoji::typed_char(&previous, self.draft.text(), cursor);
544 if typed.is_some() && self.convert_markdown(cursor, window, cx) {
559 if typed.is_some()
560 && !self.app.read(cx).markdown_mode
561 && self.convert_markdown(cursor, window, cx)
562 {
545 return;
563 return;
546 }
564 }
547 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
565 if matches!(typed, Some(' ' | '\n')) && self.convert_link(cursor, window, cx) {
@@ -1712,12 +1730,15 @@ impl Composer {
1712 draft.replace(range, glyph);
1730 draft.replace(range, glyph);
1713 draft.take_edits();
1731 draft.take_edits();
1714 }
1732 }
1715 let mentions = state
1733 let mentions: Vec<MentionInput> = state
1716 .tokens()
1734 .tokens()
1717 .iter()
1735 .iter()
1718 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1736 .filter_map(|span| self.mention_inputs.get(span.token().id().as_ref()))
1719 .cloned()
1737 .cloned()
1720 .collect();
1738 .collect();
1739 if self.app.read(cx).markdown_mode && mentions.is_empty() && image_ids.is_empty() {
1740 draft = Draft::from_markdown(draft.text());
1741 }
1721 Outgoing {
1742 Outgoing {
1722 draft,
1743 draft,
1723 subject: None,
1744 subject: None,
@@ -2434,7 +2455,10 @@ impl Composer {
2434
2455
2435 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2456 fn render_toolbar(&self, focused: bool, cx: &mut Context<Self>) -> Option<AnyElement> {
2436 let composer = cx.entity().downgrade();
2457 let composer = cx.entity().downgrade();
2437 let floating = focused && self.toolbar_requested(cx) && !self.format_bar_open();
2458 let floating = focused
2459 && self.toolbar_requested(cx)
2460 && !self.format_bar_open()
2461 && !self.app.read(cx).markdown_mode;
2438 if self.link_editor.is_none() && !floating {
2462 if self.link_editor.is_none() && !floating {
2439 return None;
2463 return None;
2440 }
2464 }
@@ -2737,36 +2761,39 @@ impl Render for Composer {
2737 ))
2761 ))
2738 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2762 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2739 });
2763 });
2740 let format_open = self.format_bar_open();
2764 let markdown_mode = self.app.read(cx).markdown_mode;
2741 let format_toggle = div()
2765 let format_open = self.format_bar_open() && !markdown_mode;
2742 .id("composer-format")
2766 let format_toggle = (!markdown_mode).then(|| {
2743 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2767 div()
2744 .size(px(COMPOSER_BUTTON_SIZE))
2768 .id("composer-format")
2745 .flex_none()
2769 .debug_selector(|| COMPOSER_FORMAT_TAG.into())
2746 .flex()
2770 .size(px(COMPOSER_BUTTON_SIZE))
2747 .items_center()
2771 .flex_none()
2748 .justify_center()
2772 .flex()
2749 .rounded(px(8.))
2773 .items_center()
2750 .cursor_pointer()
2774 .justify_center()
2751 .when(format_open, |button| button.bg(theme::popup_hover()))
2775 .rounded(px(8.))
2752 .hover(|button| button.bg(theme::popup_hover()))
2776 .cursor_pointer()
2753 .tooltip(move |window, cx| {
2777 .when(format_open, |button| button.bg(theme::popup_hover()))
2754 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2778 .hover(|button| button.bg(theme::popup_hover()))
2755 })
2779 .tooltip(move |window, cx| {
2756 .child(symbol(
2780 Tooltip::new(format_toolbar::toggle_tooltip(format_open)).build(window, cx)
2757 format_toolbar::toggle_symbol(format_open),
2781 })
2758 COMPOSER_ICON_SIZE,
2782 .child(symbol(
2759 if format_open {
2783 format_toolbar::toggle_symbol(format_open),
2760 theme::accent_soft()
2784 COMPOSER_ICON_SIZE,
2761 } else {
2785 if format_open {
2762 theme::text_muted()
2786 theme::accent_soft()
2763 },
2787 } else {
2764 ))
2788 theme::text_muted()
2765 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2789 },
2766 window.prevent_default();
2790 ))
2767 cx.stop_propagation();
2791 .on_mouse_down(MouseButton::Left, |_, window, cx| {
2768 })
2792 window.prevent_default();
2769 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)));
2793 cx.stop_propagation();
2794 })
2795 .on_click(cx.listener(|this, _, window, cx| this.toggle_format_bar(window, cx)))
2796 });
2770 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2797 let format_bar = format_open.then(|| self.render_format_bar(window, cx));
2771 let composer = cx.weak_entity();
2798 let composer = cx.weak_entity();
2772 let tokens_composer = composer.clone();
2799 let tokens_composer = composer.clone();
@@ -2987,8 +3014,12 @@ impl Render for Composer {
2987 } else if this.popup_is_open() {
3014 } else if this.popup_is_open() {
2988 this.move_highlight(-1, cx);
3015 this.move_highlight(-1, cx);
2989 cx.stop_propagation();
3016 cx.stop_propagation();
2990 } else if this.editing.is_none() && this.is_empty(cx) {
3017 } else if this.editing.is_none()
2991 cx.emit(ComposerEvent::EditLast);
3018 && this.is_empty(cx)
3019 && let Some(event) =
3020 up_arrow_event(this.app.read(cx).account_chat_settings().up_arrow)
3021 {
3022 cx.emit(event);
2992 cx.stop_propagation();
3023 cx.stop_propagation();
2993 }
3024 }
2994 }))
3025 }))
@@ -3034,6 +3065,19 @@ impl Render for Composer {
3034 } else if this.popup_is_open() {
3065 } else if this.popup_is_open() {
3035 this.accept_popup(window, cx);
3066 this.accept_popup(window, cx);
3036 cx.stop_propagation();
3067 cx.stop_propagation();
3068 } else if enter_starts_line(
3069 this.app.read(cx).account_chat_settings().enter_key,
3070 action.shift,
3071 action.secondary,
3072 ) {
3073 cx.stop_propagation();
3074 window.dispatch_action(
3075 Box::new(Enter {
3076 secondary: false,
3077 shift: true,
3078 }),
3079 cx,
3080 );
3037 } else if this.break_line(action.shift, window, cx) {
3081 } else if this.break_line(action.shift, window, cx) {
3038 cx.stop_propagation();
3082 cx.stop_propagation();
3039 }
3083 }
@@ -3165,7 +3209,7 @@ impl Render for Composer {
3165 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3209 .debug_selector(|| COMPOSER_LEADING_TAG.into())
3166 .flex_none()
3210 .flex_none()
3167 .gap(px(COMPOSER_BUTTON_INSET))
3211 .gap(px(COMPOSER_BUTTON_INSET))
3168 .child(format_toggle)
3212 .children(format_toggle)
3169 .children(self.render_delivery_button(cx))
3213 .children(self.render_delivery_button(cx))
3170 .children(fun)
3214 .children(fun)
3171 .children(attach),
3215 .children(attach),
@@ -3206,7 +3250,31 @@ impl Render for Composer {
3206
3250
3207#[cfg(test)]
3251#[cfg(test)]
3208mod tests {
3252mod tests {
3209 use super::{active_mention, submitted_text};
3253 use super::{
3254 ComposerEvent, EnterKeyBehavior, UpArrowBehavior, active_mention, enter_starts_line,
3255 submitted_text, up_arrow_event,
3256 };
3257
3258 #[test]
3259 fn new_line_mode_keeps_plain_enter_and_sends_on_ctrl_enter() {
3260 assert!(enter_starts_line(EnterKeyBehavior::NewLine, false, false));
3261 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, false, true));
3262 assert!(!enter_starts_line(EnterKeyBehavior::NewLine, true, false));
3263 assert!(!enter_starts_line(EnterKeyBehavior::Send, false, false));
3264 }
3265
3266 #[test]
3267 fn up_arrow_follows_the_account_setting() {
3268 assert!(matches!(
3269 up_arrow_event(UpArrowBehavior::EditLastMessage),
3270 Some(ComposerEvent::EditLast)
3271 ));
3272 assert!(matches!(
3273 up_arrow_event(UpArrowBehavior::NavigateToMessages),
3274 Some(ComposerEvent::FocusMessages)
3275 ));
3276 assert!(up_arrow_event(UpArrowBehavior::StayInCompose).is_none());
3277 }
3210 use gpui_kit::component::input::InputEvent;
3278 use gpui_kit::component::input::InputEvent;
3211
3279
3212 fn press(shift: bool) -> InputEvent {
3280 fn press(shift: bool) -> InputEvent {
crates/app/src/views/composer/delivery.rs +29 −10
@@ -1,3 +1,7 @@
1 use gpui_kit::component::fluent::{
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4 };
1 5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
2 6 use gpui_kit::prelude::FluentBuilder as _;
3 7 use gpui_kit::*;
@@ -17,10 +21,8 @@ pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";
17 21 pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
18 22 pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
19 23 const MENU_WIDTH: f32 = 320.;
20 const MENU_PADDING: f32 = 4.;
21 const ROW_PADDING: f32 = 10.;
22 24 const OPTION_ICON_SIZE: f32 = 20.;
23 const CHECK_SIZE: f32 = 16.;
25 const BANNER_ICON_SIZE: f32 = 16.;
24 26 const DISABLED_OPACITY: f32 = 0.4;
25 27 const LABEL_SIZE: f32 = 12.;
26 28 const LABEL_LINE_HEIGHT: f32 = 16.;
@@ -124,7 +126,8 @@ impl Composer {
124 126 .mb(px(6.))
125 127 .w(px(MENU_WIDTH))
126 128 .max_w(relative(1.))
127 .p(px(MENU_PADDING))
129 .p(MENU_LIST_PADDING)
130 .gap(MENU_ITEM_GAP)
128 131 .rounded(px(10.))
129 132 .flyout_surface()
130 133 .occlude()
@@ -153,11 +156,21 @@ impl Composer {
153 156 .id(option.tag)
154 157 .debug_selector(|| option.tag.into())
155 158 .w_full()
156 .p(px(ROW_PADDING))
157 .gap(px(ROW_PADDING))
159 .min_h(MENU_ITEM_HEIGHT)
160 .px(MENU_ITEM_PADDING_X)
161 .py(MENU_ITEM_PADDING_X)
162 .gap(MENU_ICON_LABEL_GAP)
158 163 .items_center()
159 164 .rounded(px(6.))
160 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent))
165 .child(
166 div()
167 .size(MENU_ICON_SLOT)
168 .flex_none()
169 .flex()
170 .items_center()
171 .justify_center()
172 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),
173 )
161 174 .child(
162 175 v_flex()
163 176 .flex_1()
@@ -176,7 +189,9 @@ impl Composer {
176 189 .child(option.content),
177 190 ),
178 191 )
179 .children(selected.then(|| symbol("done", CHECK_SIZE, theme::text())));
192 .children(
193 selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),
194 );
180 195 if !enabled {
181 196 return row
182 197 .opacity(DISABLED_OPACITY)
@@ -238,7 +253,11 @@ impl Composer {
238 253 .bg(theme::red().opacity(BANNER_TINT))
239 254 .text_size(px(12.))
240 255 .text_color(theme::red_tint())
241 .child(symbol("fluent_alert_urgent", CHECK_SIZE, theme::red_tint()))
256 .child(symbol(
257 "fluent_alert_urgent",
258 BANNER_ICON_SIZE,
259 theme::red_tint(),
260 ))
242 261 .child(
243 262 div()
244 263 .flex_1()
@@ -258,7 +277,7 @@ impl Composer {
258 277 .cursor_pointer()
259 278 .hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
260 279 .tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
261 .child(symbol("close", CHECK_SIZE, theme::red_tint()))
280 .child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))
262 281 .on_click(cx.listener(|this, _, window, cx| {
263 282 this.choose_importance(MessageImportance::Normal, window, cx)
264 283 })),
@@ -1,3 +1,7 @@
1use gpui_kit::component::fluent::{
2 MENU_ICON_LABEL_GAP, MENU_ICON_SLOT, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X,
3 MENU_LIST_PADDING, OPTION_CHECK_SIZE,
4};
1use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
2use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::prelude::FluentBuilder as _;
3use gpui_kit::*;
7use gpui_kit::*;
@@ -17,10 +21,8 @@ pub const COMPOSER_IMPORTANCE_LABEL_TAG: &str = "composer/importance-label";
17pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
21pub const COMPOSER_URGENT_BANNER_TAG: &str = "composer-urgent-banner";
18pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
22pub const DELIVERY_MENU_TAG: &str = "delivery-menu";
19const MENU_WIDTH: f32 = 320.;
23const MENU_WIDTH: f32 = 320.;
20const MENU_PADDING: f32 = 4.;
21const ROW_PADDING: f32 = 10.;
22const OPTION_ICON_SIZE: f32 = 20.;
24const OPTION_ICON_SIZE: f32 = 20.;
23const CHECK_SIZE: f32 = 16.;
25const BANNER_ICON_SIZE: f32 = 16.;
24const DISABLED_OPACITY: f32 = 0.4;
26const DISABLED_OPACITY: f32 = 0.4;
25const LABEL_SIZE: f32 = 12.;
27const LABEL_SIZE: f32 = 12.;
26const LABEL_LINE_HEIGHT: f32 = 16.;
28const LABEL_LINE_HEIGHT: f32 = 16.;
@@ -124,7 +126,8 @@ impl Composer {
124 .mb(px(6.))
126 .mb(px(6.))
125 .w(px(MENU_WIDTH))
127 .w(px(MENU_WIDTH))
126 .max_w(relative(1.))
128 .max_w(relative(1.))
127 .p(px(MENU_PADDING))
129 .p(MENU_LIST_PADDING)
130 .gap(MENU_ITEM_GAP)
128 .rounded(px(10.))
131 .rounded(px(10.))
129 .flyout_surface()
132 .flyout_surface()
130 .occlude()
133 .occlude()
@@ -153,11 +156,21 @@ impl Composer {
153 .id(option.tag)
156 .id(option.tag)
154 .debug_selector(|| option.tag.into())
157 .debug_selector(|| option.tag.into())
155 .w_full()
158 .w_full()
156 .p(px(ROW_PADDING))
159 .min_h(MENU_ITEM_HEIGHT)
157 .gap(px(ROW_PADDING))
160 .px(MENU_ITEM_PADDING_X)
161 .py(MENU_ITEM_PADDING_X)
162 .gap(MENU_ICON_LABEL_GAP)
158 .items_center()
163 .items_center()
159 .rounded(px(6.))
164 .rounded(px(6.))
160 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent))
165 .child(
166 div()
167 .size(MENU_ICON_SLOT)
168 .flex_none()
169 .flex()
170 .items_center()
171 .justify_center()
172 .child(symbol(option.symbol, OPTION_ICON_SIZE, accent)),
173 )
161 .child(
174 .child(
162 v_flex()
175 v_flex()
163 .flex_1()
176 .flex_1()
@@ -176,7 +189,9 @@ impl Composer {
176 .child(option.content),
189 .child(option.content),
177 ),
190 ),
178 )
191 )
179 .children(selected.then(|| symbol("done", CHECK_SIZE, theme::text())));
192 .children(
193 selected.then(|| symbol("done", f32::from(OPTION_CHECK_SIZE), theme::text())),
194 );
180 if !enabled {
195 if !enabled {
181 return row
196 return row
182 .opacity(DISABLED_OPACITY)
197 .opacity(DISABLED_OPACITY)
@@ -238,7 +253,11 @@ impl Composer {
238 .bg(theme::red().opacity(BANNER_TINT))
253 .bg(theme::red().opacity(BANNER_TINT))
239 .text_size(px(12.))
254 .text_size(px(12.))
240 .text_color(theme::red_tint())
255 .text_color(theme::red_tint())
241 .child(symbol("fluent_alert_urgent", CHECK_SIZE, theme::red_tint()))
256 .child(symbol(
257 "fluent_alert_urgent",
258 BANNER_ICON_SIZE,
259 theme::red_tint(),
260 ))
242 .child(
261 .child(
243 div()
262 div()
244 .flex_1()
263 .flex_1()
@@ -258,7 +277,7 @@ impl Composer {
258 .cursor_pointer()
277 .cursor_pointer()
259 .hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
278 .hover(|button| button.bg(theme::red().opacity(BANNER_TINT)))
260 .tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
279 .tooltip(|window, cx| Tooltip::new("Send as standard").build(window, cx))
261 .child(symbol("close", CHECK_SIZE, theme::red_tint()))
280 .child(symbol("close", BANNER_ICON_SIZE, theme::red_tint()))
262 .on_click(cx.listener(|this, _, window, cx| {
281 .on_click(cx.listener(|this, _, window, cx| {
263 this.choose_importance(MessageImportance::Normal, window, cx)
282 this.choose_importance(MessageImportance::Normal, window, cx)
264 })),
283 })),
crates/app/src/views/conversation.rs +123 −14
@@ -22,7 +22,10 @@ use teams_core::{
22 22 };
23 23
24 24 mod channel_details;
25 pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
25 pub use channel_details::{
26 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_TAG,
28 };
26 29 mod deletes;
27 30 mod detached;
28 31 mod feed;
@@ -35,16 +38,18 @@ mod render_env;
35 38 mod scheduled;
36 39 mod shared;
37 40
41 use super::add_people_dialog::open_add_people;
38 42 use super::attachments::FileActions;
39 43 use super::avatar::{
40 44 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
41 45 };
42 46 use super::call_controls::header_call_controls;
43 47 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
44 use super::add_people_dialog::open_add_people;
45 48 use super::chat_members::members_popover;
46 49 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
47 use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
50 use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
51 use super::group_name::group_name_button;
52 use super::message_actions::{Action, DelegateEntry, MessageMenu};
48 53 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
49 54 use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
50 55 use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
@@ -60,6 +65,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
60 65 use crate::backend::Engine;
61 66 use crate::card_state::CardScope;
62 67 use crate::channel_files::DownloadSource;
68 use crate::chat_settings_actions::shown_receipt;
63 69 use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
64 70 use crate::demo_library::DemoLibrary;
65 71 use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
@@ -100,6 +106,7 @@ const HEADER_PADDING: f32 = 20.;
100 106 const HEADER_GAP: f32 = 12.;
101 107 const HEADER_LEAD_SIZE: f32 = 36.;
102 108 const TABS_INLINE_MIN_WIDTH: f32 = 560.;
109 const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
103 110 const TABS_ROW_HEIGHT: f32 = 36.;
104 111 const CHAT_OPEN_LIMIT: usize = 60;
105 112 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -239,6 +246,8 @@ pub struct ConversationView {
239 246 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
240 247 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
241 248 receipt_fade: receipt_fade::ReceiptFade,
249 find_panel: Option<Entity<FindPanel>>,
250 find_subscription: Option<Subscription>,
242 251 _subscriptions: Vec<Subscription>,
243 252 }
244 253
@@ -570,6 +579,8 @@ impl ConversationView {
570 579 agent_runs: Rc::new(RefCell::new(HashMap::new())),
571 580 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
572 581 receipt_fade: receipt_fade::ReceiptFade::default(),
582 find_panel: None,
583 find_subscription: None,
573 584 _subscriptions: subscriptions,
574 585 };
575 586 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -639,7 +650,7 @@ impl ConversationView {
639 650 .as_ref()
640 651 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
641 652 if is_current {
642 if self.shared_active() || self.recap_active() {
653 if self.shared_active() || self.recap_active() || self.channel_details_open {
643 654 self.refresh_shared_items(cx);
644 655 }
645 656 self.rebuild(false, cx);
@@ -679,7 +690,7 @@ impl ConversationView {
679 690 | AppEvent::Call => {}
680 691 AppEvent::LiveMeeting => cx.notify(),
681 692 AppEvent::Saved => cx.notify(),
682 AppEvent::Translation => self.rebuild(false, cx),
693 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
683 694 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
684 695 AppEvent::Typing => cx.notify(),
685 696 AppEvent::Scheduled => self.rebuild(false, cx),
@@ -729,6 +740,7 @@ impl ConversationView {
729 740 self.schedule((**outgoing).clone(), *send_at, window, cx)
730 741 }
731 742 ComposerEvent::EditLast => self.edit_last_own(window, cx),
743 ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
732 744 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
733 745 }
734 746 }
@@ -845,6 +857,14 @@ impl ConversationView {
845 857 }
846 858
847 859 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
860 if self
861 .find_panel
862 .as_ref()
863 .is_some_and(|panel| panel.read(cx).selection() != &selection)
864 {
865 self.find_panel = None;
866 self.find_subscription = None;
867 }
848 868 self.stop_typing(cx);
849 869 self.stop_reply_typing(cx);
850 870 self.new_post_open = false;
@@ -1874,6 +1894,15 @@ impl ConversationView {
1874 1894 }
1875 1895
1876 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> {
1877 1906 let state = self.app.read(cx);
1878 1907 if state.mode.demo {
1879 1908 let read_ids = crate::demo::read_message_ids(records);
@@ -3026,6 +3055,7 @@ impl ConversationView {
3026 3055 let saved = self
3027 3056 .conversation_id()
3028 3057 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3058 let quick = state.quick_reactions();
3029 3059 let in_chat = chat_id.is_some();
3030 3060 let pin_conversation_id = self.pin_conversation_id();
3031 3061 let pinned = pin_conversation_id
@@ -3051,7 +3081,8 @@ impl ConversationView {
3051 3081 translate_label,
3052 3082 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3053 3083 saved,
3054 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3084 toggle_pinned: pinnable
3085 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3055 3086 pinned,
3056 3087 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3057 3088 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3063,7 +3094,7 @@ impl ConversationView {
3063 3094 pin,
3064 3095 hover,
3065 3096 picker: self.picker.clone(),
3066 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3097 quick,
3067 3098 mine,
3068 3099 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3069 3100 }
@@ -3230,6 +3261,51 @@ impl ConversationView {
3230 3261 )
3231 3262 }
3232 3263
3264 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3265 if self.pinned || self.draft_active {
3266 return;
3267 }
3268 let Some(selection) = self
3269 .current
3270 .as_ref()
3271 .map(|current| current.selection.clone())
3272 else {
3273 return;
3274 };
3275 self.channel_details_open = false;
3276 if let Some(panel) = &self.find_panel {
3277 panel.update(cx, |panel, cx| panel.focus(window, cx));
3278 return;
3279 }
3280 let app = self.app.clone();
3281 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3282 let subscription = cx.subscribe_in(
3283 &panel,
3284 window,
3285 move |this, _, event: &FindPanelEvent, window, cx| match event {
3286 FindPanelEvent::Close => this.close_find(window, cx),
3287 FindPanelEvent::Jump(message_id) => {
3288 let (selection, message_id) = (selection.clone(), message_id.clone());
3289 this.app.update(cx, |state, cx| {
3290 state.jump_to_message(selection, message_id, cx)
3291 });
3292 }
3293 },
3294 );
3295 panel.update(cx, |panel, cx| panel.focus(window, cx));
3296 self.find_panel = Some(panel);
3297 self.find_subscription = Some(subscription);
3298 cx.notify();
3299 }
3300
3301 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3302 self.find_panel = None;
3303 self.find_subscription = None;
3304 self.composer
3305 .update(cx, |composer, cx| composer.focus(window, cx));
3306 cx.notify();
3307 }
3308
3233 3309 fn header_width(&self, window: &Window) -> f32 {
3234 3310 match self.header_width.get() {
3235 3311 width if width > 0. => width,
@@ -3258,6 +3334,7 @@ impl ConversationView {
3258 3334 let mut lead: Option<AnyElement> = None;
3259 3335 let mut subline = String::new();
3260 3336 let mut stack: Option<AnyElement> = None;
3337 let mut rename: Option<AnyElement> = None;
3261 3338 match &current.selection {
3262 3339 Selection::Chat(chat_id) => {
3263 3340 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3293,6 +3370,15 @@ impl ConversationView {
3293 3370 stack = Some(add_people_button(&self.app, chat_id));
3294 3371 }
3295 3372 } else {
3373 if chat.kind == GROUP_KIND
3374 && me.is_some_and(|me| {
3375 chat.members
3376 .iter()
3377 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3378 })
3379 {
3380 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3381 }
3296 3382 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3297 3383 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3298 3384 subline = format!("{} participants", chat.members.len());
@@ -3395,12 +3481,19 @@ impl ConversationView {
3395 3481 .overflow_hidden()
3396 3482 .gap(px(1.))
3397 3483 .child(
3398 div()
3399 .truncate()
3400 .text_size(px(15.))
3401 .font_weight(FontWeight::SEMIBOLD)
3402 .text_color(theme::text())
3403 .child(current.title.clone()),
3484 h_flex()
3485 .min_w_0()
3486 .gap(px(2.))
3487 .items_center()
3488 .child(
3489 div()
3490 .truncate()
3491 .text_size(px(15.))
3492 .font_weight(FontWeight::SEMIBOLD)
3493 .text_color(theme::text())
3494 .child(current.title.clone()),
3495 )
3496 .children(rename),
3404 3497 )
3405 3498 .when(!subline.is_empty(), |column| {
3406 3499 column.child(
@@ -3418,6 +3511,8 @@ impl ConversationView {
3418 3511 }
3419 3512 }
3420 3513
3514 const GROUP_KIND: &str = "group";
3515
3421 3516 impl Render for ConversationView {
3422 3517 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3423 3518 let background = theme::surface();
@@ -3650,6 +3745,8 @@ impl Render for ConversationView {
3650 3745 scroller.into_any_element()
3651 3746 };
3652 3747 let channel_details = self.render_channel_details(cx);
3748 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3749 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3653 3750 let content = v_flex()
3654 3751 .relative()
3655 3752 .flex_1()
@@ -3677,12 +3774,24 @@ impl Render for ConversationView {
3677 3774 .child(self.render_drop_overlay(cx));
3678 3775 root.child(
3679 3776 h_flex()
3777 .relative()
3680 3778 .flex_1()
3681 3779 .min_h_0()
3682 3780 .w_full()
3683 3781 .items_stretch()
3684 3782 .child(content)
3685 .children(channel_details),
3783 .children(channel_details)
3784 .children(find_panel.map(|panel| {
3785 div()
3786 .h_full()
3787 .w(px(FIND_PANEL_WIDTH))
3788 .min_w_0()
3789 .flex_shrink(1.)
3790 .when(find_overlays, |slot| {
3791 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3792 })
3793 .child(panel)
3794 })),
3686 3795 )
3687 3796 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3688 3797 if this.reaction_details.is_some() {
@@ -22,7 +22,10 @@ use teams_core::{
22};
22};
23
23
24mod channel_details;
24mod channel_details;
25pub use channel_details::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
25pub use channel_details::{
26 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_TAG,
28};
26mod deletes;
29mod deletes;
27mod detached;
30mod detached;
28mod feed;
31mod feed;
@@ -35,16 +38,18 @@ mod render_env;
35mod scheduled;
38mod scheduled;
36mod shared;
39mod shared;
37
40
41use super::add_people_dialog::open_add_people;
38use super::attachments::FileActions;
42use super::attachments::FileActions;
39use super::avatar::{
43use super::avatar::{
40 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
44 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
41};
45};
42use super::call_controls::header_call_controls;
46use super::call_controls::header_call_controls;
43use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
47use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
44use super::add_people_dialog::open_add_people;
45use super::chat_members::members_popover;
48use super::chat_members::members_popover;
46use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
49use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
47use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
50use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
51use super::group_name::group_name_button;
52use super::message_actions::{Action, DelegateEntry, MessageMenu};
48use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
53use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
49use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
54use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
50use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
55use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
@@ -60,6 +65,7 @@ use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_t
60use crate::backend::Engine;
65use crate::backend::Engine;
61use crate::card_state::CardScope;
66use crate::card_state::CardScope;
62use crate::channel_files::DownloadSource;
67use crate::channel_files::DownloadSource;
68use crate::chat_settings_actions::shown_receipt;
63use 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};
64use crate::demo_library::DemoLibrary;
70use crate::demo_library::DemoLibrary;
65use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
71use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
@@ -100,6 +106,7 @@ const HEADER_PADDING: f32 = 20.;
100const HEADER_GAP: f32 = 12.;
106const HEADER_GAP: f32 = 12.;
101const HEADER_LEAD_SIZE: f32 = 36.;
107const HEADER_LEAD_SIZE: f32 = 36.;
102const TABS_INLINE_MIN_WIDTH: f32 = 560.;
108const TABS_INLINE_MIN_WIDTH: f32 = 560.;
109const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
103const TABS_ROW_HEIGHT: f32 = 36.;
110const TABS_ROW_HEIGHT: f32 = 36.;
104const CHAT_OPEN_LIMIT: usize = 60;
111const CHAT_OPEN_LIMIT: usize = 60;
105const CHANNEL_OPEN_LIMIT: usize = 300;
112const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -239,6 +246,8 @@ pub struct ConversationView {
239 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
246 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
240 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
247 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
241 receipt_fade: receipt_fade::ReceiptFade,
248 receipt_fade: receipt_fade::ReceiptFade,
249 find_panel: Option<Entity<FindPanel>>,
250 find_subscription: Option<Subscription>,
242 _subscriptions: Vec<Subscription>,
251 _subscriptions: Vec<Subscription>,
243}
252}
244
253
@@ -570,6 +579,8 @@ impl ConversationView {
570 agent_runs: Rc::new(RefCell::new(HashMap::new())),
579 agent_runs: Rc::new(RefCell::new(HashMap::new())),
571 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
580 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
572 receipt_fade: receipt_fade::ReceiptFade::default(),
581 receipt_fade: receipt_fade::ReceiptFade::default(),
582 find_panel: None,
583 find_subscription: None,
573 _subscriptions: subscriptions,
584 _subscriptions: subscriptions,
574 };
585 };
575 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
586 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -639,7 +650,7 @@ impl ConversationView {
639 .as_ref()
650 .as_ref()
640 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
651 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
641 if is_current {
652 if is_current {
642 if self.shared_active() || self.recap_active() {
653 if self.shared_active() || self.recap_active() || self.channel_details_open {
643 self.refresh_shared_items(cx);
654 self.refresh_shared_items(cx);
644 }
655 }
645 self.rebuild(false, cx);
656 self.rebuild(false, cx);
@@ -679,7 +690,7 @@ impl ConversationView {
679 | AppEvent::Call => {}
690 | AppEvent::Call => {}
680 AppEvent::LiveMeeting => cx.notify(),
691 AppEvent::LiveMeeting => cx.notify(),
681 AppEvent::Saved => cx.notify(),
692 AppEvent::Saved => cx.notify(),
682 AppEvent::Translation => self.rebuild(false, cx),
693 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
683 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
694 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
684 AppEvent::Typing => cx.notify(),
695 AppEvent::Typing => cx.notify(),
685 AppEvent::Scheduled => self.rebuild(false, cx),
696 AppEvent::Scheduled => self.rebuild(false, cx),
@@ -729,6 +740,7 @@ impl ConversationView {
729 self.schedule((**outgoing).clone(), *send_at, window, cx)
740 self.schedule((**outgoing).clone(), *send_at, window, cx)
730 }
741 }
731 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),
732 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
744 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
733 }
745 }
734 }
746 }
@@ -845,6 +857,14 @@ impl ConversationView {
845 }
857 }
846
858
847 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
859 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
860 if self
861 .find_panel
862 .as_ref()
863 .is_some_and(|panel| panel.read(cx).selection() != &selection)
864 {
865 self.find_panel = None;
866 self.find_subscription = None;
867 }
848 self.stop_typing(cx);
868 self.stop_typing(cx);
849 self.stop_reply_typing(cx);
869 self.stop_reply_typing(cx);
850 self.new_post_open = false;
870 self.new_post_open = false;
@@ -1874,6 +1894,15 @@ impl ConversationView {
1874 }
1894 }
1875
1895
1876 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> {
1877 let state = self.app.read(cx);
1906 let state = self.app.read(cx);
1878 if state.mode.demo {
1907 if state.mode.demo {
1879 let read_ids = crate::demo::read_message_ids(records);
1908 let read_ids = crate::demo::read_message_ids(records);
@@ -3026,6 +3055,7 @@ impl ConversationView {
3026 let saved = self
3055 let saved = self
3027 .conversation_id()
3056 .conversation_id()
3028 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3057 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3058 let quick = state.quick_reactions();
3029 let in_chat = chat_id.is_some();
3059 let in_chat = chat_id.is_some();
3030 let pin_conversation_id = self.pin_conversation_id();
3060 let pin_conversation_id = self.pin_conversation_id();
3031 let pinned = pin_conversation_id
3061 let pinned = pin_conversation_id
@@ -3051,7 +3081,8 @@ impl ConversationView {
3051 translate_label,
3081 translate_label,
3052 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3082 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3053 saved,
3083 saved,
3054 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3084 toggle_pinned: pinnable
3085 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3055 pinned,
3086 pinned,
3056 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3087 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3057 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3088 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3063,7 +3094,7 @@ impl ConversationView {
3063 pin,
3094 pin,
3064 hover,
3095 hover,
3065 picker: self.picker.clone(),
3096 picker: self.picker.clone(),
3066 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3097 quick,
3067 mine,
3098 mine,
3068 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3099 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3069 }
3100 }
@@ -3230,6 +3261,51 @@ impl ConversationView {
3230 )
3261 )
3231 }
3262 }
3232
3263
3264 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3265 if self.pinned || self.draft_active {
3266 return;
3267 }
3268 let Some(selection) = self
3269 .current
3270 .as_ref()
3271 .map(|current| current.selection.clone())
3272 else {
3273 return;
3274 };
3275 self.channel_details_open = false;
3276 if let Some(panel) = &self.find_panel {
3277 panel.update(cx, |panel, cx| panel.focus(window, cx));
3278 return;
3279 }
3280 let app = self.app.clone();
3281 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3282 let subscription = cx.subscribe_in(
3283 &panel,
3284 window,
3285 move |this, _, event: &FindPanelEvent, window, cx| match event {
3286 FindPanelEvent::Close => this.close_find(window, cx),
3287 FindPanelEvent::Jump(message_id) => {
3288 let (selection, message_id) = (selection.clone(), message_id.clone());
3289 this.app.update(cx, |state, cx| {
3290 state.jump_to_message(selection, message_id, cx)
3291 });
3292 }
3293 },
3294 );
3295 panel.update(cx, |panel, cx| panel.focus(window, cx));
3296 self.find_panel = Some(panel);
3297 self.find_subscription = Some(subscription);
3298 cx.notify();
3299 }
3300
3301 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3302 self.find_panel = None;
3303 self.find_subscription = None;
3304 self.composer
3305 .update(cx, |composer, cx| composer.focus(window, cx));
3306 cx.notify();
3307 }
3308
3233 fn header_width(&self, window: &Window) -> f32 {
3309 fn header_width(&self, window: &Window) -> f32 {
3234 match self.header_width.get() {
3310 match self.header_width.get() {
3235 width if width > 0. => width,
3311 width if width > 0. => width,
@@ -3258,6 +3334,7 @@ impl ConversationView {
3258 let mut lead: Option<AnyElement> = None;
3334 let mut lead: Option<AnyElement> = None;
3259 let mut subline = String::new();
3335 let mut subline = String::new();
3260 let mut stack: Option<AnyElement> = None;
3336 let mut stack: Option<AnyElement> = None;
3337 let mut rename: Option<AnyElement> = None;
3261 match &current.selection {
3338 match &current.selection {
3262 Selection::Chat(chat_id) => {
3339 Selection::Chat(chat_id) => {
3263 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3340 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3293,6 +3370,15 @@ impl ConversationView {
3293 stack = Some(add_people_button(&self.app, chat_id));
3370 stack = Some(add_people_button(&self.app, chat_id));
3294 }
3371 }
3295 } else {
3372 } else {
3373 if chat.kind == GROUP_KIND
3374 && me.is_some_and(|me| {
3375 chat.members
3376 .iter()
3377 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3378 })
3379 {
3380 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3381 }
3296 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3382 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3297 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3383 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3298 subline = format!("{} participants", chat.members.len());
3384 subline = format!("{} participants", chat.members.len());
@@ -3395,12 +3481,19 @@ impl ConversationView {
3395 .overflow_hidden()
3481 .overflow_hidden()
3396 .gap(px(1.))
3482 .gap(px(1.))
3397 .child(
3483 .child(
3398 div()
3484 h_flex()
3399 .truncate()
3485 .min_w_0()
3400 .text_size(px(15.))
3486 .gap(px(2.))
3401 .font_weight(FontWeight::SEMIBOLD)
3487 .items_center()
3402 .text_color(theme::text())
3488 .child(
3403 .child(current.title.clone()),
3489 div()
3490 .truncate()
3491 .text_size(px(15.))
3492 .font_weight(FontWeight::SEMIBOLD)
3493 .text_color(theme::text())
3494 .child(current.title.clone()),
3495 )
3496 .children(rename),
3404 )
3497 )
3405 .when(!subline.is_empty(), |column| {
3498 .when(!subline.is_empty(), |column| {
3406 column.child(
3499 column.child(
@@ -3418,6 +3511,8 @@ impl ConversationView {
3418 }
3511 }
3419}
3512}
3420
3513
3514const GROUP_KIND: &str = "group";
3515
3421impl Render for ConversationView {
3516impl Render for ConversationView {
3422 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3517 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3423 let background = theme::surface();
3518 let background = theme::surface();
@@ -3650,6 +3745,8 @@ impl Render for ConversationView {
3650 scroller.into_any_element()
3745 scroller.into_any_element()
3651 };
3746 };
3652 let channel_details = self.render_channel_details(cx);
3747 let channel_details = self.render_channel_details(cx);
3748 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3749 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3653 let content = v_flex()
3750 let content = v_flex()
3654 .relative()
3751 .relative()
3655 .flex_1()
3752 .flex_1()
@@ -3677,12 +3774,24 @@ impl Render for ConversationView {
3677 .child(self.render_drop_overlay(cx));
3774 .child(self.render_drop_overlay(cx));
3678 root.child(
3775 root.child(
3679 h_flex()
3776 h_flex()
3777 .relative()
3680 .flex_1()
3778 .flex_1()
3681 .min_h_0()
3779 .min_h_0()
3682 .w_full()
3780 .w_full()
3683 .items_stretch()
3781 .items_stretch()
3684 .child(content)
3782 .child(content)
3685 .children(channel_details),
3783 .children(channel_details)
3784 .children(find_panel.map(|panel| {
3785 div()
3786 .h_full()
3787 .w(px(FIND_PANEL_WIDTH))
3788 .min_w_0()
3789 .flex_shrink(1.)
3790 .when(find_overlays, |slot| {
3791 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3792 })
3793 .child(panel)
3794 })),
3686 )
3795 )
3687 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3796 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3688 if this.reaction_details.is_some() {
3797 if this.reaction_details.is_some() {
crates/app/src/views/conversation/channel_details.rs +191 −12
@@ -5,19 +5,26 @@ use gpui_kit::component::{h_flex, v_flex};
5 5 use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 7 use store::MessageRecord;
8 use teams_core::FileKind;
8 9
9 use super::ConversationView;
10 use super::{ChannelPane, ConversationView};
10 11 use crate::app_state::Selection;
12 use crate::channel_files::{SharedContent, SharedItem};
11 13 use crate::format;
12 14 use crate::rows::reply_excerpt;
13 15 use crate::theme;
16 use crate::views::attachments::file_badge;
14 17 use crate::views::avatar::person_avatar;
15 18
16 19 pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
17 20 pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
21 pub const CHANNEL_DETAILS_PINNED_TAG: &str = "shell/islands/main/channel-details/pinned";
22 pub const CHANNEL_DETAILS_SHARED_TAG: &str = "shell/islands/main/channel-details/shared";
18 23 const OPEN_LABEL: &str = "Open channel details";
19 24 const CLOSE_LABEL: &str = "Close channel details";
20 25 const PINNED_TITLE: &str = "Pinned";
26 const SHARED_TITLE: &str = "Shared";
27 const SEE_ALL_SHARED_ARIA: &str = "See all shared files";
21 28 const SEE_ALL_LABEL: &str = "See all";
22 29 const SEE_ALL_ARIA: &str = "See all pinned posts";
23 30 const BACK_LABEL: &str = "Back";
@@ -28,6 +35,7 @@ const HEADER_HEIGHT: f32 = 48.;
28 35 const BUTTON_SIZE: f32 = 32.;
29 36 const ITEM_AVATAR: f32 = 24.;
30 37 const COLLAPSED_PIN_COUNT: usize = 3;
38 const SHARED_FILE_COUNT: usize = 3;
31 39
32 40 pub(super) struct PinnedPostItem {
33 41 pub message_id: String,
@@ -67,6 +75,40 @@ pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>)
67 75 }
68 76 }
69 77
78 pub(super) struct SharedFileRow {
79 pub message_id: String,
80 pub name: String,
81 pub kind: FileKind,
82 pub byline: String,
83 }
84
85 pub(super) fn shared_file_rows(items: &[SharedItem]) -> (Vec<SharedFileRow>, bool) {
86 let offset = Local::now().offset().fix();
87 let today = Utc::now().with_timezone(&offset).date_naive();
88 let mut files = items.iter().filter_map(|item| match &item.content {
89 SharedContent::File(card) => Some((item, card)),
90 SharedContent::Link(_) => None,
91 });
92 let rows = files
93 .by_ref()
94 .take(SHARED_FILE_COUNT)
95 .map(|(item, card)| {
96 let date = format::list_time_label(item.created_at, today, offset);
97 SharedFileRow {
98 message_id: item.message_id.clone(),
99 name: card.name.clone(),
100 kind: card.kind,
101 byline: [item.author.as_str(), date.as_str()]
102 .into_iter()
103 .filter(|part| !part.is_empty())
104 .collect::<Vec<_>>()
105 .join(", "),
106 }
107 })
108 .collect();
109 (rows, files.next().is_some())
110 }
111
70 112 pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
71 113 if expanded {
72 114 total
@@ -101,6 +143,11 @@ impl ConversationView {
101 143 .on_click(cx.listener(|this, _, _, cx| {
102 144 this.channel_details_open = !this.channel_details_open;
103 145 this.pinned_posts_expanded = false;
146 if this.channel_details_open {
147 this.find_panel = None;
148 this.find_subscription = None;
149 this.refresh_shared_items(cx);
150 }
104 151 cx.notify();
105 152 }))
106 153 .into_any_element(),
@@ -141,21 +188,18 @@ impl ConversationView {
141 188 .pb(px(PANE_PADDING))
142 189 .gap(px(4.));
143 190 if !items.is_empty() {
191 let mut section = v_flex()
192 .w_full()
193 .gap(px(4.))
194 .debug_selector(|| CHANNEL_DETAILS_PINNED_TAG.into());
144 195 if !expanded {
145 body = body.child(
146 div()
147 .py(px(8.))
148 .text_size(px(14.))
149 .font_weight(FontWeight::SEMIBOLD)
150 .text_color(theme::text())
151 .child(PINNED_TITLE),
152 );
196 section = section.child(section_title(PINNED_TITLE));
153 197 }
154 198 for item in items.iter().take(shown) {
155 body = body.child(self.pinned_post_row(&channel_id, item, directory, cx));
199 section = section.child(self.pinned_post_row(&channel_id, item, directory, cx));
156 200 }
157 201 if has_more {
158 body = body.child(
202 section = section.child(
159 203 Button::new("channel-details-see-all-pins")
160 204 .ghost()
161 205 .label(SEE_ALL_LABEL)
@@ -166,6 +210,30 @@ impl ConversationView {
166 210 })),
167 211 );
168 212 }
213 body = body.child(section);
214 }
215 let (shared_rows, more_shared) = shared_file_rows(&self.shared.items);
216 if !expanded && !shared_rows.is_empty() {
217 let mut section = v_flex()
218 .w_full()
219 .gap(px(4.))
220 .debug_selector(|| CHANNEL_DETAILS_SHARED_TAG.into())
221 .child(section_title(SHARED_TITLE));
222 for row in &shared_rows {
223 section = section.child(self.shared_file_row(&channel_id, row, cx));
224 }
225 if more_shared {
226 section = section.child(
227 Button::new("channel-details-see-all-shared")
228 .ghost()
229 .label(SEE_ALL_LABEL)
230 .tooltip(SEE_ALL_SHARED_ARIA)
231 .on_click(cx.listener(|this, _, _, cx| {
232 this.select_pane(ChannelPane::Shared, cx);
233 })),
234 );
235 }
236 body = body.child(section);
169 237 }
170 238 let header = if expanded {
171 239 h_flex()
@@ -288,6 +356,65 @@ impl ConversationView {
288 356 }
289 357 }
290 358
359 impl ConversationView {
360 fn shared_file_row(
361 &self,
362 channel_id: &str,
363 row: &SharedFileRow,
364 cx: &Context<Self>,
365 ) -> AnyElement {
366 let (channel_id, message_id) = (channel_id.to_owned(), row.message_id.clone());
367 h_flex()
368 .id(SharedString::from(format!(
369 "shared-file-{}-{}",
370 row.message_id, row.name
371 )))
372 .w_full()
373 .p(px(8.))
374 .gap(px(10.))
375 .items_start()
376 .rounded(px(8.))
377 .cursor_pointer()
378 .hover(|item| item.bg(theme::row_hover()))
379 .child(file_badge(row.kind, ITEM_AVATAR))
380 .child(
381 v_flex()
382 .flex_1()
383 .min_w_0()
384 .gap(px(2.))
385 .child(
386 div()
387 .truncate()
388 .text_size(px(13.))
389 .text_color(theme::text())
390 .child(row.name.clone()),
391 )
392 .when(!row.byline.is_empty(), |column| {
393 column.child(
394 div()
395 .truncate()
396 .text_size(px(12.))
397 .text_color(theme::text_muted())
398 .child(row.byline.clone()),
399 )
400 }),
401 )
402 .on_click(cx.listener(move |this, _, _, cx| {
403 this.jump_to_message(&channel_id, &message_id, cx);
404 }))
405 .into_any_element()
406 }
407 }
408
409 fn section_title(text: &'static str) -> Div {
410 div()
411 .py(px(8.))
412 .text_size(px(14.))
413 .font_weight(FontWeight::SEMIBOLD)
414 .text_color(theme::text())
415 .child(text)
416 }
417
291 418 fn header_title(text: String) -> Div {
292 419 div()
293 420 .flex_1()
@@ -304,7 +431,10 @@ mod tests {
304 431 use chrono::{TimeZone, Utc};
305 432 use store::MessageRecord;
306 433
307 use super::{FALLBACK_PREVIEW, pinned_post_item, shown_pin_count};
434 use teams_core::{FileCard, FileKind};
435
436 use super::{FALLBACK_PREVIEW, pinned_post_item, shared_file_rows, shown_pin_count};
437 use crate::channel_files::{SharedContent, SharedItem};
308 438
309 439 fn record(subject: Option<&str>) -> MessageRecord {
310 440 MessageRecord {
@@ -347,4 +477,53 @@ mod tests {
347 477 assert_eq!(shown_pin_count(2, false), 2);
348 478 assert_eq!(shown_pin_count(5, true), 5);
349 479 }
480
481 fn shared(content: SharedContent, message_id: &str) -> SharedItem {
482 SharedItem {
483 content,
484 author: "Ada Lovelace".into(),
485 post_label: String::new(),
486 message_id: message_id.into(),
487 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
488 }
489 }
490
491 fn file(name: &str) -> SharedContent {
492 SharedContent::File(FileCard {
493 name: name.into(),
494 kind: FileKind::from_name(name),
495 content_type: None,
496 size: None,
497 open_url: format!("https://example.invalid/{name}"),
498 })
499 }
500
501 #[test]
502 fn shared_section_lists_the_newest_files_and_skips_links() {
503 let items = vec![
504 shared(SharedContent::Link("https://example.invalid".into()), "1"),
505 shared(file("plan.docx"), "2"),
506 shared(file("budget.xlsx"), "3"),
507 ];
508 let (rows, more) = shared_file_rows(&items);
509 let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
510 assert_eq!(names, ["plan.docx", "budget.xlsx"]);
511 assert!(!more);
512 assert_eq!(rows[0].message_id, "2");
513 assert!(
514 rows[0].byline.starts_with("Ada Lovelace, "),
515 "{}",
516 rows[0].byline
517 );
518 }
519
520 #[test]
521 fn shared_section_offers_see_all_after_three_files() {
522 let items: Vec<SharedItem> = (0..4)
523 .map(|index| shared(file(&format!("file-{index}.pdf")), &index.to_string()))
524 .collect();
525 let (rows, more) = shared_file_rows(&items);
526 assert_eq!(rows.len(), 3);
527 assert!(more);
528 }
350 529 }
@@ -5,19 +5,26 @@ use gpui_kit::component::{h_flex, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7use store::MessageRecord;
7use store::MessageRecord;
8use teams_core::FileKind;
8
9
9use super::ConversationView;
10use super::{ChannelPane, ConversationView};
10use crate::app_state::Selection;
11use crate::app_state::Selection;
12use crate::channel_files::{SharedContent, SharedItem};
11use crate::format;
13use crate::format;
12use crate::rows::reply_excerpt;
14use crate::rows::reply_excerpt;
13use crate::theme;
15use crate::theme;
16use crate::views::attachments::file_badge;
14use crate::views::avatar::person_avatar;
17use crate::views::avatar::person_avatar;
15
18
16pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
19pub const CHANNEL_DETAILS_TAG: &str = "shell/islands/main/channel-details";
17pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
20pub const CHANNEL_DETAILS_BUTTON: &str = "shell/islands/main/channel-details-button";
21pub const CHANNEL_DETAILS_PINNED_TAG: &str = "shell/islands/main/channel-details/pinned";
22pub const CHANNEL_DETAILS_SHARED_TAG: &str = "shell/islands/main/channel-details/shared";
18const OPEN_LABEL: &str = "Open channel details";
23const OPEN_LABEL: &str = "Open channel details";
19const CLOSE_LABEL: &str = "Close channel details";
24const CLOSE_LABEL: &str = "Close channel details";
20const PINNED_TITLE: &str = "Pinned";
25const PINNED_TITLE: &str = "Pinned";
26const SHARED_TITLE: &str = "Shared";
27const SEE_ALL_SHARED_ARIA: &str = "See all shared files";
21const SEE_ALL_LABEL: &str = "See all";
28const SEE_ALL_LABEL: &str = "See all";
22const SEE_ALL_ARIA: &str = "See all pinned posts";
29const SEE_ALL_ARIA: &str = "See all pinned posts";
23const BACK_LABEL: &str = "Back";
30const BACK_LABEL: &str = "Back";
@@ -28,6 +35,7 @@ const HEADER_HEIGHT: f32 = 48.;
28const BUTTON_SIZE: f32 = 32.;
35const BUTTON_SIZE: f32 = 32.;
29const ITEM_AVATAR: f32 = 24.;
36const ITEM_AVATAR: f32 = 24.;
30const COLLAPSED_PIN_COUNT: usize = 3;
37const COLLAPSED_PIN_COUNT: usize = 3;
38const SHARED_FILE_COUNT: usize = 3;
31
39
32pub(super) struct PinnedPostItem {
40pub(super) struct PinnedPostItem {
33 pub message_id: String,
41 pub message_id: String,
@@ -67,6 +75,40 @@ pub(super) fn pinned_post_item(message_id: &str, record: Option<&MessageRecord>)
67 }
75 }
68}
76}
69
77
78pub(super) struct SharedFileRow {
79 pub message_id: String,
80 pub name: String,
81 pub kind: FileKind,
82 pub byline: String,
83}
84
85pub(super) fn shared_file_rows(items: &[SharedItem]) -> (Vec<SharedFileRow>, bool) {
86 let offset = Local::now().offset().fix();
87 let today = Utc::now().with_timezone(&offset).date_naive();
88 let mut files = items.iter().filter_map(|item| match &item.content {
89 SharedContent::File(card) => Some((item, card)),
90 SharedContent::Link(_) => None,
91 });
92 let rows = files
93 .by_ref()
94 .take(SHARED_FILE_COUNT)
95 .map(|(item, card)| {
96 let date = format::list_time_label(item.created_at, today, offset);
97 SharedFileRow {
98 message_id: item.message_id.clone(),
99 name: card.name.clone(),
100 kind: card.kind,
101 byline: [item.author.as_str(), date.as_str()]
102 .into_iter()
103 .filter(|part| !part.is_empty())
104 .collect::<Vec<_>>()
105 .join(", "),
106 }
107 })
108 .collect();
109 (rows, files.next().is_some())
110}
111
70pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
112pub(super) fn shown_pin_count(total: usize, expanded: bool) -> usize {
71 if expanded {
113 if expanded {
72 total
114 total
@@ -101,6 +143,11 @@ impl ConversationView {
101 .on_click(cx.listener(|this, _, _, cx| {
143 .on_click(cx.listener(|this, _, _, cx| {
102 this.channel_details_open = !this.channel_details_open;
144 this.channel_details_open = !this.channel_details_open;
103 this.pinned_posts_expanded = false;
145 this.pinned_posts_expanded = false;
146 if this.channel_details_open {
147 this.find_panel = None;
148 this.find_subscription = None;
149 this.refresh_shared_items(cx);
150 }
104 cx.notify();
151 cx.notify();
105 }))
152 }))
106 .into_any_element(),
153 .into_any_element(),
@@ -141,21 +188,18 @@ impl ConversationView {
141 .pb(px(PANE_PADDING))
188 .pb(px(PANE_PADDING))
142 .gap(px(4.));
189 .gap(px(4.));
143 if !items.is_empty() {
190 if !items.is_empty() {
191 let mut section = v_flex()
192 .w_full()
193 .gap(px(4.))
194 .debug_selector(|| CHANNEL_DETAILS_PINNED_TAG.into());
144 if !expanded {
195 if !expanded {
145 body = body.child(
196 section = section.child(section_title(PINNED_TITLE));
146 div()
147 .py(px(8.))
148 .text_size(px(14.))
149 .font_weight(FontWeight::SEMIBOLD)
150 .text_color(theme::text())
151 .child(PINNED_TITLE),
152 );
153 }
197 }
154 for item in items.iter().take(shown) {
198 for item in items.iter().take(shown) {
155 body = body.child(self.pinned_post_row(&channel_id, item, directory, cx));
199 section = section.child(self.pinned_post_row(&channel_id, item, directory, cx));
156 }
200 }
157 if has_more {
201 if has_more {
158 body = body.child(
202 section = section.child(
159 Button::new("channel-details-see-all-pins")
203 Button::new("channel-details-see-all-pins")
160 .ghost()
204 .ghost()
161 .label(SEE_ALL_LABEL)
205 .label(SEE_ALL_LABEL)
@@ -166,6 +210,30 @@ impl ConversationView {
166 })),
210 })),
167 );
211 );
168 }
212 }
213 body = body.child(section);
214 }
215 let (shared_rows, more_shared) = shared_file_rows(&self.shared.items);
216 if !expanded && !shared_rows.is_empty() {
217 let mut section = v_flex()
218 .w_full()
219 .gap(px(4.))
220 .debug_selector(|| CHANNEL_DETAILS_SHARED_TAG.into())
221 .child(section_title(SHARED_TITLE));
222 for row in &shared_rows {
223 section = section.child(self.shared_file_row(&channel_id, row, cx));
224 }
225 if more_shared {
226 section = section.child(
227 Button::new("channel-details-see-all-shared")
228 .ghost()
229 .label(SEE_ALL_LABEL)
230 .tooltip(SEE_ALL_SHARED_ARIA)
231 .on_click(cx.listener(|this, _, _, cx| {
232 this.select_pane(ChannelPane::Shared, cx);
233 })),
234 );
235 }
236 body = body.child(section);
169 }
237 }
170 let header = if expanded {
238 let header = if expanded {
171 h_flex()
239 h_flex()
@@ -288,6 +356,65 @@ impl ConversationView {
288 }
356 }
289}
357}
290
358
359impl ConversationView {
360 fn shared_file_row(
361 &self,
362 channel_id: &str,
363 row: &SharedFileRow,
364 cx: &Context<Self>,
365 ) -> AnyElement {
366 let (channel_id, message_id) = (channel_id.to_owned(), row.message_id.clone());
367 h_flex()
368 .id(SharedString::from(format!(
369 "shared-file-{}-{}",
370 row.message_id, row.name
371 )))
372 .w_full()
373 .p(px(8.))
374 .gap(px(10.))
375 .items_start()
376 .rounded(px(8.))
377 .cursor_pointer()
378 .hover(|item| item.bg(theme::row_hover()))
379 .child(file_badge(row.kind, ITEM_AVATAR))
380 .child(
381 v_flex()
382 .flex_1()
383 .min_w_0()
384 .gap(px(2.))
385 .child(
386 div()
387 .truncate()
388 .text_size(px(13.))
389 .text_color(theme::text())
390 .child(row.name.clone()),
391 )
392 .when(!row.byline.is_empty(), |column| {
393 column.child(
394 div()
395 .truncate()
396 .text_size(px(12.))
397 .text_color(theme::text_muted())
398 .child(row.byline.clone()),
399 )
400 }),
401 )
402 .on_click(cx.listener(move |this, _, _, cx| {
403 this.jump_to_message(&channel_id, &message_id, cx);
404 }))
405 .into_any_element()
406 }
407}
408
409fn section_title(text: &'static str) -> Div {
410 div()
411 .py(px(8.))
412 .text_size(px(14.))
413 .font_weight(FontWeight::SEMIBOLD)
414 .text_color(theme::text())
415 .child(text)
416}
417
291fn header_title(text: String) -> Div {
418fn header_title(text: String) -> Div {
292 div()
419 div()
293 .flex_1()
420 .flex_1()
@@ -304,7 +431,10 @@ mod tests {
304 use chrono::{TimeZone, Utc};
431 use chrono::{TimeZone, Utc};
305 use store::MessageRecord;
432 use store::MessageRecord;
306
433
307 use super::{FALLBACK_PREVIEW, pinned_post_item, shown_pin_count};
434 use teams_core::{FileCard, FileKind};
435
436 use super::{FALLBACK_PREVIEW, pinned_post_item, shared_file_rows, shown_pin_count};
437 use crate::channel_files::{SharedContent, SharedItem};
308
438
309 fn record(subject: Option<&str>) -> MessageRecord {
439 fn record(subject: Option<&str>) -> MessageRecord {
310 MessageRecord {
440 MessageRecord {
@@ -347,4 +477,53 @@ mod tests {
347 assert_eq!(shown_pin_count(2, false), 2);
477 assert_eq!(shown_pin_count(2, false), 2);
348 assert_eq!(shown_pin_count(5, true), 5);
478 assert_eq!(shown_pin_count(5, true), 5);
349 }
479 }
480
481 fn shared(content: SharedContent, message_id: &str) -> SharedItem {
482 SharedItem {
483 content,
484 author: "Ada Lovelace".into(),
485 post_label: String::new(),
486 message_id: message_id.into(),
487 created_at: Utc.with_ymd_and_hms(2024, 3, 4, 9, 30, 0).unwrap(),
488 }
489 }
490
491 fn file(name: &str) -> SharedContent {
492 SharedContent::File(FileCard {
493 name: name.into(),
494 kind: FileKind::from_name(name),
495 content_type: None,
496 size: None,
497 open_url: format!("https://example.invalid/{name}"),
498 })
499 }
500
501 #[test]
502 fn shared_section_lists_the_newest_files_and_skips_links() {
503 let items = vec![
504 shared(SharedContent::Link("https://example.invalid".into()), "1"),
505 shared(file("plan.docx"), "2"),
506 shared(file("budget.xlsx"), "3"),
507 ];
508 let (rows, more) = shared_file_rows(&items);
509 let names: Vec<&str> = rows.iter().map(|row| row.name.as_str()).collect();
510 assert_eq!(names, ["plan.docx", "budget.xlsx"]);
511 assert!(!more);
512 assert_eq!(rows[0].message_id, "2");
513 assert!(
514 rows[0].byline.starts_with("Ada Lovelace, "),
515 "{}",
516 rows[0].byline
517 );
518 }
519
520 #[test]
521 fn shared_section_offers_see_all_after_three_files() {
522 let items: Vec<SharedItem> = (0..4)
523 .map(|index| shared(file(&format!("file-{index}.pdf")), &index.to_string()))
524 .collect();
525 let (rows, more) = shared_file_rows(&items);
526 assert_eq!(rows.len(), 3);
527 assert!(more);
528 }
350}
529}
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/pins.rs +53 −3
@@ -5,7 +5,12 @@ use gpui_kit::*;
5 5 use store::MessageRecord;
6 6
7 7 use super::ConversationView;
8 use crate::app_state::Selection;
8 use gpui_kit::component::WindowExt as _;
9 use gpui_kit::component::button::{Button, ButtonVariants as _};
10 use gpui_kit::component::dialog::DialogFooter;
11
12 use crate::app_state::{AppState, Selection};
13 use crate::channel_menu::post_pin_dialog;
9 14 use crate::rows::reply_excerpt;
10 15 use crate::runtime;
11 16 use crate::views::message_actions::Action;
@@ -25,6 +30,40 @@ impl PinPreview {
25 30 }
26 31 }
27 32
33 fn confirm_post_pin(
34 state: &Entity<AppState>,
35 channel_id: &str,
36 message_id: &str,
37 pin: bool,
38 window: &mut Window,
39 cx: &mut App,
40 ) {
41 let dialog = post_pin_dialog(pin);
42 let (state, channel_id, message_id) =
43 (state.clone(), channel_id.to_owned(), message_id.to_owned());
44 window.open_alert_dialog(cx, move |alert, _, _| {
45 let (state, channel_id, message_id) =
46 (state.clone(), channel_id.clone(), message_id.clone());
47 let cancel = Button::new("post-pin-cancel")
48 .label("Cancel")
49 .on_click(|_, window, cx| window.close_dialog(cx));
50 let confirm = Button::new("post-pin-confirm")
51 .label(dialog.confirm)
52 .primary()
53 .on_click(move |_, window, cx| {
54 state.update(cx, |state, cx| {
55 state.set_pinned(&channel_id, &message_id, pin, cx)
56 });
57 window.close_dialog(cx);
58 });
59 alert
60 .title(dialog.title)
61 .description(dialog.body)
62 .footer(DialogFooter::new().child(cancel).child(confirm))
63 .on_ok(|_, _, _| false)
64 });
65 }
66
28 67 impl ConversationView {
29 68 pub(super) fn chat_id(&self) -> Option<String> {
30 69 match self.current.as_ref()?.selection {
@@ -222,12 +261,23 @@ impl ConversationView {
222 261 }
223 262 }
224 263
225 pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
226 if let Some(conversation_id) = self.pin_conversation_id() {
264 pub(super) fn toggle_pinned(
265 &mut self,
266 message_id: &str,
267 window: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 let Some(conversation_id) = self.pin_conversation_id() else {
271 return;
272 };
273 if self.chat_id().is_some() {
227 274 self.app.update(cx, |state, cx| {
228 275 state.toggle_pinned(&conversation_id, message_id, cx)
229 276 });
277 return;
230 278 }
279 let pin = !self.app.read(cx).is_pinned(&conversation_id, message_id);
280 confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
231 281 }
232 282
233 283 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
@@ -5,7 +5,12 @@ use gpui_kit::*;
5use store::MessageRecord;
5use store::MessageRecord;
6
6
7use super::ConversationView;
7use super::ConversationView;
8use crate::app_state::Selection;
8use gpui_kit::component::WindowExt as _;
9use gpui_kit::component::button::{Button, ButtonVariants as _};
10use gpui_kit::component::dialog::DialogFooter;
11
12use crate::app_state::{AppState, Selection};
13use crate::channel_menu::post_pin_dialog;
9use crate::rows::reply_excerpt;
14use crate::rows::reply_excerpt;
10use crate::runtime;
15use crate::runtime;
11use crate::views::message_actions::Action;
16use crate::views::message_actions::Action;
@@ -25,6 +30,40 @@ impl PinPreview {
25 }
30 }
26}
31}
27
32
33fn confirm_post_pin(
34 state: &Entity<AppState>,
35 channel_id: &str,
36 message_id: &str,
37 pin: bool,
38 window: &mut Window,
39 cx: &mut App,
40) {
41 let dialog = post_pin_dialog(pin);
42 let (state, channel_id, message_id) =
43 (state.clone(), channel_id.to_owned(), message_id.to_owned());
44 window.open_alert_dialog(cx, move |alert, _, _| {
45 let (state, channel_id, message_id) =
46 (state.clone(), channel_id.clone(), message_id.clone());
47 let cancel = Button::new("post-pin-cancel")
48 .label("Cancel")
49 .on_click(|_, window, cx| window.close_dialog(cx));
50 let confirm = Button::new("post-pin-confirm")
51 .label(dialog.confirm)
52 .primary()
53 .on_click(move |_, window, cx| {
54 state.update(cx, |state, cx| {
55 state.set_pinned(&channel_id, &message_id, pin, cx)
56 });
57 window.close_dialog(cx);
58 });
59 alert
60 .title(dialog.title)
61 .description(dialog.body)
62 .footer(DialogFooter::new().child(cancel).child(confirm))
63 .on_ok(|_, _, _| false)
64 });
65}
66
28impl ConversationView {
67impl ConversationView {
29 pub(super) fn chat_id(&self) -> Option<String> {
68 pub(super) fn chat_id(&self) -> Option<String> {
30 match self.current.as_ref()?.selection {
69 match self.current.as_ref()?.selection {
@@ -222,12 +261,23 @@ impl ConversationView {
222 }
261 }
223 }
262 }
224
263
225 pub(super) fn toggle_pinned(&mut self, message_id: &str, cx: &mut Context<Self>) {
264 pub(super) fn toggle_pinned(
226 if let Some(conversation_id) = self.pin_conversation_id() {
265 &mut self,
266 message_id: &str,
267 window: &mut Window,
268 cx: &mut Context<Self>,
269 ) {
270 let Some(conversation_id) = self.pin_conversation_id() else {
271 return;
272 };
273 if self.chat_id().is_some() {
227 self.app.update(cx, |state, cx| {
274 self.app.update(cx, |state, cx| {
228 state.toggle_pinned(&conversation_id, message_id, cx)
275 state.toggle_pinned(&conversation_id, message_id, cx)
229 });
276 });
277 return;
230 }
278 }
279 let pin = !self.app.read(cx).is_pinned(&conversation_id, message_id);
280 confirm_post_pin(&self.app, &conversation_id, message_id, pin, window, cx);
231 }
281 }
232
282
233 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
283 pub(super) fn mark_unread_from(&mut self, message_id: &str, cx: &mut Context<Self>) {
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/conversation/shared.rs +3 −0
@@ -77,6 +77,9 @@ impl ConversationView {
77 77 generation: self.shared.generation + 1,
78 78 ..SharedState::default()
79 79 };
80 if self.channel_details_open {
81 self.refresh_shared_items(cx);
82 }
80 83 self.reload_channel_tabs(cx);
81 84 }
82 85
@@ -77,6 +77,9 @@ impl ConversationView {
77 generation: self.shared.generation + 1,
77 generation: self.shared.generation + 1,
78 ..SharedState::default()
78 ..SharedState::default()
79 };
79 };
80 if self.channel_details_open {
81 self.refresh_shared_items(cx);
82 }
80 self.reload_channel_tabs(cx);
83 self.reload_channel_tabs(cx);
81 }
84 }
82
85
crates/app/src/views/customize_reactions.rs added +263 −0
@@ -0,0 +1,263 @@
1 use std::collections::HashSet;
2 use std::rc::Rc;
3
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 use gpui_kit::component::dialog::{Dialog, DialogFooter};
7 use gpui_kit::component::popover::Popover;
8 use gpui_kit::component::tooltip::Tooltip;
9 use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
10 use gpui_kit::prelude::FluentBuilder as _;
11 use gpui_kit::*;
12
13 use super::reaction_picker::ReactionPicker;
14 use super::widgets::{Corner, corner_badge, icon};
15 use crate::app_state::AppState;
16 use crate::default_reactions::{
17 filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
18 };
19 use crate::emoji;
20 use crate::emoticons::{SKIN_TONE_COUNT, with_tone};
21 use crate::theme;
22
23 pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";
24 const TITLE: &str = "Customise your reactions and appearance in Teams";
25 const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";
26 const SKIN_TONE_TEXT: &str =
27 "Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";
28 const CHOOSE_EMOJI: &str = "Choose an emoji";
29 const REMOVE_REACTION: &str = "Remove reaction";
30 const TONE_SAMPLE: &str = "\u{1F44D}";
31 const DIALOG_WIDTH: f32 = 440.;
32 const SLOT_SIZE: f32 = 48.;
33 const SLOT_GLYPH_SIZE: f32 = 26.;
34 const TONE_SIZE: f32 = 36.;
35 const TONE_GLYPH_SIZE: f32 = 20.;
36 const REMOVE_SIZE: f32 = 18.;
37 const REMOVE_OVERHANG: f32 = 5.;
38 const SECTION_GAP: f32 = 16.;
39 const TEXT_SIZE: f32 = 13.;
40
41 struct CustomizeForm {
42 state: Entity<AppState>,
43 picker: Entity<ReactionPicker>,
44 saved_ids: Vec<String>,
45 saved_tone: u8,
46 slots: Vec<Option<String>>,
47 skin_tone: u8,
48 }
49
50 impl CustomizeForm {
51 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
52 let (saved_ids, saved_tone, store) = {
53 let app = state.read(cx);
54 (
55 app.default_reactions(),
56 teams_core::skin_tone(&app.store),
57 app.store.clone(),
58 )
59 };
60 let recent = cx.new(|_| emoji::Recent::load(&store));
61 let picker_state = state.clone();
62 let picker =
63 cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());
64 CustomizeForm {
65 state,
66 picker,
67 slots: slots_for(&saved_ids),
68 saved_ids,
69 saved_tone,
70 skin_tone: saved_tone,
71 }
72 }
73
74 fn unchanged(&self) -> bool {
75 filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone
76 }
77
78 fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {
79 if let Some(reaction_id) = reaction_id_for_glyph(glyph) {
80 place_in_slot(&mut self.slots, index, reaction_id);
81 cx.notify();
82 }
83 }
84
85 fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
86 if let Some(slot) = self.slots.get_mut(index) {
87 *slot = None;
88 cx.notify();
89 }
90 }
91
92 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
93 let reaction_ids = filled(&self.slots);
94 let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);
95 self.state.update(cx, |state, cx| {
96 if tone_changed {
97 state.set_skin_tone(tone, cx);
98 }
99 state.set_default_reactions(reaction_ids, cx);
100 });
101 window.close_dialog(cx);
102 }
103
104 fn slot_glyph(&self, reaction_id: &str) -> Option<String> {
105 quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)
106 .into_iter()
107 .next()
108 }
109
110 fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
111 let glyph = self
112 .slots
113 .get(index)
114 .cloned()
115 .flatten()
116 .and_then(|reaction_id| self.slot_glyph(&reaction_id));
117 let label = if glyph.is_some() {
118 REMOVE_REACTION
119 } else {
120 CHOOSE_EMOJI
121 };
122 let trigger = Button::new(("customize-reaction-slot", index))
123 .size(px(SLOT_SIZE))
124 .rounded(px(10.))
125 .tooltip(label)
126 .map(|button| match &glyph {
127 Some(glyph) => {
128 button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
129 }
130 None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131 });
132 let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
133 let selected: HashSet<String> = glyph.iter().cloned().collect();
134 let popover = Popover::new(("customize-reaction-picker", index))
135 .anchor(Anchor::TopLeft)
136 .trigger(trigger)
137 .on_open_change({
138 let picker = self.picker.clone();
139 move |open, window, cx| {
140 if *open {
141 picker.update(cx, |picker, cx| picker.reset(window, cx));
142 }
143 }
144 })
145 .content(move |_, _, cx| {
146 let popover = cx.entity().downgrade();
147 let view = view.clone();
148 picker.update(cx, |picker, _| {
149 picker.set_target(
150 Rc::new(move |glyph, _, cx| {
151 view.update(cx, |form, cx| form.place(index, glyph, cx))
152 .ok();
153 }),
154 Rc::new(|_, _| {}),
155 popover,
156 selected.clone(),
157 )
158 });
159 picker.clone()
160 });
161 let remove = glyph.is_some().then(|| {
162 corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(
163 div()
164 .id(("customize-reaction-remove", index))
165 .size(px(REMOVE_SIZE))
166 .flex()
167 .items_center()
168 .justify_center()
169 .rounded_full()
170 .cursor_pointer()
171 .bg(theme::popup_hover())
172 .hover(|button| button.bg(theme::row_hover()))
173 .child(icon(IconName::X, 10., theme::text_soft()))
174 .tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))
175 .on_click(cx.listener(move |form, _, _, cx| {
176 cx.stop_propagation();
177 form.remove(index, cx);
178 })),
179 )
180 });
181 div()
182 .relative()
183 .child(popover)
184 .children(remove)
185 .into_any_element()
186 }
187
188 fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {
189 let selected = tone == self.skin_tone;
190 div()
191 .id(("customize-skin-tone", usize::from(tone)))
192 .size(px(TONE_SIZE))
193 .flex()
194 .items_center()
195 .justify_center()
196 .rounded_full()
197 .cursor_pointer()
198 .text_size(px(TONE_GLYPH_SIZE))
199 .when(selected, |choice| choice.bg(theme::reaction_on_own()))
200 .when(!selected, |choice| {
201 choice.hover(|choice| choice.bg(theme::popup_hover()))
202 })
203 .child(with_tone(TONE_SAMPLE, tone))
204 .on_click(cx.listener(move |form, _, _, cx| {
205 form.skin_tone = tone;
206 cx.notify();
207 }))
208 .into_any_element()
209 }
210 }
211
212 impl Render for CustomizeForm {
213 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214 let slots: Vec<AnyElement> = (0..self.slots.len())
215 .map(|index| self.slot(index, cx))
216 .collect();
217 let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)
218 .map(|tone| self.tone_choice(tone, cx))
219 .collect();
220 v_flex()
221 .gap(px(SECTION_GAP))
222 .text_size(px(TEXT_SIZE))
223 .text_color(theme::text())
224 .child(div().text_color(theme::text_soft()).child(DESCRIPTION))
225 .child(
226 h_flex()
227 .justify_center()
228 .gap(px(10.))
229 .py(px(4.))
230 .children(slots),
231 )
232 .child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))
233 .child(h_flex().gap(px(6.)).children(tones))
234 }
235 }
236
237 pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
238 let form = cx.new(|cx| CustomizeForm::new(state, window, cx));
239 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240 let submit_form = form.clone();
241 let unchanged = form.read(cx).unchanged();
242 let footer = DialogFooter::new()
243 .child(
244 Button::new("customize-reactions-cancel")
245 .label("Cancel")
246 .on_click(|_, window, cx| window.close_dialog(cx)),
247 )
248 .child(
249 Button::new("customize-reactions-save")
250 .primary()
251 .label("Save")
252 .disabled(unchanged)
253 .on_click(move |_, window, cx| {
254 submit_form.update(cx, |form, cx| form.save(window, cx));
255 }),
256 );
257 dialog
258 .title(TITLE)
259 .w(px(DIALOG_WIDTH))
260 .child(form.clone())
261 .footer(footer)
262 });
263 }
@@ -0,0 +1,263 @@
1use std::collections::HashSet;
2use std::rc::Rc;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::dialog::{Dialog, DialogFooter};
7use gpui_kit::component::popover::Popover;
8use gpui_kit::component::tooltip::Tooltip;
9use gpui_kit::component::{Disableable as _, WindowExt as _, h_flex, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12
13use super::reaction_picker::ReactionPicker;
14use super::widgets::{Corner, corner_badge, icon};
15use crate::app_state::AppState;
16use crate::default_reactions::{
17 filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
18};
19use crate::emoji;
20use crate::emoticons::{SKIN_TONE_COUNT, with_tone};
21use crate::theme;
22
23pub const CUSTOMIZE_TOOLTIP: &str = "Customise default reactions";
24const TITLE: &str = "Customise your reactions and appearance in Teams";
25const DESCRIPTION: &str = "Click on a reaction below, then choose an emoji to replace it with.";
26const SKIN_TONE_TEXT: &str =
27 "Choose a skin tone. After selection, reactions and emoji will appear with this skin tone.";
28const CHOOSE_EMOJI: &str = "Choose an emoji";
29const REMOVE_REACTION: &str = "Remove reaction";
30const TONE_SAMPLE: &str = "\u{1F44D}";
31const DIALOG_WIDTH: f32 = 440.;
32const SLOT_SIZE: f32 = 48.;
33const SLOT_GLYPH_SIZE: f32 = 26.;
34const TONE_SIZE: f32 = 36.;
35const TONE_GLYPH_SIZE: f32 = 20.;
36const REMOVE_SIZE: f32 = 18.;
37const REMOVE_OVERHANG: f32 = 5.;
38const SECTION_GAP: f32 = 16.;
39const TEXT_SIZE: f32 = 13.;
40
41struct CustomizeForm {
42 state: Entity<AppState>,
43 picker: Entity<ReactionPicker>,
44 saved_ids: Vec<String>,
45 saved_tone: u8,
46 slots: Vec<Option<String>>,
47 skin_tone: u8,
48}
49
50impl CustomizeForm {
51 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
52 let (saved_ids, saved_tone, store) = {
53 let app = state.read(cx);
54 (
55 app.default_reactions(),
56 teams_core::skin_tone(&app.store),
57 app.store.clone(),
58 )
59 };
60 let recent = cx.new(|_| emoji::Recent::load(&store));
61 let picker_state = state.clone();
62 let picker =
63 cx.new(|cx| ReactionPicker::new(picker_state, recent, window, cx).for_customizing());
64 CustomizeForm {
65 state,
66 picker,
67 slots: slots_for(&saved_ids),
68 saved_ids,
69 saved_tone,
70 skin_tone: saved_tone,
71 }
72 }
73
74 fn unchanged(&self) -> bool {
75 filled(&self.slots) == self.saved_ids && self.skin_tone == self.saved_tone
76 }
77
78 fn place(&mut self, index: usize, glyph: &str, cx: &mut Context<Self>) {
79 if let Some(reaction_id) = reaction_id_for_glyph(glyph) {
80 place_in_slot(&mut self.slots, index, reaction_id);
81 cx.notify();
82 }
83 }
84
85 fn remove(&mut self, index: usize, cx: &mut Context<Self>) {
86 if let Some(slot) = self.slots.get_mut(index) {
87 *slot = None;
88 cx.notify();
89 }
90 }
91
92 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
93 let reaction_ids = filled(&self.slots);
94 let (tone_changed, tone) = (self.skin_tone != self.saved_tone, self.skin_tone);
95 self.state.update(cx, |state, cx| {
96 if tone_changed {
97 state.set_skin_tone(tone, cx);
98 }
99 state.set_default_reactions(reaction_ids, cx);
100 });
101 window.close_dialog(cx);
102 }
103
104 fn slot_glyph(&self, reaction_id: &str) -> Option<String> {
105 quick_reaction_glyphs(&[reaction_id.to_owned()], self.skin_tone)
106 .into_iter()
107 .next()
108 }
109
110 fn slot(&self, index: usize, cx: &mut Context<Self>) -> AnyElement {
111 let glyph = self
112 .slots
113 .get(index)
114 .cloned()
115 .flatten()
116 .and_then(|reaction_id| self.slot_glyph(&reaction_id));
117 let label = if glyph.is_some() {
118 REMOVE_REACTION
119 } else {
120 CHOOSE_EMOJI
121 };
122 let trigger = Button::new(("customize-reaction-slot", index))
123 .size(px(SLOT_SIZE))
124 .rounded(px(10.))
125 .tooltip(label)
126 .map(|button| match &glyph {
127 Some(glyph) => {
128 button.child(div().text_size(px(SLOT_GLYPH_SIZE)).child(glyph.clone()))
129 }
130 None => button.child(icon(IconName::Plus, 18., theme::text_muted())),
131 });
132 let (picker, view) = (self.picker.clone(), cx.entity().downgrade());
133 let selected: HashSet<String> = glyph.iter().cloned().collect();
134 let popover = Popover::new(("customize-reaction-picker", index))
135 .anchor(Anchor::TopLeft)
136 .trigger(trigger)
137 .on_open_change({
138 let picker = self.picker.clone();
139 move |open, window, cx| {
140 if *open {
141 picker.update(cx, |picker, cx| picker.reset(window, cx));
142 }
143 }
144 })
145 .content(move |_, _, cx| {
146 let popover = cx.entity().downgrade();
147 let view = view.clone();
148 picker.update(cx, |picker, _| {
149 picker.set_target(
150 Rc::new(move |glyph, _, cx| {
151 view.update(cx, |form, cx| form.place(index, glyph, cx))
152 .ok();
153 }),
154 Rc::new(|_, _| {}),
155 popover,
156 selected.clone(),
157 )
158 });
159 picker.clone()
160 });
161 let remove = glyph.is_some().then(|| {
162 corner_badge(Corner::TopRight, REMOVE_OVERHANG).child(
163 div()
164 .id(("customize-reaction-remove", index))
165 .size(px(REMOVE_SIZE))
166 .flex()
167 .items_center()
168 .justify_center()
169 .rounded_full()
170 .cursor_pointer()
171 .bg(theme::popup_hover())
172 .hover(|button| button.bg(theme::row_hover()))
173 .child(icon(IconName::X, 10., theme::text_soft()))
174 .tooltip(|window, cx| Tooltip::new(REMOVE_REACTION).build(window, cx))
175 .on_click(cx.listener(move |form, _, _, cx| {
176 cx.stop_propagation();
177 form.remove(index, cx);
178 })),
179 )
180 });
181 div()
182 .relative()
183 .child(popover)
184 .children(remove)
185 .into_any_element()
186 }
187
188 fn tone_choice(&self, tone: u8, cx: &mut Context<Self>) -> AnyElement {
189 let selected = tone == self.skin_tone;
190 div()
191 .id(("customize-skin-tone", usize::from(tone)))
192 .size(px(TONE_SIZE))
193 .flex()
194 .items_center()
195 .justify_center()
196 .rounded_full()
197 .cursor_pointer()
198 .text_size(px(TONE_GLYPH_SIZE))
199 .when(selected, |choice| choice.bg(theme::reaction_on_own()))
200 .when(!selected, |choice| {
201 choice.hover(|choice| choice.bg(theme::popup_hover()))
202 })
203 .child(with_tone(TONE_SAMPLE, tone))
204 .on_click(cx.listener(move |form, _, _, cx| {
205 form.skin_tone = tone;
206 cx.notify();
207 }))
208 .into_any_element()
209 }
210}
211
212impl Render for CustomizeForm {
213 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
214 let slots: Vec<AnyElement> = (0..self.slots.len())
215 .map(|index| self.slot(index, cx))
216 .collect();
217 let tones: Vec<AnyElement> = (0..=SKIN_TONE_COUNT)
218 .map(|tone| self.tone_choice(tone, cx))
219 .collect();
220 v_flex()
221 .gap(px(SECTION_GAP))
222 .text_size(px(TEXT_SIZE))
223 .text_color(theme::text())
224 .child(div().text_color(theme::text_soft()).child(DESCRIPTION))
225 .child(
226 h_flex()
227 .justify_center()
228 .gap(px(10.))
229 .py(px(4.))
230 .children(slots),
231 )
232 .child(div().text_color(theme::text_soft()).child(SKIN_TONE_TEXT))
233 .child(h_flex().gap(px(6.)).children(tones))
234 }
235}
236
237pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
238 let form = cx.new(|cx| CustomizeForm::new(state, window, cx));
239 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
240 let submit_form = form.clone();
241 let unchanged = form.read(cx).unchanged();
242 let footer = DialogFooter::new()
243 .child(
244 Button::new("customize-reactions-cancel")
245 .label("Cancel")
246 .on_click(|_, window, cx| window.close_dialog(cx)),
247 )
248 .child(
249 Button::new("customize-reactions-save")
250 .primary()
251 .label("Save")
252 .disabled(unchanged)
253 .on_click(move |_, window, cx| {
254 submit_form.update(cx, |form, cx| form.save(window, cx));
255 }),
256 );
257 dialog
258 .title(TITLE)
259 .w(px(DIALOG_WIDTH))
260 .child(form.clone())
261 .footer(footer)
262 });
263}
crates/app/src/views/find_panel.rs added +664 −0
@@ -0,0 +1,664 @@
1 use std::time::Duration;
2
3 use chrono::{Local, NaiveDate, Offset};
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
7 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9 use gpui_kit::prelude::FluentBuilder as _;
10 use gpui_kit::*;
11 use store::Store;
12 use teams_core::substrate_search::{QueryRequest, QueryResults, QueryScope, SearchSession};
13
14 use super::widgets::icon;
15 use crate::app_state::{AppState, Selection};
16 use crate::find_in_chat::{
17 DATE_LABEL, DateRange, EMPTY_HINT, FIND_IN_CHANNEL, FIND_IN_CHAT, FROM_LABEL, FindFilters,
18 FindHit, HAS_ATTACHMENT_LABEL, LOAD_ERROR, LOADING, MENTIONS_LABEL, NO_RESULTS_CHANNEL,
19 NO_RESULTS_CHAT, Sender, from_local, from_record, from_server, group_by_month, merge,
20 no_results_with_filters, same_user, step_index,
21 };
22 use crate::format;
23 use crate::runtime;
24 use crate::theme;
25
26 pub const FIND_PANEL_TAG: &str = "shell/islands/main/find";
27 pub const FIND_DIVIDER_TAG: &str = "shell/islands/main/find/divider-side";
28 pub const FIND_INPUT_TAG: &str = "shell/islands/main/find/input";
29 pub const FIND_RESULTS_TAG: &str = "shell/islands/main/find/results";
30 pub const FIND_PANEL_WIDTH: f32 = 320.;
31 const HEADER_HEIGHT: f32 = 48.;
32 const SIDE_INSET: f32 = 16.;
33 const INPUT_HEIGHT: f32 = 32.;
34 const CHIP_HEIGHT: f32 = 24.;
35 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
36 const LOCAL_LIMIT: usize = 100;
37 const FILTER_SCAN_LIMIT: usize = 500;
38 const SENDER_SCAN_LIMIT: usize = 200;
39
40 pub enum FindPanelEvent {
41 Close,
42 Jump(String),
43 }
44
45 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
46 enum Status {
47 Idle,
48 Loading,
49 Ready,
50 Failed,
51 }
52
53 pub struct FindPanel {
54 app: Entity<AppState>,
55 selection: Selection,
56 input: Entity<InputState>,
57 query: String,
58 filters: FindFilters,
59 senders: Vec<Sender>,
60 local_hits: Vec<FindHit>,
61 hits: Vec<FindHit>,
62 status: Status,
63 generation: u64,
64 current_index: Option<usize>,
65 search_session: SearchSession,
66 scroll: ScrollHandle,
67 _subscription: Subscription,
68 }
69
70 impl EventEmitter<FindPanelEvent> for FindPanel {}
71
72 impl FindPanel {
73 pub fn new(
74 app: Entity<AppState>,
75 selection: Selection,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 let title = panel_title(&selection);
80 let input = cx.new(|cx| InputState::new(window, cx).placeholder(title));
81 let subscription = cx.subscribe_in(&input, window, Self::on_input);
82 let senders = senders_of(app.read(cx), selection.conversation_id());
83 FindPanel {
84 app,
85 selection,
86 input,
87 query: String::new(),
88 filters: FindFilters::default(),
89 senders,
90 local_hits: Vec::new(),
91 hits: Vec::new(),
92 status: Status::Idle,
93 generation: 0,
94 current_index: None,
95 search_session: SearchSession::new(),
96 scroll: ScrollHandle::new(),
97 _subscription: subscription,
98 }
99 }
100
101 pub fn selection(&self) -> &Selection {
102 &self.selection
103 }
104
105 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
106 self.input.update(cx, |input, cx| input.focus(window, cx));
107 }
108
109 fn on_input(
110 &mut self,
111 input: &Entity<InputState>,
112 event: &InputEvent,
113 _: &mut Window,
114 cx: &mut Context<Self>,
115 ) {
116 match event {
117 InputEvent::Change => {
118 self.query = input.read(cx).value().trim().to_owned();
119 self.schedule_search(cx);
120 }
121 InputEvent::PressEnter { shift, .. } => self.step(*shift, cx),
122 _ => {}
123 }
124 }
125
126 fn step(&mut self, backwards: bool, cx: &mut Context<Self>) {
127 if let Some(index) = step_index(self.current_index, self.hits.len(), backwards) {
128 self.pick(index, cx);
129 }
130 }
131
132 fn pick(&mut self, index: usize, cx: &mut Context<Self>) {
133 let Some(hit) = self.hits.get(index) else {
134 return;
135 };
136 self.current_index = Some(index);
137 self.scroll.scroll_to_item(index);
138 cx.emit(FindPanelEvent::Jump(hit.message_id.clone()));
139 cx.notify();
140 }
141
142 fn update_filters(&mut self, change: impl FnOnce(&mut FindFilters), cx: &mut Context<Self>) {
143 change(&mut self.filters);
144 self.schedule_search(cx);
145 cx.notify();
146 }
147
148 fn schedule_search(&mut self, cx: &mut Context<Self>) {
149 self.generation += 1;
150 let generation = self.generation;
151 cx.spawn(async move |this, cx| {
152 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
153 this.update(cx, |panel, cx| {
154 if panel.generation == generation {
155 panel.run_search(cx);
156 }
157 })
158 .ok();
159 })
160 .detach();
161 }
162
163 fn run_search(&mut self, cx: &mut Context<Self>) {
164 self.current_index = None;
165 if self.query.is_empty() && !self.filters.is_active() {
166 self.local_hits.clear();
167 self.hits.clear();
168 self.status = Status::Idle;
169 cx.notify();
170 return;
171 }
172 let (store, engine, my_id) = {
173 let state = self.app.read(cx);
174 (
175 state.store.clone(),
176 state.engine.clone(),
177 state.directory.me.as_ref().map(|me| me.user_id.clone()),
178 )
179 };
180 let (today, offset) = today_and_offset();
181 let conversation_id = self.selection.conversation_id().to_owned();
182 let local: Vec<FindHit> =
183 local_hits(&store, &conversation_id, &self.query, my_id.as_deref())
184 .into_iter()
185 .filter(|hit| self.filters.admits(hit, today, offset))
186 .collect();
187 self.local_hits = local;
188 self.hits = merge(self.local_hits.clone(), Vec::new());
189 let server_engine = engine.filter(|_| matches!(self.selection, Selection::Chat(_)));
190 let Some(engine) = server_engine else {
191 self.status = Status::Ready;
192 cx.notify();
193 return;
194 };
195 self.status = Status::Loading;
196 let request = QueryRequest::new(self.query.clone(), QueryScope::Messages)
197 .with_filters(self.filters.server_filters(&conversation_id));
198 let search_session = self.search_session.clone();
199 let generation = self.generation;
200 let receiver =
201 runtime::spawn(async move { engine.server_query(&search_session, &request).await });
202 cx.spawn(async move |this, cx| {
203 let results = match receiver.await {
204 Ok(Ok(results)) => Some(results),
205 _ => None,
206 };
207 this.update(cx, |panel, cx| panel.apply_server(generation, results, cx))
208 .ok();
209 })
210 .detach();
211 cx.notify();
212 }
213
214 fn apply_server(
215 &mut self,
216 generation: u64,
217 results: Option<QueryResults>,
218 cx: &mut Context<Self>,
219 ) {
220 if generation != self.generation {
221 return;
222 }
223 let Some(results) = results else {
224 self.status = if self.hits.is_empty() {
225 Status::Failed
226 } else {
227 Status::Ready
228 };
229 cx.notify();
230 return;
231 };
232 let (today, offset) = today_and_offset();
233 let conversation_id = self.selection.conversation_id();
234 let server: Vec<FindHit> = results
235 .messages
236 .items
237 .iter()
238 .filter(|message| message.conversation_id == conversation_id)
239 .filter_map(from_server)
240 .filter(|hit| self.filters.admits(hit, today, offset))
241 .collect();
242 self.hits = merge(self.local_hits.clone(), server);
243 self.status = Status::Ready;
244 cx.notify();
245 }
246
247 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
248 h_flex()
249 .h(px(HEADER_HEIGHT))
250 .flex_none()
251 .pl(px(SIDE_INSET))
252 .pr(px(12.))
253 .items_center()
254 .justify_between()
255 .child(
256 div()
257 .text_size(px(15.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .child(panel_title(&self.selection)),
260 )
261 .child(
262 div()
263 .id("find-close")
264 .size(px(28.))
265 .flex()
266 .items_center()
267 .justify_center()
268 .rounded(px(7.))
269 .cursor_pointer()
270 .hover(|button| button.bg(theme::row_hover()))
271 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
272 .child(icon(IconName::Close, 14., theme::text_muted()))
273 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
274 )
275 }
276
277 fn search_row(&self) -> impl IntoElement {
278 h_flex()
279 .debug_selector(|| FIND_INPUT_TAG.into())
280 .mx(px(SIDE_INSET))
281 .h(px(INPUT_HEIGHT))
282 .flex_none()
283 .px(px(10.))
284 .gap(px(8.))
285 .items_center()
286 .rounded(px(6.))
287 .bg(theme::surface_raised())
288 .child(icon(IconName::Search, 14., theme::text_muted()))
289 .child(
290 div()
291 .flex_1()
292 .min_w_0()
293 .child(Input::new(&self.input).appearance(false).bordered(false)),
294 )
295 }
296
297 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
298 let panel = cx.weak_entity();
299 h_flex()
300 .px(px(SIDE_INSET))
301 .pt(px(8.))
302 .flex_none()
303 .flex_wrap()
304 .gap(px(6.))
305 .child(self.from_chip(panel.clone()))
306 .child(self.date_chip(panel))
307 .child(self.toggle_chip(
308 "find-has-attachment",
309 HAS_ATTACHMENT_LABEL,
310 self.filters.has_attachment,
311 |filters| filters.has_attachment = !filters.has_attachment,
312 cx,
313 ))
314 .child(self.toggle_chip(
315 "find-mentions",
316 MENTIONS_LABEL,
317 self.filters.mentions_me,
318 |filters| filters.mentions_me = !filters.mentions_me,
319 cx,
320 ))
321 }
322
323 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
324 let selected = self.filters.from.clone();
325 let label = selected
326 .as_ref()
327 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
328 let senders = self.senders.clone();
329 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
330 senders.iter().fold(menu, |menu, sender| {
331 let checked = selected
332 .as_ref()
333 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
334 let (panel, sender) = (panel.clone(), sender.clone());
335 menu.item(
336 PopupMenuItem::new(sender.name.clone())
337 .checked(checked)
338 .on_click(move |_, _, cx| {
339 let pick = (!checked).then(|| sender.clone());
340 panel
341 .update(cx, |panel, cx| {
342 panel.update_filters(|filters| filters.from = pick, cx)
343 })
344 .ok();
345 }),
346 )
347 })
348 })
349 }
350
351 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
352 let selected = self.filters.date;
353 let label = selected.map_or(DATE_LABEL, DateRange::label);
354 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
355 move |menu, _, _| {
356 DateRange::ALL.into_iter().fold(menu, |menu, range| {
357 let checked = selected == Some(range);
358 let panel = panel.clone();
359 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
360 move |_, _, cx| {
361 let pick = (!checked).then_some(range);
362 panel
363 .update(cx, |panel, cx| {
364 panel.update_filters(|filters| filters.date = pick, cx)
365 })
366 .ok();
367 },
368 ))
369 })
370 },
371 )
372 }
373
374 fn toggle_chip(
375 &self,
376 id: &'static str,
377 label: &'static str,
378 selected: bool,
379 change: fn(&mut FindFilters),
380 cx: &mut Context<Self>,
381 ) -> impl IntoElement {
382 div()
383 .id(id)
384 .h(px(CHIP_HEIGHT))
385 .px(px(12.))
386 .flex()
387 .flex_none()
388 .items_center()
389 .rounded_full()
390 .cursor_pointer()
391 .text_size(px(12.))
392 .when(selected, |chip| {
393 chip.bg(theme::accent()).text_color(theme::on_accent())
394 })
395 .when(!selected, |chip| {
396 chip.bg(theme::surface_raised())
397 .text_color(theme::text_soft())
398 .hover(|chip| chip.bg(theme::border_strong()))
399 })
400 .child(label)
401 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
402 }
403
404 fn message_line(&self) -> Option<String> {
405 let no_results = || {
406 if self.filters.is_active() && !self.query.is_empty() {
407 no_results_with_filters(&self.query)
408 } else {
409 match self.selection {
410 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
411 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
412 }
413 }
414 };
415 match self.status {
416 Status::Idle => Some(EMPTY_HINT.to_owned()),
417 Status::Failed => Some(LOAD_ERROR.to_owned()),
418 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
419 Status::Ready if self.hits.is_empty() => Some(no_results()),
420 _ => None,
421 }
422 }
423
424 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
425 let (today, offset) = today_and_offset();
426 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
427 if let Some(message) = self.message_line() {
428 list = list.child(
429 div()
430 .px(px(SIDE_INSET))
431 .py(px(8.))
432 .text_size(px(13.))
433 .text_color(theme::text_muted())
434 .child(message),
435 );
436 }
437 let mut index = 0;
438 for group in group_by_month(&self.hits, today, offset) {
439 list = list.child(
440 div()
441 .px(px(SIDE_INSET))
442 .pt(px(12.))
443 .pb(px(4.))
444 .text_size(px(12.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .text_color(theme::text_muted())
447 .child(group.label),
448 );
449 for hit in group.hits {
450 list = list.child(self.hit_row(&hit, index, today, offset, cx));
451 index += 1;
452 }
453 }
454 div()
455 .debug_selector(|| FIND_RESULTS_TAG.into())
456 .id("find-results")
457 .flex_1()
458 .min_h_0()
459 .w_full()
460 .overflow_y_scroll()
461 .track_scroll(&self.scroll)
462 .child(list)
463 }
464
465 fn hit_row(
466 &self,
467 hit: &FindHit,
468 index: usize,
469 today: NaiveDate,
470 offset: chrono::FixedOffset,
471 cx: &mut Context<Self>,
472 ) -> impl IntoElement {
473 let current = self.current_index == Some(index);
474 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
475 .highlights
476 .iter()
477 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
478 .map(|range| {
479 (
480 range.clone(),
481 HighlightStyle {
482 color: Some(theme::accent_text()),
483 font_weight: Some(FontWeight::SEMIBOLD),
484 ..Default::default()
485 },
486 )
487 })
488 .collect();
489 v_flex()
490 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
491 .mx(px(8.))
492 .px(px(8.))
493 .py(px(8.))
494 .gap(px(2.))
495 .rounded(px(6.))
496 .cursor_pointer()
497 .when(current, |row| row.bg(theme::selection()))
498 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
499 .child(
500 h_flex()
501 .gap(px(8.))
502 .text_size(px(12.))
503 .child(
504 div()
505 .flex_1()
506 .min_w_0()
507 .truncate()
508 .font_weight(FontWeight::SEMIBOLD)
509 .text_color(theme::text())
510 .child(hit.sender_name.clone()),
511 )
512 .child(
513 div()
514 .flex_none()
515 .text_color(theme::text_muted())
516 .child(format::list_time_label(hit.sent_at, today, offset)),
517 ),
518 )
519 .child(
520 div()
521 .text_size(px(13.))
522 .text_color(theme::text_soft())
523 .line_clamp(2)
524 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
525 )
526 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
527 }
528 }
529
530 impl Render for FindPanel {
531 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
532 h_flex()
533 .debug_selector(|| FIND_PANEL_TAG.into())
534 .h_full()
535 .items_start()
536 .bg(theme::surface())
537 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
538 cx.emit(FindPanelEvent::Close);
539 cx.stop_propagation();
540 }))
541 .child(
542 div()
543 .debug_selector(|| FIND_DIVIDER_TAG.into())
544 .w(px(1.))
545 .h_full()
546 .flex_none()
547 .bg(theme::border()),
548 )
549 .child(
550 v_flex()
551 .flex_1()
552 .min_w_0()
553 .h_full()
554 .child(self.header(cx))
555 .child(self.search_row())
556 .child(self.chips(cx))
557 .child(self.results(cx)),
558 )
559 }
560 }
561
562 fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
563 Button::new(id)
564 .ghost()
565 .compact()
566 .label(label)
567 .dropdown_caret(true)
568 .rounded(px(CHIP_HEIGHT / 2.))
569 .h(px(CHIP_HEIGHT))
570 .text_size(px(12.))
571 .when(selected, |chip| {
572 chip.bg(theme::accent()).text_color(theme::on_accent())
573 })
574 .when(!selected, |chip| {
575 chip.bg(theme::surface_raised())
576 .text_color(theme::text_soft())
577 })
578 }
579
580 fn panel_title(selection: &Selection) -> &'static str {
581 match selection {
582 Selection::Chat(_) => FIND_IN_CHAT,
583 Selection::Channel(_) => FIND_IN_CHANNEL,
584 }
585 }
586
587 fn today_and_offset() -> (NaiveDate, chrono::FixedOffset) {
588 let now = Local::now();
589 (now.date_naive(), now.offset().fix())
590 }
591
592 fn local_hits(
593 store: &Store,
594 conversation_id: &str,
595 query: &str,
596 my_id: Option<&str>,
597 ) -> Vec<FindHit> {
598 if query.is_empty() {
599 return store
600 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
601 .unwrap_or_default()
602 .iter()
603 .filter(|record| !record.deleted)
604 .map(|record| from_record(record, my_id))
605 .collect();
606 }
607 let found = store
608 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
609 .unwrap_or_default();
610 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
611 let records = store
612 .messages_by_id(conversation_id, &message_ids)
613 .unwrap_or_default();
614 found
615 .iter()
616 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
617 .collect()
618 }
619
620 fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
621 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
622 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
623 let mut senders: Vec<Sender> = Vec::new();
624 let mut push = |user_id: &str, name: &str| {
625 if name.is_empty() || is_me(user_id) {
626 return;
627 }
628 if senders
629 .iter()
630 .any(|sender| same_user(&sender.user_id, user_id))
631 {
632 return;
633 }
634 senders.push(Sender {
635 user_id: user_id.to_owned(),
636 name: name.to_owned(),
637 });
638 };
639 if let Some(chat) = state
640 .sidebar
641 .chats
642 .iter()
643 .find(|chat| chat.id == conversation_id)
644 {
645 for member in &chat.members {
646 if let Some(user_id) = &member.user_id {
647 push(user_id, &member.display_name);
648 }
649 }
650 }
651 for record in state
652 .store
653 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
654 .unwrap_or_default()
655 .iter()
656 .rev()
657 {
658 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
659 push(user_id, name);
660 }
661 }
662 senders.sort_by_key(|sender| sender.name.to_lowercase());
663 senders
664 }
@@ -0,0 +1,664 @@
1use std::time::Duration;
2
3use chrono::{Local, NaiveDate, Offset};
4use gpui_kit::assets::IconName;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
7use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
8use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11use store::Store;
12use teams_core::substrate_search::{QueryRequest, QueryResults, QueryScope, SearchSession};
13
14use super::widgets::icon;
15use crate::app_state::{AppState, Selection};
16use crate::find_in_chat::{
17 DATE_LABEL, DateRange, EMPTY_HINT, FIND_IN_CHANNEL, FIND_IN_CHAT, FROM_LABEL, FindFilters,
18 FindHit, HAS_ATTACHMENT_LABEL, LOAD_ERROR, LOADING, MENTIONS_LABEL, NO_RESULTS_CHANNEL,
19 NO_RESULTS_CHAT, Sender, from_local, from_record, from_server, group_by_month, merge,
20 no_results_with_filters, same_user, step_index,
21};
22use crate::format;
23use crate::runtime;
24use crate::theme;
25
26pub const FIND_PANEL_TAG: &str = "shell/islands/main/find";
27pub const FIND_DIVIDER_TAG: &str = "shell/islands/main/find/divider-side";
28pub const FIND_INPUT_TAG: &str = "shell/islands/main/find/input";
29pub const FIND_RESULTS_TAG: &str = "shell/islands/main/find/results";
30pub const FIND_PANEL_WIDTH: f32 = 320.;
31const HEADER_HEIGHT: f32 = 48.;
32const SIDE_INSET: f32 = 16.;
33const INPUT_HEIGHT: f32 = 32.;
34const CHIP_HEIGHT: f32 = 24.;
35const SEARCH_DEBOUNCE: Duration = Duration::from_millis(200);
36const LOCAL_LIMIT: usize = 100;
37const FILTER_SCAN_LIMIT: usize = 500;
38const SENDER_SCAN_LIMIT: usize = 200;
39
40pub enum FindPanelEvent {
41 Close,
42 Jump(String),
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46enum Status {
47 Idle,
48 Loading,
49 Ready,
50 Failed,
51}
52
53pub struct FindPanel {
54 app: Entity<AppState>,
55 selection: Selection,
56 input: Entity<InputState>,
57 query: String,
58 filters: FindFilters,
59 senders: Vec<Sender>,
60 local_hits: Vec<FindHit>,
61 hits: Vec<FindHit>,
62 status: Status,
63 generation: u64,
64 current_index: Option<usize>,
65 search_session: SearchSession,
66 scroll: ScrollHandle,
67 _subscription: Subscription,
68}
69
70impl EventEmitter<FindPanelEvent> for FindPanel {}
71
72impl FindPanel {
73 pub fn new(
74 app: Entity<AppState>,
75 selection: Selection,
76 window: &mut Window,
77 cx: &mut Context<Self>,
78 ) -> Self {
79 let title = panel_title(&selection);
80 let input = cx.new(|cx| InputState::new(window, cx).placeholder(title));
81 let subscription = cx.subscribe_in(&input, window, Self::on_input);
82 let senders = senders_of(app.read(cx), selection.conversation_id());
83 FindPanel {
84 app,
85 selection,
86 input,
87 query: String::new(),
88 filters: FindFilters::default(),
89 senders,
90 local_hits: Vec::new(),
91 hits: Vec::new(),
92 status: Status::Idle,
93 generation: 0,
94 current_index: None,
95 search_session: SearchSession::new(),
96 scroll: ScrollHandle::new(),
97 _subscription: subscription,
98 }
99 }
100
101 pub fn selection(&self) -> &Selection {
102 &self.selection
103 }
104
105 pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
106 self.input.update(cx, |input, cx| input.focus(window, cx));
107 }
108
109 fn on_input(
110 &mut self,
111 input: &Entity<InputState>,
112 event: &InputEvent,
113 _: &mut Window,
114 cx: &mut Context<Self>,
115 ) {
116 match event {
117 InputEvent::Change => {
118 self.query = input.read(cx).value().trim().to_owned();
119 self.schedule_search(cx);
120 }
121 InputEvent::PressEnter { shift, .. } => self.step(*shift, cx),
122 _ => {}
123 }
124 }
125
126 fn step(&mut self, backwards: bool, cx: &mut Context<Self>) {
127 if let Some(index) = step_index(self.current_index, self.hits.len(), backwards) {
128 self.pick(index, cx);
129 }
130 }
131
132 fn pick(&mut self, index: usize, cx: &mut Context<Self>) {
133 let Some(hit) = self.hits.get(index) else {
134 return;
135 };
136 self.current_index = Some(index);
137 self.scroll.scroll_to_item(index);
138 cx.emit(FindPanelEvent::Jump(hit.message_id.clone()));
139 cx.notify();
140 }
141
142 fn update_filters(&mut self, change: impl FnOnce(&mut FindFilters), cx: &mut Context<Self>) {
143 change(&mut self.filters);
144 self.schedule_search(cx);
145 cx.notify();
146 }
147
148 fn schedule_search(&mut self, cx: &mut Context<Self>) {
149 self.generation += 1;
150 let generation = self.generation;
151 cx.spawn(async move |this, cx| {
152 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
153 this.update(cx, |panel, cx| {
154 if panel.generation == generation {
155 panel.run_search(cx);
156 }
157 })
158 .ok();
159 })
160 .detach();
161 }
162
163 fn run_search(&mut self, cx: &mut Context<Self>) {
164 self.current_index = None;
165 if self.query.is_empty() && !self.filters.is_active() {
166 self.local_hits.clear();
167 self.hits.clear();
168 self.status = Status::Idle;
169 cx.notify();
170 return;
171 }
172 let (store, engine, my_id) = {
173 let state = self.app.read(cx);
174 (
175 state.store.clone(),
176 state.engine.clone(),
177 state.directory.me.as_ref().map(|me| me.user_id.clone()),
178 )
179 };
180 let (today, offset) = today_and_offset();
181 let conversation_id = self.selection.conversation_id().to_owned();
182 let local: Vec<FindHit> =
183 local_hits(&store, &conversation_id, &self.query, my_id.as_deref())
184 .into_iter()
185 .filter(|hit| self.filters.admits(hit, today, offset))
186 .collect();
187 self.local_hits = local;
188 self.hits = merge(self.local_hits.clone(), Vec::new());
189 let server_engine = engine.filter(|_| matches!(self.selection, Selection::Chat(_)));
190 let Some(engine) = server_engine else {
191 self.status = Status::Ready;
192 cx.notify();
193 return;
194 };
195 self.status = Status::Loading;
196 let request = QueryRequest::new(self.query.clone(), QueryScope::Messages)
197 .with_filters(self.filters.server_filters(&conversation_id));
198 let search_session = self.search_session.clone();
199 let generation = self.generation;
200 let receiver =
201 runtime::spawn(async move { engine.server_query(&search_session, &request).await });
202 cx.spawn(async move |this, cx| {
203 let results = match receiver.await {
204 Ok(Ok(results)) => Some(results),
205 _ => None,
206 };
207 this.update(cx, |panel, cx| panel.apply_server(generation, results, cx))
208 .ok();
209 })
210 .detach();
211 cx.notify();
212 }
213
214 fn apply_server(
215 &mut self,
216 generation: u64,
217 results: Option<QueryResults>,
218 cx: &mut Context<Self>,
219 ) {
220 if generation != self.generation {
221 return;
222 }
223 let Some(results) = results else {
224 self.status = if self.hits.is_empty() {
225 Status::Failed
226 } else {
227 Status::Ready
228 };
229 cx.notify();
230 return;
231 };
232 let (today, offset) = today_and_offset();
233 let conversation_id = self.selection.conversation_id();
234 let server: Vec<FindHit> = results
235 .messages
236 .items
237 .iter()
238 .filter(|message| message.conversation_id == conversation_id)
239 .filter_map(from_server)
240 .filter(|hit| self.filters.admits(hit, today, offset))
241 .collect();
242 self.hits = merge(self.local_hits.clone(), server);
243 self.status = Status::Ready;
244 cx.notify();
245 }
246
247 fn header(&self, cx: &mut Context<Self>) -> impl IntoElement {
248 h_flex()
249 .h(px(HEADER_HEIGHT))
250 .flex_none()
251 .pl(px(SIDE_INSET))
252 .pr(px(12.))
253 .items_center()
254 .justify_between()
255 .child(
256 div()
257 .text_size(px(15.))
258 .font_weight(FontWeight::SEMIBOLD)
259 .child(panel_title(&self.selection)),
260 )
261 .child(
262 div()
263 .id("find-close")
264 .size(px(28.))
265 .flex()
266 .items_center()
267 .justify_center()
268 .rounded(px(7.))
269 .cursor_pointer()
270 .hover(|button| button.bg(theme::row_hover()))
271 .tooltip(|window, cx| Tooltip::new("Close").build(window, cx))
272 .child(icon(IconName::Close, 14., theme::text_muted()))
273 .on_click(cx.listener(|_, _, _, cx| cx.emit(FindPanelEvent::Close))),
274 )
275 }
276
277 fn search_row(&self) -> impl IntoElement {
278 h_flex()
279 .debug_selector(|| FIND_INPUT_TAG.into())
280 .mx(px(SIDE_INSET))
281 .h(px(INPUT_HEIGHT))
282 .flex_none()
283 .px(px(10.))
284 .gap(px(8.))
285 .items_center()
286 .rounded(px(6.))
287 .bg(theme::surface_raised())
288 .child(icon(IconName::Search, 14., theme::text_muted()))
289 .child(
290 div()
291 .flex_1()
292 .min_w_0()
293 .child(Input::new(&self.input).appearance(false).bordered(false)),
294 )
295 }
296
297 fn chips(&self, cx: &mut Context<Self>) -> impl IntoElement {
298 let panel = cx.weak_entity();
299 h_flex()
300 .px(px(SIDE_INSET))
301 .pt(px(8.))
302 .flex_none()
303 .flex_wrap()
304 .gap(px(6.))
305 .child(self.from_chip(panel.clone()))
306 .child(self.date_chip(panel))
307 .child(self.toggle_chip(
308 "find-has-attachment",
309 HAS_ATTACHMENT_LABEL,
310 self.filters.has_attachment,
311 |filters| filters.has_attachment = !filters.has_attachment,
312 cx,
313 ))
314 .child(self.toggle_chip(
315 "find-mentions",
316 MENTIONS_LABEL,
317 self.filters.mentions_me,
318 |filters| filters.mentions_me = !filters.mentions_me,
319 cx,
320 ))
321 }
322
323 fn from_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
324 let selected = self.filters.from.clone();
325 let label = selected
326 .as_ref()
327 .map_or(FROM_LABEL.to_owned(), |sender| sender.name.clone());
328 let senders = self.senders.clone();
329 chip_button("find-from", label, selected.is_some()).dropdown_menu(move |menu, _, _| {
330 senders.iter().fold(menu, |menu, sender| {
331 let checked = selected
332 .as_ref()
333 .is_some_and(|chosen| same_user(&chosen.user_id, &sender.user_id));
334 let (panel, sender) = (panel.clone(), sender.clone());
335 menu.item(
336 PopupMenuItem::new(sender.name.clone())
337 .checked(checked)
338 .on_click(move |_, _, cx| {
339 let pick = (!checked).then(|| sender.clone());
340 panel
341 .update(cx, |panel, cx| {
342 panel.update_filters(|filters| filters.from = pick, cx)
343 })
344 .ok();
345 }),
346 )
347 })
348 })
349 }
350
351 fn date_chip(&self, panel: WeakEntity<FindPanel>) -> impl IntoElement {
352 let selected = self.filters.date;
353 let label = selected.map_or(DATE_LABEL, DateRange::label);
354 chip_button("find-date", label.to_owned(), selected.is_some()).dropdown_menu(
355 move |menu, _, _| {
356 DateRange::ALL.into_iter().fold(menu, |menu, range| {
357 let checked = selected == Some(range);
358 let panel = panel.clone();
359 menu.item(PopupMenuItem::new(range.label()).checked(checked).on_click(
360 move |_, _, cx| {
361 let pick = (!checked).then_some(range);
362 panel
363 .update(cx, |panel, cx| {
364 panel.update_filters(|filters| filters.date = pick, cx)
365 })
366 .ok();
367 },
368 ))
369 })
370 },
371 )
372 }
373
374 fn toggle_chip(
375 &self,
376 id: &'static str,
377 label: &'static str,
378 selected: bool,
379 change: fn(&mut FindFilters),
380 cx: &mut Context<Self>,
381 ) -> impl IntoElement {
382 div()
383 .id(id)
384 .h(px(CHIP_HEIGHT))
385 .px(px(12.))
386 .flex()
387 .flex_none()
388 .items_center()
389 .rounded_full()
390 .cursor_pointer()
391 .text_size(px(12.))
392 .when(selected, |chip| {
393 chip.bg(theme::accent()).text_color(theme::on_accent())
394 })
395 .when(!selected, |chip| {
396 chip.bg(theme::surface_raised())
397 .text_color(theme::text_soft())
398 .hover(|chip| chip.bg(theme::border_strong()))
399 })
400 .child(label)
401 .on_click(cx.listener(move |panel, _, _, cx| panel.update_filters(change, cx)))
402 }
403
404 fn message_line(&self) -> Option<String> {
405 let no_results = || {
406 if self.filters.is_active() && !self.query.is_empty() {
407 no_results_with_filters(&self.query)
408 } else {
409 match self.selection {
410 Selection::Chat(_) => NO_RESULTS_CHAT.to_owned(),
411 Selection::Channel(_) => NO_RESULTS_CHANNEL.to_owned(),
412 }
413 }
414 };
415 match self.status {
416 Status::Idle => Some(EMPTY_HINT.to_owned()),
417 Status::Failed => Some(LOAD_ERROR.to_owned()),
418 Status::Loading if self.hits.is_empty() => Some(LOADING.to_owned()),
419 Status::Ready if self.hits.is_empty() => Some(no_results()),
420 _ => None,
421 }
422 }
423
424 fn results(&self, cx: &mut Context<Self>) -> impl IntoElement {
425 let (today, offset) = today_and_offset();
426 let mut list = v_flex().w_full().pt(px(8.)).pb(px(SIDE_INSET));
427 if let Some(message) = self.message_line() {
428 list = list.child(
429 div()
430 .px(px(SIDE_INSET))
431 .py(px(8.))
432 .text_size(px(13.))
433 .text_color(theme::text_muted())
434 .child(message),
435 );
436 }
437 let mut index = 0;
438 for group in group_by_month(&self.hits, today, offset) {
439 list = list.child(
440 div()
441 .px(px(SIDE_INSET))
442 .pt(px(12.))
443 .pb(px(4.))
444 .text_size(px(12.))
445 .font_weight(FontWeight::SEMIBOLD)
446 .text_color(theme::text_muted())
447 .child(group.label),
448 );
449 for hit in group.hits {
450 list = list.child(self.hit_row(&hit, index, today, offset, cx));
451 index += 1;
452 }
453 }
454 div()
455 .debug_selector(|| FIND_RESULTS_TAG.into())
456 .id("find-results")
457 .flex_1()
458 .min_h_0()
459 .w_full()
460 .overflow_y_scroll()
461 .track_scroll(&self.scroll)
462 .child(list)
463 }
464
465 fn hit_row(
466 &self,
467 hit: &FindHit,
468 index: usize,
469 today: NaiveDate,
470 offset: chrono::FixedOffset,
471 cx: &mut Context<Self>,
472 ) -> impl IntoElement {
473 let current = self.current_index == Some(index);
474 let marks: Vec<(std::ops::Range<usize>, HighlightStyle)> = hit
475 .highlights
476 .iter()
477 .filter(|range| hit.text.is_char_boundary(range.start) && range.end <= hit.text.len())
478 .map(|range| {
479 (
480 range.clone(),
481 HighlightStyle {
482 color: Some(theme::accent_text()),
483 font_weight: Some(FontWeight::SEMIBOLD),
484 ..Default::default()
485 },
486 )
487 })
488 .collect();
489 v_flex()
490 .id(ElementId::NamedInteger("find-hit".into(), index as u64))
491 .mx(px(8.))
492 .px(px(8.))
493 .py(px(8.))
494 .gap(px(2.))
495 .rounded(px(6.))
496 .cursor_pointer()
497 .when(current, |row| row.bg(theme::selection()))
498 .when(!current, |row| row.hover(|row| row.bg(theme::row_hover())))
499 .child(
500 h_flex()
501 .gap(px(8.))
502 .text_size(px(12.))
503 .child(
504 div()
505 .flex_1()
506 .min_w_0()
507 .truncate()
508 .font_weight(FontWeight::SEMIBOLD)
509 .text_color(theme::text())
510 .child(hit.sender_name.clone()),
511 )
512 .child(
513 div()
514 .flex_none()
515 .text_color(theme::text_muted())
516 .child(format::list_time_label(hit.sent_at, today, offset)),
517 ),
518 )
519 .child(
520 div()
521 .text_size(px(13.))
522 .text_color(theme::text_soft())
523 .line_clamp(2)
524 .child(StyledText::new(hit.text.clone()).with_highlights(marks)),
525 )
526 .on_click(cx.listener(move |panel, _, _, cx| panel.pick(index, cx)))
527 }
528}
529
530impl Render for FindPanel {
531 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
532 h_flex()
533 .debug_selector(|| FIND_PANEL_TAG.into())
534 .h_full()
535 .items_start()
536 .bg(theme::surface())
537 .capture_action(cx.listener(|_, _: &Escape, _, cx| {
538 cx.emit(FindPanelEvent::Close);
539 cx.stop_propagation();
540 }))
541 .child(
542 div()
543 .debug_selector(|| FIND_DIVIDER_TAG.into())
544 .w(px(1.))
545 .h_full()
546 .flex_none()
547 .bg(theme::border()),
548 )
549 .child(
550 v_flex()
551 .flex_1()
552 .min_w_0()
553 .h_full()
554 .child(self.header(cx))
555 .child(self.search_row())
556 .child(self.chips(cx))
557 .child(self.results(cx)),
558 )
559 }
560}
561
562fn chip_button(id: &'static str, label: String, selected: bool) -> Button {
563 Button::new(id)
564 .ghost()
565 .compact()
566 .label(label)
567 .dropdown_caret(true)
568 .rounded(px(CHIP_HEIGHT / 2.))
569 .h(px(CHIP_HEIGHT))
570 .text_size(px(12.))
571 .when(selected, |chip| {
572 chip.bg(theme::accent()).text_color(theme::on_accent())
573 })
574 .when(!selected, |chip| {
575 chip.bg(theme::surface_raised())
576 .text_color(theme::text_soft())
577 })
578}
579
580fn panel_title(selection: &Selection) -> &'static str {
581 match selection {
582 Selection::Chat(_) => FIND_IN_CHAT,
583 Selection::Channel(_) => FIND_IN_CHANNEL,
584 }
585}
586
587fn today_and_offset() -> (NaiveDate, chrono::FixedOffset) {
588 let now = Local::now();
589 (now.date_naive(), now.offset().fix())
590}
591
592fn local_hits(
593 store: &Store,
594 conversation_id: &str,
595 query: &str,
596 my_id: Option<&str>,
597) -> Vec<FindHit> {
598 if query.is_empty() {
599 return store
600 .messages(conversation_id, None, FILTER_SCAN_LIMIT)
601 .unwrap_or_default()
602 .iter()
603 .filter(|record| !record.deleted)
604 .map(|record| from_record(record, my_id))
605 .collect();
606 }
607 let found = store
608 .search_messages(query, Some(conversation_id), LOCAL_LIMIT)
609 .unwrap_or_default();
610 let message_ids: Vec<String> = found.iter().map(|hit| hit.message_id.clone()).collect();
611 let records = store
612 .messages_by_id(conversation_id, &message_ids)
613 .unwrap_or_default();
614 found
615 .iter()
616 .map(|hit| from_local(hit, records.get(&hit.message_id), my_id))
617 .collect()
618}
619
620fn senders_of(state: &AppState, conversation_id: &str) -> Vec<Sender> {
621 let my_id = state.directory.me.as_ref().map(|me| me.user_id.as_str());
622 let is_me = |user_id: &str| my_id.is_some_and(|my_id| same_user(my_id, user_id));
623 let mut senders: Vec<Sender> = Vec::new();
624 let mut push = |user_id: &str, name: &str| {
625 if name.is_empty() || is_me(user_id) {
626 return;
627 }
628 if senders
629 .iter()
630 .any(|sender| same_user(&sender.user_id, user_id))
631 {
632 return;
633 }
634 senders.push(Sender {
635 user_id: user_id.to_owned(),
636 name: name.to_owned(),
637 });
638 };
639 if let Some(chat) = state
640 .sidebar
641 .chats
642 .iter()
643 .find(|chat| chat.id == conversation_id)
644 {
645 for member in &chat.members {
646 if let Some(user_id) = &member.user_id {
647 push(user_id, &member.display_name);
648 }
649 }
650 }
651 for record in state
652 .store
653 .messages(conversation_id, None, SENDER_SCAN_LIMIT)
654 .unwrap_or_default()
655 .iter()
656 .rev()
657 {
658 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
659 push(user_id, name);
660 }
661 }
662 senders.sort_by_key(|sender| sender.name.to_lowercase());
663 senders
664}
crates/app/src/views/group_name.rs added +196 −0
@@ -0,0 +1,196 @@
1 use std::cell::RefCell;
2 use std::rc::Rc;
3
4 use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5 use gpui_kit::assets::IconName;
6 use gpui_kit::base::PopoverState;
7 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 use gpui_kit::component::input::{Input, InputEvent, InputState};
9 use gpui_kit::component::popover::Popover;
10 use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11 use gpui_kit::prelude::FluentBuilder as _;
12 use gpui_kit::*;
13
14 use super::widgets::icon;
15 use crate::app_state::AppState;
16 use crate::theme;
17
18 const BUTTON_TOOLTIP: &str = "Name group chat";
19 const FIELD_LABEL: &str = "Group name";
20 const PLACEHOLDER: &str = "Type a group name";
21 const FORM_WIDTH: f32 = 300.;
22 const FORM_PADDING: f32 = 12.;
23 const FORM_GAP: f32 = 8.;
24 const LABEL_SIZE: f32 = 12.;
25 const ICON_SIZE: f32 = 16.;
26
27 pub fn problem_text(problem: TopicProblem) -> String {
28 match problem {
29 TopicProblem::TooLong => {
30 format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31 }
32 TopicProblem::InvalidCharacter => {
33 format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34 }
35 }
36 }
37
38 struct GroupNameForm {
39 app: Entity<AppState>,
40 chat_id: String,
41 input: Entity<InputState>,
42 popover: WeakEntity<PopoverState>,
43 _subscription: Subscription,
44 }
45
46 impl GroupNameForm {
47 fn new(
48 app: Entity<AppState>,
49 chat_id: String,
50 title: String,
51 popover: WeakEntity<PopoverState>,
52 window: &mut Window,
53 cx: &mut Context<Self>,
54 ) -> Self {
55 let input = cx.new(|cx| {
56 let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57 state.set_value(title, window, cx);
58 state
59 });
60 input.update(cx, |state, cx| state.focus(window, cx));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 GroupNameForm {
63 app,
64 chat_id,
65 input,
66 popover,
67 _subscription: subscription,
68 }
69 }
70
71 fn on_input_event(
72 &mut self,
73 _: &Entity<InputState>,
74 event: &InputEvent,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 match event {
79 InputEvent::Change => cx.notify(),
80 InputEvent::PressEnter { .. } => self.save(window, cx),
81 _ => {}
82 }
83 }
84
85 fn problem(&self, cx: &App) -> Option<TopicProblem> {
86 topic_problem(self.input.read(cx).value().trim())
87 }
88
89 fn close(&self, window: &mut Window, cx: &mut App) {
90 self.popover
91 .update(cx, |state, cx| state.dismiss(window, cx))
92 .ok();
93 }
94
95 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96 if self.problem(cx).is_some() {
97 return;
98 }
99 let topic = self.input.read(cx).value().trim().to_owned();
100 let chat_id = self.chat_id.clone();
101 self.app
102 .update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103 self.close(window, cx);
104 }
105 }
106
107 impl Render for GroupNameForm {
108 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109 let problem = self.problem(cx);
110 v_flex()
111 .w(px(FORM_WIDTH))
112 .p(px(FORM_PADDING))
113 .gap(px(FORM_GAP))
114 .child(
115 div()
116 .text_size(px(LABEL_SIZE))
117 .text_color(theme::text_soft())
118 .child(FIELD_LABEL),
119 )
120 .child(Input::new(&self.input))
121 .when_some(problem, |form, problem| {
122 form.child(
123 div()
124 .text_size(px(LABEL_SIZE))
125 .text_color(theme::red_soft())
126 .child(problem_text(problem)),
127 )
128 })
129 .child(
130 h_flex()
131 .justify_end()
132 .gap(px(FORM_GAP))
133 .child(
134 Button::new("group-name-cancel")
135 .label("Cancel")
136 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137 )
138 .child(
139 Button::new("group-name-save")
140 .primary()
141 .label("Save")
142 .disabled(problem.is_some())
143 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144 ),
145 )
146 }
147 }
148
149 pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151 let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152 let reset = form.clone();
153 Popover::new("group-name")
154 .anchor(Anchor::TopLeft)
155 .p(px(0.))
156 .trigger(
157 Button::new("group-name-button")
158 .ghost()
159 .compact()
160 .tooltip(BUTTON_TOOLTIP)
161 .child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162 )
163 .on_open_change(move |open, _, _| {
164 if !*open {
165 reset.borrow_mut().take();
166 }
167 })
168 .content(move |_, window, cx| {
169 if let Some(existing) = form.borrow().clone() {
170 return existing;
171 }
172 let popover = cx.entity().downgrade();
173 let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174 let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175 *form.borrow_mut() = Some(created.clone());
176 created
177 })
178 .into_any_element()
179 }
180
181 #[cfg(test)]
182 mod tests {
183 use super::{TopicProblem, problem_text};
184
185 #[test]
186 fn problems_use_the_teams_wording() {
187 assert_eq!(
188 problem_text(TopicProblem::TooLong),
189 "Your group name can't be longer than 250 characters."
190 );
191 assert_eq!(
192 problem_text(TopicProblem::InvalidCharacter),
193 "':' is not a valid character in group names."
194 );
195 }
196 }
@@ -0,0 +1,196 @@
1use std::cell::RefCell;
2use std::rc::Rc;
3
4use chatsvc::{INVALID_TOPIC_CHARACTER, MAX_TOPIC_LENGTH, TopicProblem, topic_problem};
5use gpui_kit::assets::IconName;
6use gpui_kit::base::PopoverState;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::input::{Input, InputEvent, InputState};
9use gpui_kit::component::popover::Popover;
10use gpui_kit::component::{Disableable as _, h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::widgets::icon;
15use crate::app_state::AppState;
16use crate::theme;
17
18const BUTTON_TOOLTIP: &str = "Name group chat";
19const FIELD_LABEL: &str = "Group name";
20const PLACEHOLDER: &str = "Type a group name";
21const FORM_WIDTH: f32 = 300.;
22const FORM_PADDING: f32 = 12.;
23const FORM_GAP: f32 = 8.;
24const LABEL_SIZE: f32 = 12.;
25const ICON_SIZE: f32 = 16.;
26
27pub fn problem_text(problem: TopicProblem) -> String {
28 match problem {
29 TopicProblem::TooLong => {
30 format!("Your group name can't be longer than {MAX_TOPIC_LENGTH} characters.")
31 }
32 TopicProblem::InvalidCharacter => {
33 format!("'{INVALID_TOPIC_CHARACTER}' is not a valid character in group names.")
34 }
35 }
36}
37
38struct GroupNameForm {
39 app: Entity<AppState>,
40 chat_id: String,
41 input: Entity<InputState>,
42 popover: WeakEntity<PopoverState>,
43 _subscription: Subscription,
44}
45
46impl GroupNameForm {
47 fn new(
48 app: Entity<AppState>,
49 chat_id: String,
50 title: String,
51 popover: WeakEntity<PopoverState>,
52 window: &mut Window,
53 cx: &mut Context<Self>,
54 ) -> Self {
55 let input = cx.new(|cx| {
56 let mut state = InputState::new(window, cx).placeholder(PLACEHOLDER);
57 state.set_value(title, window, cx);
58 state
59 });
60 input.update(cx, |state, cx| state.focus(window, cx));
61 let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
62 GroupNameForm {
63 app,
64 chat_id,
65 input,
66 popover,
67 _subscription: subscription,
68 }
69 }
70
71 fn on_input_event(
72 &mut self,
73 _: &Entity<InputState>,
74 event: &InputEvent,
75 window: &mut Window,
76 cx: &mut Context<Self>,
77 ) {
78 match event {
79 InputEvent::Change => cx.notify(),
80 InputEvent::PressEnter { .. } => self.save(window, cx),
81 _ => {}
82 }
83 }
84
85 fn problem(&self, cx: &App) -> Option<TopicProblem> {
86 topic_problem(self.input.read(cx).value().trim())
87 }
88
89 fn close(&self, window: &mut Window, cx: &mut App) {
90 self.popover
91 .update(cx, |state, cx| state.dismiss(window, cx))
92 .ok();
93 }
94
95 fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
96 if self.problem(cx).is_some() {
97 return;
98 }
99 let topic = self.input.read(cx).value().trim().to_owned();
100 let chat_id = self.chat_id.clone();
101 self.app
102 .update(cx, |state, cx| state.rename_chat(&chat_id, &topic, cx));
103 self.close(window, cx);
104 }
105}
106
107impl Render for GroupNameForm {
108 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
109 let problem = self.problem(cx);
110 v_flex()
111 .w(px(FORM_WIDTH))
112 .p(px(FORM_PADDING))
113 .gap(px(FORM_GAP))
114 .child(
115 div()
116 .text_size(px(LABEL_SIZE))
117 .text_color(theme::text_soft())
118 .child(FIELD_LABEL),
119 )
120 .child(Input::new(&self.input))
121 .when_some(problem, |form, problem| {
122 form.child(
123 div()
124 .text_size(px(LABEL_SIZE))
125 .text_color(theme::red_soft())
126 .child(problem_text(problem)),
127 )
128 })
129 .child(
130 h_flex()
131 .justify_end()
132 .gap(px(FORM_GAP))
133 .child(
134 Button::new("group-name-cancel")
135 .label("Cancel")
136 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
137 )
138 .child(
139 Button::new("group-name-save")
140 .primary()
141 .label("Save")
142 .disabled(problem.is_some())
143 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
144 ),
145 )
146 }
147}
148
149pub fn group_name_button(app: &Entity<AppState>, chat_id: &str, title: &str) -> AnyElement {
150 let (app, chat_id, title) = (app.clone(), chat_id.to_owned(), title.to_owned());
151 let form: Rc<RefCell<Option<Entity<GroupNameForm>>>> = Rc::default();
152 let reset = form.clone();
153 Popover::new("group-name")
154 .anchor(Anchor::TopLeft)
155 .p(px(0.))
156 .trigger(
157 Button::new("group-name-button")
158 .ghost()
159 .compact()
160 .tooltip(BUTTON_TOOLTIP)
161 .child(icon(IconName::Pencil, ICON_SIZE, theme::text_soft())),
162 )
163 .on_open_change(move |open, _, _| {
164 if !*open {
165 reset.borrow_mut().take();
166 }
167 })
168 .content(move |_, window, cx| {
169 if let Some(existing) = form.borrow().clone() {
170 return existing;
171 }
172 let popover = cx.entity().downgrade();
173 let (app, chat_id, title) = (app.clone(), chat_id.clone(), title.clone());
174 let created = cx.new(|cx| GroupNameForm::new(app, chat_id, title, popover, window, cx));
175 *form.borrow_mut() = Some(created.clone());
176 created
177 })
178 .into_any_element()
179}
180
181#[cfg(test)]
182mod tests {
183 use super::{TopicProblem, problem_text};
184
185 #[test]
186 fn problems_use_the_teams_wording() {
187 assert_eq!(
188 problem_text(TopicProblem::TooLong),
189 "Your group name can't be longer than 250 characters."
190 );
191 assert_eq!(
192 problem_text(TopicProblem::InvalidCharacter),
193 "':' is not a valid character in group names."
194 );
195 }
196}
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_actions.rs +0 −1
@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;
23 23 const BAR_ICON: f32 = 16.;
24 24 const DELEGATE_ITEM_WIDTH: f32 = 188.;
25 25 const DELEGATE_AGENT_SIZE: f32 = 11.;
26 pub const QUICK_REACTION_COUNT: usize = 4;
27 26
28 27 pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
29 28 pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
@@ -23,7 +23,6 @@ const BAR_PADDING: f32 = 3.;
23const BAR_ICON: f32 = 16.;
23const BAR_ICON: f32 = 16.;
24const DELEGATE_ITEM_WIDTH: f32 = 188.;
24const DELEGATE_ITEM_WIDTH: f32 = 188.;
25const DELEGATE_AGENT_SIZE: f32 = 11.;
25const DELEGATE_AGENT_SIZE: f32 = 11.;
26pub const QUICK_REACTION_COUNT: usize = 4;
27
26
28pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
27pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
29pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
28pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
crates/app/src/views/message_row.rs +50 −10
@@ -51,6 +51,10 @@ pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";
51 51 pub(super) const AVATAR_SIZE: f32 = 28.;
52 52 pub(super) const AVATAR_GAP: f32 = 8.;
53 53 const SERIES_START_GAP: f32 = 8.;
54 const SERIES_GAP: f32 = 2.;
55 const COMPACT_SERIES_START_GAP: f32 = 4.;
56 const COMPACT_SERIES_GAP: f32 = 1.;
57 const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;
54 58 pub(super) const BODY_SIZE: f32 = 13.5;
55 59 const MAX_WIDTH_RATIO: f32 = 0.7;
56 60 const NARROW_BUBBLE_WIDTH: f32 = 300.;
@@ -61,6 +65,8 @@ const META_CHECK_SIZE: f32 = 15.;
61 65 const SAVED_MARK_SIZE: f32 = 12.;
62 66 const FORWARDED_SIZE: f32 = 11.;
63 67 const IMPORTANCE_LABEL_SIZE: f32 = 12.;
68 const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
69 const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
64 70 pub(super) const BUBBLE_PADDING_X: f32 = 12.;
65 71 const FIGURE_SPACE_WIDTH: f32 = 7.4;
66 72 const PULSE_PERIOD: Duration = Duration::from_millis(1600);
@@ -93,6 +99,24 @@ pub struct RowActions {
93 99 pub call: CallActions,
94 100 pub reaction_proposal: Option<ReactionPill>,
95 101 pub undo_delete: SharedRowAction,
102 pub compact: bool,
103 }
104
105 pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
106 match (has_previous, compact) {
107 (true, false) => SERIES_GAP,
108 (true, true) => COMPACT_SERIES_GAP,
109 (false, false) => SERIES_START_GAP,
110 (false, true) => COMPACT_SERIES_START_GAP,
111 }
112 }
113
114 pub fn bubble_padding_y(compact: bool) -> f32 {
115 if compact {
116 COMPACT_BUBBLE_PADDING_Y
117 } else {
118 BUBBLE_PADDING_Y
119 }
96 120 }
97 121
98 122 const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -194,7 +218,7 @@ fn bubble(
194 218 .rounded_br(px(corners.bottom_right))
195 219 .rounded_bl(px(corners.bottom_left))
196 220 .px(px(BUBBLE_PADDING_X))
197 .py(px(BUBBLE_PADDING_Y))
221 .py(px(bubble_padding_y(extras.compact)))
198 222 })
199 223 .text_size(px(BODY_SIZE))
200 224 .line_height(relative(1.45));
@@ -230,7 +254,7 @@ fn bubble(
230 254 let has_reactions = !row.reactions.is_empty();
231 255 let saved = extras.saved;
232 256 let mut content = v_flex().gap(px(6.));
233 content = content.children(importance_header(row));
257 content = content.children(importance_header(row, extras.compact));
234 258 if row.forwarded {
235 259 content = content.child(forwarded_header());
236 260 }
@@ -304,7 +328,7 @@ fn bubble(
304 328 .child(
305 329 h_flex()
306 330 .flex_none()
307 .mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
331 .mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))
308 332 .child(bubble_meta(row, own, saved)),
309 333 ),
310 334 );
@@ -353,6 +377,7 @@ struct BubbleExtras {
353 377 agent_run: Option<AgentRun>,
354 378 reaction_proposal: Option<ReactionPill>,
355 379 undo_delete: SharedRowAction,
380 compact: bool,
356 381 }
357 382
358 383 fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -360,13 +385,17 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
360 385 }
361 386
362 387 /// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
363 pub(super) fn importance_header(row: &MessageRow) -> Option<Div> {
388 pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {
364 389 let label = importance_label(row.importance)?;
365 390 Some(
366 391 div()
367 392 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
368 393 .text_size(px(IMPORTANCE_LABEL_SIZE))
369 .line_height(px(16.))
394 .line_height(px(if compact {
395 COMPACT_IMPORTANCE_LINE_HEIGHT
396 } else {
397 IMPORTANCE_LINE_HEIGHT
398 }))
370 399 .font_weight(FontWeight::BOLD)
371 400 .text_color(theme::red())
372 401 .child(label),
@@ -704,6 +733,7 @@ pub fn render_message_row(
704 733 pinned: _,
705 734 reaction_proposal,
706 735 undo_delete,
736 compact,
707 737 } = actions;
708 738 let extras = BubbleExtras {
709 739 hover: hovered,
@@ -719,13 +749,10 @@ pub fn render_message_row(
719 749 agent_run,
720 750 reaction_proposal,
721 751 undo_delete,
752 compact,
722 753 };
723 754 let own = row.own;
724 let spacing = if row.series.has_prev {
725 px(2.)
726 } else {
727 px(SERIES_START_GAP)
728 };
755 let spacing = px(row_spacing(row.series.has_prev, compact));
729 756 let mut container = v_flex().w_full().px(px(ROW_PADDING));
730 757 if let Some(day) = &row.day_header {
731 758 container = container.child(day_separator(day));
@@ -759,3 +786,16 @@ pub fn render_message_row(
759 786 )
760 787 .into_any_element()
761 788 }
789
790 #[cfg(test)]
791 mod density_tests {
792 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
793
794 #[test]
795 fn compact_density_tightens_gaps_and_bubble_padding() {
796 assert!(row_spacing(false, true) < row_spacing(false, false));
797 assert!(row_spacing(true, true) < row_spacing(true, false));
798 assert!(bubble_padding_y(true) < bubble_padding_y(false));
799 assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);
800 }
801 }
@@ -51,6 +51,10 @@ pub const IMPORTANCE_LABEL_TAG: &str = "message-importance-label";
51pub(super) const AVATAR_SIZE: f32 = 28.;
51pub(super) const AVATAR_SIZE: f32 = 28.;
52pub(super) const AVATAR_GAP: f32 = 8.;
52pub(super) const AVATAR_GAP: f32 = 8.;
53const SERIES_START_GAP: f32 = 8.;
53const SERIES_START_GAP: f32 = 8.;
54const SERIES_GAP: f32 = 2.;
55const COMPACT_SERIES_START_GAP: f32 = 4.;
56const COMPACT_SERIES_GAP: f32 = 1.;
57const COMPACT_BUBBLE_PADDING_Y: f32 = 4.;
54pub(super) const BODY_SIZE: f32 = 13.5;
58pub(super) const BODY_SIZE: f32 = 13.5;
55const MAX_WIDTH_RATIO: f32 = 0.7;
59const MAX_WIDTH_RATIO: f32 = 0.7;
56const NARROW_BUBBLE_WIDTH: f32 = 300.;
60const NARROW_BUBBLE_WIDTH: f32 = 300.;
@@ -61,6 +65,8 @@ const META_CHECK_SIZE: f32 = 15.;
61const SAVED_MARK_SIZE: f32 = 12.;
65const SAVED_MARK_SIZE: f32 = 12.;
62const FORWARDED_SIZE: f32 = 11.;
66const FORWARDED_SIZE: f32 = 11.;
63const IMPORTANCE_LABEL_SIZE: f32 = 12.;
67const IMPORTANCE_LABEL_SIZE: f32 = 12.;
68const IMPORTANCE_LINE_HEIGHT: f32 = 16.;
69const COMPACT_IMPORTANCE_LINE_HEIGHT: f32 = 14.;
64pub(super) const BUBBLE_PADDING_X: f32 = 12.;
70pub(super) const BUBBLE_PADDING_X: f32 = 12.;
65const FIGURE_SPACE_WIDTH: f32 = 7.4;
71const FIGURE_SPACE_WIDTH: f32 = 7.4;
66const PULSE_PERIOD: Duration = Duration::from_millis(1600);
72const PULSE_PERIOD: Duration = Duration::from_millis(1600);
@@ -93,6 +99,24 @@ pub struct RowActions {
93 pub call: CallActions,
99 pub call: CallActions,
94 pub reaction_proposal: Option<ReactionPill>,
100 pub reaction_proposal: Option<ReactionPill>,
95 pub undo_delete: SharedRowAction,
101 pub undo_delete: SharedRowAction,
102 pub compact: bool,
103}
104
105pub fn row_spacing(has_previous: bool, compact: bool) -> f32 {
106 match (has_previous, compact) {
107 (true, false) => SERIES_GAP,
108 (true, true) => COMPACT_SERIES_GAP,
109 (false, false) => SERIES_START_GAP,
110 (false, true) => COMPACT_SERIES_START_GAP,
111 }
112}
113
114pub fn bubble_padding_y(compact: bool) -> f32 {
115 if compact {
116 COMPACT_BUBBLE_PADDING_Y
117 } else {
118 BUBBLE_PADDING_Y
119 }
96}
120}
97
121
98const TOOLBAR_RIGHT_INSET: f32 = 0.;
122const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -194,7 +218,7 @@ fn bubble(
194 .rounded_br(px(corners.bottom_right))
218 .rounded_br(px(corners.bottom_right))
195 .rounded_bl(px(corners.bottom_left))
219 .rounded_bl(px(corners.bottom_left))
196 .px(px(BUBBLE_PADDING_X))
220 .px(px(BUBBLE_PADDING_X))
197 .py(px(BUBBLE_PADDING_Y))
221 .py(px(bubble_padding_y(extras.compact)))
198 })
222 })
199 .text_size(px(BODY_SIZE))
223 .text_size(px(BODY_SIZE))
200 .line_height(relative(1.45));
224 .line_height(relative(1.45));
@@ -230,7 +254,7 @@ fn bubble(
230 let has_reactions = !row.reactions.is_empty();
254 let has_reactions = !row.reactions.is_empty();
231 let saved = extras.saved;
255 let saved = extras.saved;
232 let mut content = v_flex().gap(px(6.));
256 let mut content = v_flex().gap(px(6.));
233 content = content.children(importance_header(row));
257 content = content.children(importance_header(row, extras.compact));
234 if row.forwarded {
258 if row.forwarded {
235 content = content.child(forwarded_header());
259 content = content.child(forwarded_header());
236 }
260 }
@@ -304,7 +328,7 @@ fn bubble(
304 .child(
328 .child(
305 h_flex()
329 h_flex()
306 .flex_none()
330 .flex_none()
307 .mb(px(META_BOTTOM_INSET - BUBBLE_PADDING_Y))
331 .mb(px(META_BOTTOM_INSET - bubble_padding_y(extras.compact)))
308 .child(bubble_meta(row, own, saved)),
332 .child(bubble_meta(row, own, saved)),
309 ),
333 ),
310 );
334 );
@@ -353,6 +377,7 @@ struct BubbleExtras {
353 agent_run: Option<AgentRun>,
377 agent_run: Option<AgentRun>,
354 reaction_proposal: Option<ReactionPill>,
378 reaction_proposal: Option<ReactionPill>,
355 undo_delete: SharedRowAction,
379 undo_delete: SharedRowAction,
380 compact: bool,
356}
381}
357
382
358fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
383fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
@@ -360,13 +385,17 @@ fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
360}
385}
361
386
362/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
387/// Teams: bold "Important!" / "Urgent!" in capitals above the message text.
363pub(super) fn importance_header(row: &MessageRow) -> Option<Div> {
388pub(super) fn importance_header(row: &MessageRow, compact: bool) -> Option<Div> {
364 let label = importance_label(row.importance)?;
389 let label = importance_label(row.importance)?;
365 Some(
390 Some(
366 div()
391 div()
367 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
392 .debug_selector(|| IMPORTANCE_LABEL_TAG.into())
368 .text_size(px(IMPORTANCE_LABEL_SIZE))
393 .text_size(px(IMPORTANCE_LABEL_SIZE))
369 .line_height(px(16.))
394 .line_height(px(if compact {
395 COMPACT_IMPORTANCE_LINE_HEIGHT
396 } else {
397 IMPORTANCE_LINE_HEIGHT
398 }))
370 .font_weight(FontWeight::BOLD)
399 .font_weight(FontWeight::BOLD)
371 .text_color(theme::red())
400 .text_color(theme::red())
372 .child(label),
401 .child(label),
@@ -704,6 +733,7 @@ pub fn render_message_row(
704 pinned: _,
733 pinned: _,
705 reaction_proposal,
734 reaction_proposal,
706 undo_delete,
735 undo_delete,
736 compact,
707 } = actions;
737 } = actions;
708 let extras = BubbleExtras {
738 let extras = BubbleExtras {
709 hover: hovered,
739 hover: hovered,
@@ -719,13 +749,10 @@ pub fn render_message_row(
719 agent_run,
749 agent_run,
720 reaction_proposal,
750 reaction_proposal,
721 undo_delete,
751 undo_delete,
752 compact,
722 };
753 };
723 let own = row.own;
754 let own = row.own;
724 let spacing = if row.series.has_prev {
755 let spacing = px(row_spacing(row.series.has_prev, compact));
725 px(2.)
726 } else {
727 px(SERIES_START_GAP)
728 };
729 let mut container = v_flex().w_full().px(px(ROW_PADDING));
756 let mut container = v_flex().w_full().px(px(ROW_PADDING));
730 if let Some(day) = &row.day_header {
757 if let Some(day) = &row.day_header {
731 container = container.child(day_separator(day));
758 container = container.child(day_separator(day));
@@ -759,3 +786,16 @@ pub fn render_message_row(
759 )
786 )
760 .into_any_element()
787 .into_any_element()
761}
788}
789
790#[cfg(test)]
791mod density_tests {
792 use super::{META_BOTTOM_INSET, bubble_padding_y, row_spacing};
793
794 #[test]
795 fn compact_density_tightens_gaps_and_bubble_padding() {
796 assert!(row_spacing(false, true) < row_spacing(false, false));
797 assert!(row_spacing(true, true) < row_spacing(true, false));
798 assert!(bubble_padding_y(true) < bubble_padding_y(false));
799 assert!(META_BOTTOM_INSET - bubble_padding_y(true) >= 0.);
800 }
801}
crates/app/src/views/mod.rs +3 −0
@@ -38,11 +38,14 @@ pub mod chat_members;
38 38 pub mod composer;
39 39 pub mod connection_banner;
40 40 pub mod conversation;
41 pub mod customize_reactions;
41 42 pub mod dialog_overlay;
42 43 pub mod emoji_popup;
43 44 pub mod format_toolbar;
44 45 pub mod forward_dialog;
46 pub mod find_panel;
45 47 pub mod fun_picker;
48 pub mod group_name;
46 49 pub mod image_menu;
47 50 pub mod image_viewer;
48 51 pub mod join_dialog;
@@ -38,11 +38,14 @@ pub mod chat_members;
38pub mod composer;
38pub mod composer;
39pub mod connection_banner;
39pub mod connection_banner;
40pub mod conversation;
40pub mod conversation;
41pub mod customize_reactions;
41pub mod dialog_overlay;
42pub mod dialog_overlay;
42pub mod emoji_popup;
43pub mod emoji_popup;
43pub mod format_toolbar;
44pub mod format_toolbar;
44pub mod forward_dialog;
45pub mod forward_dialog;
46pub mod find_panel;
45pub mod fun_picker;
47pub mod fun_picker;
48pub mod group_name;
46pub mod image_menu;
49pub mod image_menu;
47pub mod image_viewer;
50pub mod image_viewer;
48pub mod join_dialog;
51pub mod join_dialog;
crates/app/src/views/new_meeting_dialog.rs +16 −2
@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12 12 use gpui_kit::prelude::FluentBuilder as _;
13 13 use gpui_kit::*;
14 14
15 use super::new_chat::NewChatDraft;
15 use super::new_chat::{NewChatDraft, Pick};
16 16 use super::widgets::icon;
17 17 use crate::app_state::AppState;
18 18 use crate::call::{FormValues, Invitee, default_window, draft_from_form};
@@ -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))
@@ -233,7 +234,20 @@ impl Render for MeetingForm {
233 234 }
234 235
235 236 pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
237 open_new_meeting_with(state, Vec::new(), window, cx);
238 }
239
240 pub fn open_new_meeting_with(
241 state: Entity<AppState>,
242 people: Vec<Pick>,
243 window: &mut Window,
244 cx: &mut App,
245 ) {
236 246 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
247 if !people.is_empty() {
248 let draft = form.read(cx).people.clone();
249 draft.update(cx, |draft, cx| draft.set_chips(people, cx));
250 }
237 251 let first_field = form.read(cx).title.clone();
238 252 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239 253 let submit_form = form.clone();
@@ -12,7 +12,7 @@ use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
13use gpui_kit::*;
14
14
15use super::new_chat::NewChatDraft;
15use super::new_chat::{NewChatDraft, Pick};
16use super::widgets::icon;
16use super::widgets::icon;
17use crate::app_state::AppState;
17use crate::app_state::AppState;
18use crate::call::{FormValues, Invitee, default_window, draft_from_form};
18use crate::call::{FormValues, Invitee, default_window, draft_from_form};
@@ -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))
@@ -233,7 +234,20 @@ impl Render for MeetingForm {
233}
234}
234
235
235pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
236pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
237 open_new_meeting_with(state, Vec::new(), window, cx);
238}
239
240pub fn open_new_meeting_with(
241 state: Entity<AppState>,
242 people: Vec<Pick>,
243 window: &mut Window,
244 cx: &mut App,
245) {
236 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
246 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
247 if !people.is_empty() {
248 let draft = form.read(cx).people.clone();
249 draft.update(cx, |draft, cx| draft.set_chips(people, cx));
250 }
237 let first_field = form.read(cx).title.clone();
251 let first_field = form.read(cx).title.clone();
238 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
252 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239 let submit_form = form.clone();
253 let submit_form = form.clone();
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/profile_card.rs +94 −3
@@ -9,6 +9,8 @@ use gpui_kit::*;
9 9 use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10 10
11 11 use super::avatar::{person_avatar, with_presence};
12 use super::new_chat::Pick;
13 use super::new_meeting_dialog::open_new_meeting_with;
12 14 use super::widgets::icon;
13 15 use crate::app_state::{AppHandle, AppState};
14 16 use crate::data::{Presence, PresenceKind, presence_kind_of};
@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;
31 33 const REPORTS_MAX_HEIGHT: f32 = 168.;
32 34 const ACTION_HEIGHT: f32 = 30.;
33 35 const SKELETON_HEIGHT: f32 = 10.;
36 const SCHEDULE_MEETING: &str = "Schedule meeting";
37 const EMAIL: &str = "Email";
38 const COPY_EMAIL: &str = "Copy email";
34 39
35 40 pub enum ProfileCardEvent {
36 41 Close,
@@ -255,25 +260,76 @@ impl ProfileCard {
255 260 .me
256 261 .as_ref()
257 262 .is_some_and(|me| me.user_id == self.user_id);
263 let profile = self
264 .app
265 .read(cx)
266 .profiles
267 .get(&self.user_id)
268 .and_then(|entry| entry.profile.clone());
269 let name = self.display_name(profile.as_deref(), cx);
258 270 let user_id = self.user_id.clone();
259 271 let (mail_email, copy_email) = (email.clone(), email.clone());
272 let invitee = Pick {
273 user_id: user_id.clone(),
274 name: name.clone(),
275 mail: email,
276 };
277 let chat_id = user_id.clone();
278 let (video_id, audio_id) = (user_id.clone(), user_id.clone());
260 279 h_flex()
261 280 .gap(px(8.))
262 281 .when(!is_me, |row| {
263 282 row.child(
264 283 action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
265 284 cx.listener(move |this, _, _, cx| {
266 let user_id = user_id.clone();
285 let user_id = chat_id.clone();
267 286 this.app
268 287 .update(cx, |state, cx| state.open_chat_with(&user_id, cx));
269 288 cx.emit(ProfileCardEvent::Close);
270 289 }),
271 290 ),
272 291 )
292 .child(
293 icon_action(
294 "profile-video-call",
295 IconName::Video,
296 video_call_tooltip(&name),
297 )
298 .on_click(cx.listener(move |this, _, _, cx| {
299 let user_id = video_id.clone();
300 this.app
301 .update(cx, |state, cx| state.call_person(&user_id, true, cx));
302 cx.emit(ProfileCardEvent::Close);
303 })),
304 )
305 .child(
306 icon_action(
307 "profile-audio-call",
308 IconName::Phone,
309 audio_call_tooltip(&name),
310 )
311 .on_click(cx.listener(move |this, _, _, cx| {
312 let user_id = audio_id.clone();
313 this.app
314 .update(cx, |state, cx| state.call_person(&user_id, false, cx));
315 cx.emit(ProfileCardEvent::Close);
316 })),
317 )
318 .child(
319 icon_action(
320 "profile-schedule-meeting",
321 IconName::Calendar,
322 SCHEDULE_MEETING.to_owned(),
323 )
324 .on_click(cx.listener(move |this, _, window, cx| {
325 open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);
326 cx.emit(ProfileCardEvent::Close);
327 })),
328 )
273 329 })
274 330 .when_some(mail_email, |row, address| {
275 331 row.child(
276 action_button("profile-email", "Email", IconName::Mail, false).on_click(
332 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
277 333 cx.listener(move |_, _, _, cx| {
278 334 cx.open_url(&mailto_url(&address));
279 335 cx.emit(ProfileCardEvent::Close);
@@ -283,7 +339,7 @@ impl ProfileCard {
283 339 })
284 340 .when_some(copy_email, |row, address| {
285 341 row.child(
286 action_button("profile-copy-email", "Copy email", IconName::Copy, false)
342 icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())
287 343 .on_click(cx.listener(move |this, _, _, cx| {
288 344 this.app
289 345 .update(cx, |state, cx| state.copy_profile_email(&address, cx));
@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {
557 613 )
558 614 }
559 615
616 pub fn video_call_tooltip(name: &str) -> String {
617 format!("Start a video call with {name}")
618 }
619
620 pub fn audio_call_tooltip(name: &str) -> String {
621 format!("Start an audio call with {name}")
622 }
623
624 fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {
625 div()
626 .id(id)
627 .size(px(ACTION_HEIGHT))
628 .flex()
629 .flex_none()
630 .items_center()
631 .justify_center()
632 .rounded(px(6.))
633 .cursor_pointer()
634 .bg(theme::popup_hover())
635 .hover(|button| button.opacity(0.9))
636 .child(icon(glyph, 14., theme::text_soft()))
637 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
638 }
639
560 640 fn action_button(
561 641 id: &'static str,
562 642 label: &'static str,
@@ -664,3 +744,14 @@ impl Render for ProfileCard {
664 744 )
665 745 }
666 746 }
747
748 #[cfg(test)]
749 mod tests {
750 use super::{audio_call_tooltip, video_call_tooltip};
751
752 #[test]
753 fn call_tooltips_use_the_teams_wording() {
754 assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");
755 assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");
756 }
757 }
@@ -9,6 +9,8 @@ use gpui_kit::*;
9use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
9use teams_core::{OrgPerson, PROFILE_LINK_PREFIX, PersonProfile, WorkLocationKind};
10
10
11use super::avatar::{person_avatar, with_presence};
11use super::avatar::{person_avatar, with_presence};
12use super::new_chat::Pick;
13use super::new_meeting_dialog::open_new_meeting_with;
12use super::widgets::icon;
14use super::widgets::icon;
13use crate::app_state::{AppHandle, AppState};
15use crate::app_state::{AppHandle, AppState};
14use crate::data::{Presence, PresenceKind, presence_kind_of};
16use crate::data::{Presence, PresenceKind, presence_kind_of};
@@ -31,6 +33,9 @@ const STATUS_LINES: usize = 3;
31const REPORTS_MAX_HEIGHT: f32 = 168.;
33const REPORTS_MAX_HEIGHT: f32 = 168.;
32const ACTION_HEIGHT: f32 = 30.;
34const ACTION_HEIGHT: f32 = 30.;
33const SKELETON_HEIGHT: f32 = 10.;
35const SKELETON_HEIGHT: f32 = 10.;
36const SCHEDULE_MEETING: &str = "Schedule meeting";
37const EMAIL: &str = "Email";
38const COPY_EMAIL: &str = "Copy email";
34
39
35pub enum ProfileCardEvent {
40pub enum ProfileCardEvent {
36 Close,
41 Close,
@@ -255,25 +260,76 @@ impl ProfileCard {
255 .me
260 .me
256 .as_ref()
261 .as_ref()
257 .is_some_and(|me| me.user_id == self.user_id);
262 .is_some_and(|me| me.user_id == self.user_id);
263 let profile = self
264 .app
265 .read(cx)
266 .profiles
267 .get(&self.user_id)
268 .and_then(|entry| entry.profile.clone());
269 let name = self.display_name(profile.as_deref(), cx);
258 let user_id = self.user_id.clone();
270 let user_id = self.user_id.clone();
259 let (mail_email, copy_email) = (email.clone(), email.clone());
271 let (mail_email, copy_email) = (email.clone(), email.clone());
272 let invitee = Pick {
273 user_id: user_id.clone(),
274 name: name.clone(),
275 mail: email,
276 };
277 let chat_id = user_id.clone();
278 let (video_id, audio_id) = (user_id.clone(), user_id.clone());
260 h_flex()
279 h_flex()
261 .gap(px(8.))
280 .gap(px(8.))
262 .when(!is_me, |row| {
281 .when(!is_me, |row| {
263 row.child(
282 row.child(
264 action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
283 action_button("profile-chat", "Chat", IconName::MessageSquare, true).on_click(
265 cx.listener(move |this, _, _, cx| {
284 cx.listener(move |this, _, _, cx| {
266 let user_id = user_id.clone();
285 let user_id = chat_id.clone();
267 this.app
286 this.app
268 .update(cx, |state, cx| state.open_chat_with(&user_id, cx));
287 .update(cx, |state, cx| state.open_chat_with(&user_id, cx));
269 cx.emit(ProfileCardEvent::Close);
288 cx.emit(ProfileCardEvent::Close);
270 }),
289 }),
271 ),
290 ),
272 )
291 )
292 .child(
293 icon_action(
294 "profile-video-call",
295 IconName::Video,
296 video_call_tooltip(&name),
297 )
298 .on_click(cx.listener(move |this, _, _, cx| {
299 let user_id = video_id.clone();
300 this.app
301 .update(cx, |state, cx| state.call_person(&user_id, true, cx));
302 cx.emit(ProfileCardEvent::Close);
303 })),
304 )
305 .child(
306 icon_action(
307 "profile-audio-call",
308 IconName::Phone,
309 audio_call_tooltip(&name),
310 )
311 .on_click(cx.listener(move |this, _, _, cx| {
312 let user_id = audio_id.clone();
313 this.app
314 .update(cx, |state, cx| state.call_person(&user_id, false, cx));
315 cx.emit(ProfileCardEvent::Close);
316 })),
317 )
318 .child(
319 icon_action(
320 "profile-schedule-meeting",
321 IconName::Calendar,
322 SCHEDULE_MEETING.to_owned(),
323 )
324 .on_click(cx.listener(move |this, _, window, cx| {
325 open_new_meeting_with(this.app.clone(), vec![invitee.clone()], window, cx);
326 cx.emit(ProfileCardEvent::Close);
327 })),
328 )
273 })
329 })
274 .when_some(mail_email, |row, address| {
330 .when_some(mail_email, |row, address| {
275 row.child(
331 row.child(
276 action_button("profile-email", "Email", IconName::Mail, false).on_click(
332 icon_action("profile-email", IconName::Mail, EMAIL.to_owned()).on_click(
277 cx.listener(move |_, _, _, cx| {
333 cx.listener(move |_, _, _, cx| {
278 cx.open_url(&mailto_url(&address));
334 cx.open_url(&mailto_url(&address));
279 cx.emit(ProfileCardEvent::Close);
335 cx.emit(ProfileCardEvent::Close);
@@ -283,7 +339,7 @@ impl ProfileCard {
283 })
339 })
284 .when_some(copy_email, |row, address| {
340 .when_some(copy_email, |row, address| {
285 row.child(
341 row.child(
286 action_button("profile-copy-email", "Copy email", IconName::Copy, false)
342 icon_action("profile-copy-email", IconName::Copy, COPY_EMAIL.to_owned())
287 .on_click(cx.listener(move |this, _, _, cx| {
343 .on_click(cx.listener(move |this, _, _, cx| {
288 this.app
344 this.app
289 .update(cx, |state, cx| state.copy_profile_email(&address, cx));
345 .update(cx, |state, cx| state.copy_profile_email(&address, cx));
@@ -557,6 +613,30 @@ fn contact_row(row: ContactRow) -> Div {
557 )
613 )
558}
614}
559
615
616pub fn video_call_tooltip(name: &str) -> String {
617 format!("Start a video call with {name}")
618}
619
620pub fn audio_call_tooltip(name: &str) -> String {
621 format!("Start an audio call with {name}")
622}
623
624fn icon_action(id: &'static str, glyph: IconName, tooltip: String) -> Stateful<Div> {
625 div()
626 .id(id)
627 .size(px(ACTION_HEIGHT))
628 .flex()
629 .flex_none()
630 .items_center()
631 .justify_center()
632 .rounded(px(6.))
633 .cursor_pointer()
634 .bg(theme::popup_hover())
635 .hover(|button| button.opacity(0.9))
636 .child(icon(glyph, 14., theme::text_soft()))
637 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
638}
639
560fn action_button(
640fn action_button(
561 id: &'static str,
641 id: &'static str,
562 label: &'static str,
642 label: &'static str,
@@ -664,3 +744,14 @@ impl Render for ProfileCard {
664 )
744 )
665 }
745 }
666}
746}
747
748#[cfg(test)]
749mod tests {
750 use super::{audio_call_tooltip, video_call_tooltip};
751
752 #[test]
753 fn call_tooltips_use_the_teams_wording() {
754 assert_eq!(video_call_tooltip("Ann"), "Start a video call with Ann");
755 assert_eq!(audio_call_tooltip("Ann"), "Start an audio call with Ann");
756 }
757}
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/reaction_picker.rs +60 −8
@@ -10,7 +10,12 @@ use gpui_kit::component::{
10 10 use gpui_kit::prelude::FluentBuilder as _;
11 11 use gpui_kit::*;
12 12
13 use gpui_kit::assets::IconName;
14 use gpui_kit::component::tooltip::Tooltip;
15
16 use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};
13 17 use super::skin_tone_choices::{tone_badge, tone_choices};
18 use super::widgets::icon;
14 19 use crate::app_state::AppState;
15 20 use crate::emoji;
16 21 use crate::emoticons;
@@ -67,6 +72,7 @@ pub struct ReactionPicker {
67 72 target: Option<PickTarget>,
68 73 skin_tone: u8,
69 74 tone_menu: Option<(String, Point<Pixels>)>,
75 customizing: bool,
70 76 _subscription: Subscription,
71 77 }
72 78
@@ -88,10 +94,16 @@ impl ReactionPicker {
88 94 target: None,
89 95 skin_tone: 0,
90 96 tone_menu: None,
97 customizing: false,
91 98 _subscription: subscription,
92 99 }
93 100 }
94 101
102 pub fn for_customizing(mut self) -> Self {
103 self.customizing = true;
104 self
105 }
106
95 107 pub fn set_target(
96 108 &mut self,
97 109 on_pick: PickHandler,
@@ -195,10 +207,43 @@ impl ReactionPicker {
195 207
196 208 fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
197 209 self.skin_tone = tone;
198 self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
210 if !self.customizing {
211 self.app
212 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
213 }
199 214 self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
200 215 }
201 216
217 fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {
218 if let Some(target) = self.target.take() {
219 target
220 .popover
221 .update(cx, |state, cx| state.dismiss(window, cx))
222 .ok();
223 (target.on_done)(window, cx);
224 }
225 open_customize_reactions(self.app.clone(), window, cx);
226 }
227
228 fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
229 (!self.customizing).then(|| {
230 div()
231 .id("customize-reactions-trigger")
232 .size(px(CELL_SIZE))
233 .flex_none()
234 .flex()
235 .items_center()
236 .justify_center()
237 .rounded(px(8.))
238 .cursor_pointer()
239 .hover(|button| button.bg(theme::popup_hover()))
240 .child(icon(IconName::Settings, 16., theme::text_soft()))
241 .tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))
242 .on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))
243 .into_any_element()
244 })
245 }
246
202 247 fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
203 248 let (base, position) = self.tone_menu.clone()?;
204 249 let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
@@ -303,14 +348,21 @@ impl Render for ReactionPicker {
303 348 .p(px(8.))
304 349 .child(h_flex().gap(px(2.)).children(quick))
305 350 .child(
306 div()
307 .h(px(32.))
308 .px(px(8.))
309 .flex()
351 h_flex()
352 .gap(px(4.))
310 353 .items_center()
311 .rounded(px(8.))
312 .bg(theme::popup_hover())
313 .child(Input::new(&self.input).appearance(false).bordered(false)),
354 .child(
355 div()
356 .flex_1()
357 .h(px(32.))
358 .px(px(8.))
359 .flex()
360 .items_center()
361 .rounded(px(8.))
362 .bg(theme::popup_hover())
363 .child(Input::new(&self.input).appearance(false).bordered(false)),
364 )
365 .children(self.customize_button(cx)),
314 366 )
315 367 .child(
316 368 div()
@@ -10,7 +10,12 @@ use gpui_kit::component::{
10use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
11use gpui_kit::*;
12
12
13use gpui_kit::assets::IconName;
14use gpui_kit::component::tooltip::Tooltip;
15
16use super::customize_reactions::{CUSTOMIZE_TOOLTIP, open_customize_reactions};
13use super::skin_tone_choices::{tone_badge, tone_choices};
17use super::skin_tone_choices::{tone_badge, tone_choices};
18use super::widgets::icon;
14use crate::app_state::AppState;
19use crate::app_state::AppState;
15use crate::emoji;
20use crate::emoji;
16use crate::emoticons;
21use crate::emoticons;
@@ -67,6 +72,7 @@ pub struct ReactionPicker {
67 target: Option<PickTarget>,
72 target: Option<PickTarget>,
68 skin_tone: u8,
73 skin_tone: u8,
69 tone_menu: Option<(String, Point<Pixels>)>,
74 tone_menu: Option<(String, Point<Pixels>)>,
75 customizing: bool,
70 _subscription: Subscription,
76 _subscription: Subscription,
71}
77}
72
78
@@ -88,10 +94,16 @@ impl ReactionPicker {
88 target: None,
94 target: None,
89 skin_tone: 0,
95 skin_tone: 0,
90 tone_menu: None,
96 tone_menu: None,
97 customizing: false,
91 _subscription: subscription,
98 _subscription: subscription,
92 }
99 }
93 }
100 }
94
101
102 pub fn for_customizing(mut self) -> Self {
103 self.customizing = true;
104 self
105 }
106
95 pub fn set_target(
107 pub fn set_target(
96 &mut self,
108 &mut self,
97 on_pick: PickHandler,
109 on_pick: PickHandler,
@@ -195,10 +207,43 @@ impl ReactionPicker {
195
207
196 fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
208 fn pick_tone(&mut self, glyph: &str, tone: u8, window: &mut Window, cx: &mut Context<Self>) {
197 self.skin_tone = tone;
209 self.skin_tone = tone;
198 self.app.update(cx, |state, cx| state.set_skin_tone(tone, cx));
210 if !self.customizing {
211 self.app
212 .update(cx, |state, cx| state.set_skin_tone(tone, cx));
213 }
199 self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
214 self.pick(&emoticons::with_tone(glyph, tone), false, window, cx);
200 }
215 }
201
216
217 fn open_customize(&mut self, window: &mut Window, cx: &mut Context<Self>) {
218 if let Some(target) = self.target.take() {
219 target
220 .popover
221 .update(cx, |state, cx| state.dismiss(window, cx))
222 .ok();
223 (target.on_done)(window, cx);
224 }
225 open_customize_reactions(self.app.clone(), window, cx);
226 }
227
228 fn customize_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
229 (!self.customizing).then(|| {
230 div()
231 .id("customize-reactions-trigger")
232 .size(px(CELL_SIZE))
233 .flex_none()
234 .flex()
235 .items_center()
236 .justify_center()
237 .rounded(px(8.))
238 .cursor_pointer()
239 .hover(|button| button.bg(theme::popup_hover()))
240 .child(icon(IconName::Settings, 16., theme::text_soft()))
241 .tooltip(|window, cx| Tooltip::new(CUSTOMIZE_TOOLTIP).build(window, cx))
242 .on_click(cx.listener(|this, _, window, cx| this.open_customize(window, cx)))
243 .into_any_element()
244 })
245 }
246
202 fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
247 fn tone_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
203 let (base, position) = self.tone_menu.clone()?;
248 let (base, position) = self.tone_menu.clone()?;
204 let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
249 let (pick_view, dismiss_view) = (cx.entity().downgrade(), cx.entity().downgrade());
@@ -303,14 +348,21 @@ impl Render for ReactionPicker {
303 .p(px(8.))
348 .p(px(8.))
304 .child(h_flex().gap(px(2.)).children(quick))
349 .child(h_flex().gap(px(2.)).children(quick))
305 .child(
350 .child(
306 div()
351 h_flex()
307 .h(px(32.))
352 .gap(px(4.))
308 .px(px(8.))
309 .flex()
310 .items_center()
353 .items_center()
311 .rounded(px(8.))
354 .child(
312 .bg(theme::popup_hover())
355 div()
313 .child(Input::new(&self.input).appearance(false).bordered(false)),
356 .flex_1()
357 .h(px(32.))
358 .px(px(8.))
359 .flex()
360 .items_center()
361 .rounded(px(8.))
362 .bg(theme::popup_hover())
363 .child(Input::new(&self.input).appearance(false).bordered(false)),
364 )
365 .children(self.customize_button(cx)),
314 )
366 )
315 .child(
367 .child(
316 div()
368 div()
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/shell.rs +41 −3
@@ -17,10 +17,12 @@ use super::prejoin_view::PrejoinView;
17 17 use super::profile_card::{ProfileCard, ProfileCardEvent};
18 18 use gpui_kit::prelude::FluentBuilder as _;
19 19 use super::rail::RailView;
20 use crate::chat_filter::ChatFilterPill;
20 21 use super::saved_panel::{SavedPanel, SavedPanelEvent};
21 22 use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 28 ZoomShareReset,
@@ -28,7 +30,7 @@ use super::shortcuts::{
28 30 use super::window_zoom::{WindowZoom, change_zoom};
29 31 use super::call_pop_out::zoom_listener;
30 32 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
31 use super::sidebar::SidebarView;
33 use super::sidebar::{SidebarEvent, SidebarView};
32 34 use app_ui_kit::render::hooks::RenderHooks;
33 35 use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
34 36 use super::connection_banner::render_connection_banner;
@@ -138,6 +140,7 @@ pub struct AppShell {
138 140 call_mini: Entity<CallMiniView>,
139 141 _call_media_observation: Subscription,
140 142 _panel_subscriptions: [Subscription; 2],
143 _sidebar_subscription: Subscription,
141 144 _agents_subscription: Option<Subscription>,
142 145 _agent_subscription: Option<Subscription>,
143 146 _escape_observation: Subscription,
@@ -251,6 +254,9 @@ impl AppShell {
251 254 )
252 255 });
253 256 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
257 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, _: &SidebarEvent, window, cx| {
258 this.restore_focus(window, cx);
259 });
254 260 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
255 261 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
256 262 let timeline = conversation.read(cx).timeline_bounds();
@@ -332,6 +338,7 @@ impl AppShell {
332 338 call_mini,
333 339 _call_media_observation: call_media_observation,
334 340 _panel_subscriptions: panel_subscriptions,
341 _sidebar_subscription: sidebar_subscription,
335 342 _agents_subscription: agents_subscription,
336 343 _agent_subscription: agent_subscription,
337 344 _escape_observation: escape_observation,
@@ -968,6 +975,36 @@ impl Render for AppShell {
968 975 this.sidebar
969 976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
970 977 }))
978 .on_action(cx.listener(|this, _: &FindInChat, window, cx| {
979 this.close_image_viewer(window, cx);
980 this.conversation
981 .update(cx, |conversation, cx| conversation.open_find(window, cx));
982 }))
983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
984 this.close_image_viewer(window, cx);
985 this.sidebar
986 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
987 }))
988 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
989 this.sidebar
990 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
991 }))
992 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
993 this.sidebar
994 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
995 }))
996 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
997 this.sidebar
998 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
999 }))
1000 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1001 this.sidebar
1002 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1003 }))
1004 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1005 this.sidebar
1006 .update(cx, |sidebar, cx| sidebar.clear_filters(window, cx));
1007 }))
971 1008 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
972 1009 this.close_image_viewer(window, cx);
973 1010 this.sidebar
@@ -1061,6 +1098,7 @@ impl Render for AppShell {
1061 1098 .text_size(px(14.))
1062 1099 .child(crate::frame_log::probe("first"))
1063 1100 .child(user_activity::input_probe(self.user_input.clone()))
1101 .child(app_ui_kit::long_press::long_press_right_click())
1064 1102 .child(
1065 1103 v_flex()
1066 1104 .debug_selector(|| "shell".into())
@@ -17,10 +17,12 @@ use super::prejoin_view::PrejoinView;
17use super::profile_card::{ProfileCard, ProfileCardEvent};
17use super::profile_card::{ProfileCard, ProfileCardEvent};
18use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::prelude::FluentBuilder as _;
19use super::rail::RailView;
19use super::rail::RailView;
20use crate::chat_filter::ChatFilterPill;
20use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::saved_panel::{SavedPanel, SavedPanelEvent};
21use super::shortcuts::{
22use super::shortcuts::{
22 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
23 AcceptCall, ClearChatFilters, DeclineCall, FilterMeetingChats, FilterMutedChats,
23 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 FilterNonMeetingChats, FilterUnreadChats, FindInChat, HangUpCall, JoinMeetingFromToast, JumpToLastReadOrNewest, NextConversation, OpenActivity,
25 OpenAgents, OpenCallsTab, OpenSettings, OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
24 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
26 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
25 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
27 ToggleCallHand, ToggleCallShare, ZoomIn, ZoomOut, ZoomReset, ZoomShareIn, ZoomShareOut,
26 ZoomShareReset,
28 ZoomShareReset,
@@ -28,7 +30,7 @@ use super::shortcuts::{
28use super::window_zoom::{WindowZoom, change_zoom};
30use super::window_zoom::{WindowZoom, change_zoom};
29use super::call_pop_out::zoom_listener;
31use super::call_pop_out::zoom_listener;
30use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
32use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
31use super::sidebar::SidebarView;
33use super::sidebar::{SidebarEvent, SidebarView};
32use app_ui_kit::render::hooks::RenderHooks;
34use app_ui_kit::render::hooks::RenderHooks;
33use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
35use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
34use super::connection_banner::render_connection_banner;
36use super::connection_banner::render_connection_banner;
@@ -138,6 +140,7 @@ pub struct AppShell {
138 call_mini: Entity<CallMiniView>,
140 call_mini: Entity<CallMiniView>,
139 _call_media_observation: Subscription,
141 _call_media_observation: Subscription,
140 _panel_subscriptions: [Subscription; 2],
142 _panel_subscriptions: [Subscription; 2],
143 _sidebar_subscription: Subscription,
141 _agents_subscription: Option<Subscription>,
144 _agents_subscription: Option<Subscription>,
142 _agent_subscription: Option<Subscription>,
145 _agent_subscription: Option<Subscription>,
143 _escape_observation: Subscription,
146 _escape_observation: Subscription,
@@ -251,6 +254,9 @@ impl AppShell {
251 )
254 )
252 });
255 });
253 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
256 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, agents_panel, cx));
257 let sidebar_subscription = cx.subscribe_in(&sidebar, window, |this, _, _: &SidebarEvent, window, cx| {
258 this.restore_focus(window, cx);
259 });
254 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
260 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
255 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
261 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
256 let timeline = conversation.read(cx).timeline_bounds();
262 let timeline = conversation.read(cx).timeline_bounds();
@@ -332,6 +338,7 @@ impl AppShell {
332 call_mini,
338 call_mini,
333 _call_media_observation: call_media_observation,
339 _call_media_observation: call_media_observation,
334 _panel_subscriptions: panel_subscriptions,
340 _panel_subscriptions: panel_subscriptions,
341 _sidebar_subscription: sidebar_subscription,
335 _agents_subscription: agents_subscription,
342 _agents_subscription: agents_subscription,
336 _agent_subscription: agent_subscription,
343 _agent_subscription: agent_subscription,
337 _escape_observation: escape_observation,
344 _escape_observation: escape_observation,
@@ -968,6 +975,36 @@ impl Render for AppShell {
968 this.sidebar
975 this.sidebar
969 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
976 .update(cx, |sidebar, cx| sidebar.show_chats(cx));
970 }))
977 }))
978 .on_action(cx.listener(|this, _: &FindInChat, window, cx| {
979 this.close_image_viewer(window, cx);
980 this.conversation
981 .update(cx, |conversation, cx| conversation.open_find(window, cx));
982 }))
983 .on_action(cx.listener(|this, _: &OpenChatFilter, window, cx| {
984 this.close_image_viewer(window, cx);
985 this.sidebar
986 .update(cx, |sidebar, cx| sidebar.toggle_filter_box(window, cx));
987 }))
988 .on_action(cx.listener(|this, _: &FilterUnreadChats, _, cx| {
989 this.sidebar
990 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Unread, cx));
991 }))
992 .on_action(cx.listener(|this, _: &FilterNonMeetingChats, _, cx| {
993 this.sidebar
994 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Chats, cx));
995 }))
996 .on_action(cx.listener(|this, _: &FilterMeetingChats, _, cx| {
997 this.sidebar
998 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Meetings, cx));
999 }))
1000 .on_action(cx.listener(|this, _: &FilterMutedChats, _, cx| {
1001 this.sidebar
1002 .update(cx, |sidebar, cx| sidebar.toggle_pill(ChatFilterPill::Muted, cx));
1003 }))
1004 .on_action(cx.listener(|this, _: &ClearChatFilters, window, cx| {
1005 this.sidebar
1006 .update(cx, |sidebar, cx| sidebar.clear_filters(window, cx));
1007 }))
971 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
1008 .on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
972 this.close_image_viewer(window, cx);
1009 this.close_image_viewer(window, cx);
973 this.sidebar
1010 this.sidebar
@@ -1061,6 +1098,7 @@ impl Render for AppShell {
1061 .text_size(px(14.))
1098 .text_size(px(14.))
1062 .child(crate::frame_log::probe("first"))
1099 .child(crate::frame_log::probe("first"))
1063 .child(user_activity::input_probe(self.user_input.clone()))
1100 .child(user_activity::input_probe(self.user_input.clone()))
1101 .child(app_ui_kit::long_press::long_press_right_click())
1064 .child(
1102 .child(
1065 v_flex()
1103 v_flex()
1066 .debug_selector(|| "shell".into())
1104 .debug_selector(|| "shell".into())
crates/app/src/views/shortcuts.rs +14 −0
@@ -29,6 +29,13 @@ actions!(
29 29 OpenSaved,
30 30 OpenCallsTab,
31 31 OpenAgents,
32 OpenChatFilter,
33 FindInChat,
34 FilterUnreadChats,
35 FilterNonMeetingChats,
36 FilterMeetingChats,
37 FilterMutedChats,
38 ClearChatFilters,
32 39 PreviousConversation,
33 40 NextConversation,
34 41 JumpToLastReadOrNewest,
@@ -129,6 +136,13 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 136 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
130 137 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
131 138 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
139 shortcut!(Navigation, GlobalOverTextFields, "Open filter", "ctrl-shift-f", Some("cmd-shift-f"), OpenChatFilter),
140 shortcut!(Navigation, OutsideTextFields, "Filter chat list by unread chats only", "ctrl-alt-u", None, FilterUnreadChats),
141 shortcut!(Navigation, OutsideTextFields, "Filter chat list by chats only", "ctrl-alt-c", None, FilterNonMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
144 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
145 shortcut!(Composer, GlobalOverTextFields, "Find in chat", "ctrl-f", Some("cmd-f"), FindInChat),
132 146 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 147 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
134 148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
@@ -29,6 +29,13 @@ actions!(
29 OpenSaved,
29 OpenSaved,
30 OpenCallsTab,
30 OpenCallsTab,
31 OpenAgents,
31 OpenAgents,
32 OpenChatFilter,
33 FindInChat,
34 FilterUnreadChats,
35 FilterNonMeetingChats,
36 FilterMeetingChats,
37 FilterMutedChats,
38 ClearChatFilters,
32 PreviousConversation,
39 PreviousConversation,
33 NextConversation,
40 NextConversation,
34 JumpToLastReadOrNewest,
41 JumpToLastReadOrNewest,
@@ -129,6 +136,13 @@ pub const SHORTCUTS: &[Shortcut] = &[
129 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
136 shortcut!(Navigation, GlobalOverTextFields, "Open Agents", "ctrl-6", Some("cmd-6"), OpenAgents),
130 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
137 shortcut!(Navigation, GlobalOverTextFields, "Previous chat or channel", "alt-up", None, PreviousConversation),
131 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
138 shortcut!(Navigation, GlobalOverTextFields, "Next chat or channel", "alt-down", None, NextConversation),
139 shortcut!(Navigation, GlobalOverTextFields, "Open filter", "ctrl-shift-f", Some("cmd-shift-f"), OpenChatFilter),
140 shortcut!(Navigation, OutsideTextFields, "Filter chat list by unread chats only", "ctrl-alt-u", None, FilterUnreadChats),
141 shortcut!(Navigation, OutsideTextFields, "Filter chat list by chats only", "ctrl-alt-c", None, FilterNonMeetingChats),
142 shortcut!(Navigation, OutsideTextFields, "Filter chat list by meeting chats only", "ctrl-alt-b", None, FilterMeetingChats),
143 shortcut!(Navigation, OutsideTextFields, "Filter chat list by muted chats only", "ctrl-alt-q", None, FilterMutedChats),
144 shortcut!(Navigation, OutsideTextFields, "Remove all filters in the chat list", "ctrl-alt-z", None, ClearChatFilters),
145 shortcut!(Composer, GlobalOverTextFields, "Find in chat", "ctrl-f", Some("cmd-f"), FindInChat),
132 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
146 shortcut!(Composer, Global, "Reply to the message under the pointer", "alt-r", None, ReplyToHovered),
133 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
147 shortcut!(Composer, Global, "Jump to last read or newest message", "ctrl-j", Some("cmd-j"), JumpToLastReadOrNewest),
134 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
148 shortcut!(Composer, Composer, "Bold", "ctrl-b", Some("cmd-b"), ToggleBold),
crates/app/src/views/sidebar.rs +282 −27
@@ -14,7 +14,7 @@ use store::{
14 14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
15 15 Store, TeamRecord,
16 16 };
17 use teams_core::is_notes_chat;
17 use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
18 18
19 19 use super::activity_panel::ActivityPanel;
20 20 use super::avatar::{spec_avatar, square_avatar, with_presence};
@@ -22,10 +22,14 @@ use super::calls_tab::calls_body;
22 22 use super::saved_panel::SavedPanel;
23 23 use super::scroll_edge::with_top_edge;
24 24 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
25 use super::widgets::{count_badge, icon, page_header, symbol, unread_marker};
25 use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
26 26 use crate::agents::AgentsPanel;
27 27 use crate::app_state::{AppEvent, AppState, Selection};
28 use crate::channel_menu::{
29 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
30 };
28 31 use crate::chat_actions::TITLE_LIMIT;
32 use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
29 33 use crate::data::{Directory, is_pending_folder};
30 34 use crate::format;
31 35 use crate::local_previews::LocalPreview;
@@ -39,6 +43,9 @@ use crate::sidebar_model::{
39 43 };
40 44 use crate::theme;
41 45 use app_ui_kit::layout::SIDEBAR_WIDTH;
46 use gpui_kit::component::input::InputState;
47
48 pub(crate) mod chat_filter_bar;
42 49
43 50 pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
44 51 const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -61,7 +68,6 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
61 68 const TEAM_ROW_HEIGHT: f32 = 40.;
62 69 const REVEAL_ROW_HEIGHT: f32 = 32.;
63 70 const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
64 const MENU_ICON_SIZE: f32 = 15.;
65 71 const NOTIFICATION_ICON_SIZE: f32 = 13.;
66 72 const MENTION_ICON_SIZE: f32 = 15.;
67 73 const IMPORTANCE_MARKER_SIZE: f32 = 16.;
@@ -89,6 +95,10 @@ impl SidebarTab {
89 95 }
90 96 }
91 97
98 pub fn chat_row_selector(chat_id: &str) -> String {
99 format!("chat-row/{chat_id}")
100 }
101
92 102 #[derive(Clone)]
93 103 struct DraggedChat {
94 104 id: String,
@@ -130,10 +140,6 @@ struct MenuContext {
130 140 folders: Vec<(String, String)>,
131 141 }
132 142
133 fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
134 icon(name, MENU_ICON_SIZE, theme::text_muted())
135 }
136
137 143 fn chat_menu(
138 144 popup: PopupMenu,
139 145 window: &mut Window,
@@ -214,18 +220,18 @@ fn chat_menu(
214 220 if notes {
215 221 return popup;
216 222 }
217 popup = popup
218 .item(
219 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
220 .icon(menu_icon(if muted {
221 IconName::Bell
222 } else {
223 IconName::BellOff
224 }))
225 .on_click(move |_, _, cx| {
226 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
227 }),
228 )
223 popup = popup.item(
224 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
225 .icon(menu_icon(if muted {
226 IconName::Bell
227 } else {
228 IconName::BellOff
229 }))
230 .on_click(move |_, _, cx| {
231 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
232 }),
233 );
234 popup = chat_notifications_submenu(popup, window, cx, context, target)
229 235 .separator()
230 236 .item(
231 237 PopupMenuItem::new("Hide")
@@ -234,6 +240,17 @@ fn chat_menu(
234 240 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
235 241 }),
236 242 );
243 if !target.is_group {
244 let remove_state = context.state.clone();
245 let remove_id = target.id.clone();
246 popup = popup.item(
247 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
248 .icon(menu_icon(IconName::Trash))
249 .on_click(move |_, window, cx| {
250 confirm_remove_history(&remove_state, &remove_id, window, cx);
251 }),
252 );
253 }
237 254 if target.is_group {
238 255 let leave_state = context.state.clone();
239 256 let leave_id = target.id.clone();
@@ -243,7 +260,7 @@ fn chat_menu(
243 260 PopupMenuItem::element(|_, _| {
244 261 div().text_color(theme::red_soft()).child("Leave chat...")
245 262 })
246 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
263 .icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))
247 264 .on_click(move |_, window, cx| {
248 265 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
249 266 }),
@@ -252,6 +269,76 @@ fn chat_menu(
252 269 popup
253 270 }
254 271
272 const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [
273 ("All new messages", ChatNotificationMode::AllNewMessages),
274 ("Mute", ChatNotificationMode::Mute),
275 ];
276
277 const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
278 (
279 "Match settings used for all chats",
280 DesktopNotifications::MatchAllChats,
281 ),
282 ("Don't get desktop notifications", DesktopNotifications::Off),
283 ];
284
285 fn chat_notifications_submenu(
286 popup: PopupMenu,
287 window: &mut Window,
288 cx: &mut Context<PopupMenu>,
289 context: &MenuContext,
290 target: &ChatMenuTarget,
291 ) -> PopupMenu {
292 let state = context.state.clone();
293 let chat_id = target.id.clone();
294 let mode = if target.muted {
295 ChatNotificationMode::Mute
296 } else {
297 ChatNotificationMode::AllNewMessages
298 };
299 let desktop = state.read(cx).chat_desktop_notifications(&chat_id);
300 popup.submenu_with_icon(
301 Some(menu_icon(IconName::Bell)),
302 "Manage notifications",
303 window,
304 cx,
305 move |submenu, _, _| {
306 let choose = |chosen_mode: ChatNotificationMode,
307 chosen_desktop: DesktopNotifications| {
308 let (state, chat_id) = (state.clone(), chat_id.clone());
309 move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
310 state.update(cx, |state, cx| {
311 state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)
312 });
313 }
314 };
315 let submenu = submenu.label("Chat notification mode");
316 let submenu =
317 CHAT_NOTIFICATION_MODES
318 .iter()
319 .fold(submenu, |submenu, (label, value)| {
320 submenu.item(
321 PopupMenuItem::new(*label)
322 .checked(*value == mode)
323 .on_click(choose(*value, desktop)),
324 )
325 });
326 let submenu = submenu
327 .separator()
328 .label("Set a desktop notification preference");
329 DESKTOP_NOTIFICATIONS
330 .iter()
331 .fold(submenu, |submenu, (label, value)| {
332 submenu.item(
333 PopupMenuItem::new(*label)
334 .checked(*value == desktop)
335 .on_click(choose(mode, *value)),
336 )
337 })
338 },
339 )
340 }
341
255 342 #[derive(Clone)]
256 343 struct SectionMenuTarget {
257 344 id: String,
@@ -394,7 +481,7 @@ fn section_menu(
394 481 PopupMenuItem::element(|_, _| {
395 482 div().text_color(theme::red_soft()).child("Delete section")
396 483 })
397 .icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
484 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
398 485 .disabled(target.read_only)
399 486 .on_click(move |_, window, cx| {
400 487 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
@@ -445,6 +532,40 @@ fn leave_description(member_count: usize) -> String {
445 532 format!("{who} {verb} that you left. You can only come back if someone adds you.")
446 533 }
447 534
535 const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
536 const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
537 const REMOVE_HISTORY_TEXT: &str =
538 "This will remove the chat from your list and search. It affects you only.";
539
540 fn confirm_remove_history(
541 state: &Entity<AppState>,
542 chat_id: &str,
543 window: &mut Window,
544 cx: &mut App,
545 ) {
546 let state = state.clone();
547 let chat_id = chat_id.to_owned();
548 window.open_alert_dialog(cx, move |alert, _, _| {
549 let state = state.clone();
550 let chat_id = chat_id.clone();
551 let cancel = Button::new("remove-history-cancel")
552 .label("Cancel")
553 .on_click(|_, window, cx| window.close_dialog(cx));
554 let remove = Button::new("remove-history-confirm")
555 .label("Remove")
556 .primary()
557 .on_click(move |_, window, cx| {
558 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
559 window.close_dialog(cx);
560 });
561 alert
562 .title(REMOVE_HISTORY_TITLE)
563 .description(REMOVE_HISTORY_TEXT)
564 .footer(DialogFooter::new().child(cancel).child(remove))
565 .on_ok(|_, _, _| false)
566 });
567 }
568
448 569 pub(crate) fn confirm_leave(
449 570 state: &Entity<AppState>,
450 571 chat_id: &str,
@@ -478,6 +599,12 @@ pub(crate) fn confirm_leave(
478 599 });
479 600 }
480 601
602 pub enum SidebarEvent {
603 RestoreFocus,
604 }
605
606 impl EventEmitter<SidebarEvent> for SidebarView {}
607
481 608 pub struct SidebarView {
482 609 state: Entity<AppState>,
483 610 tab: SidebarTab,
@@ -492,6 +619,12 @@ pub struct SidebarView {
492 619 older_chats_seen: Cell<(bool, bool)>,
493 620 channels_scroll: ScrollHandle,
494 621 calls_scroll: ScrollHandle,
622 chat_filter: ChatFilter,
623 filter_box_open: bool,
624 more_filters_open: bool,
625 filter_input: Option<Entity<InputState>>,
626 filter_subscription: Option<Subscription>,
627 _activity_observation: Subscription,
495 628 _subscription: Subscription,
496 629 _state_observation: Subscription,
497 630 _agent_observation: Option<Subscription>,
@@ -582,6 +715,15 @@ impl SidebarView {
582 715 SidebarTab::Chats
583 716 };
584 717 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
718 let activity = activity_panel.read(cx).activity();
719 let activity_observation = cx.observe(&activity, |view, _, cx| {
720 if view
721 .chat_filter
722 .has(crate::chat_filter::ChatFilterPill::Mentions)
723 {
724 cx.notify();
725 }
726 });
585 727 cx.spawn(async move |this, cx| {
586 728 loop {
587 729 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -610,6 +752,12 @@ impl SidebarView {
610 752 older_chats_seen: Cell::new((false, false)),
611 753 channels_scroll: ScrollHandle::new(),
612 754 calls_scroll: ScrollHandle::new(),
755 chat_filter: ChatFilter::default(),
756 filter_box_open: false,
757 more_filters_open: false,
758 filter_input: None,
759 filter_subscription: None,
760 _activity_observation: activity_observation,
613 761 _subscription: subscription,
614 762 _state_observation: state_observation,
615 763 _agent_observation: agent_observation,
@@ -1047,6 +1195,7 @@ impl SidebarView {
1047 1195 };
1048 1196 h_flex()
1049 1197 .id(SharedString::from(format!("chat-{}", item.id)))
1198 .debug_selector(|| chat_row_selector(&item.id))
1050 1199 .mx(px(6.))
1051 1200 .h(px(ROW_HEIGHT))
1052 1201 .flex_none()
@@ -1097,7 +1246,18 @@ impl SidebarView {
1097 1246 now,
1098 1247 offset,
1099 1248 };
1100 let sections = build_sections(&input);
1249 let sections = if self.chat_filter.is_active() {
1250 let mentioned = self.mentioned_chats(cx);
1251 let selected_id = self.selected_chat_id(cx);
1252 filtered_sections(
1253 &input,
1254 &self.chat_filter,
1255 &mentioned,
1256 selected_id.as_deref(),
1257 )
1258 } else {
1259 build_sections(&input)
1260 };
1101 1261 let menu = MenuContext {
1102 1262 state: self.state.clone(),
1103 1263 folders: state.directory.move_targets(),
@@ -1222,6 +1382,10 @@ impl SidebarView {
1222 1382 .child(LOADING_OLDER_LABEL),
1223 1383 );
1224 1384 }
1385 let selected_chat_id = self.selected_chat_id(cx);
1386 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1387 list = list.child(self.filter_empty_state(cx));
1388 }
1225 1389 list = with_spacer(list, &mut skipped_height);
1226 1390 self.request_lazy_data(faces, presence_users, cx);
1227 1391 let scroll_area = div()
@@ -1378,6 +1542,8 @@ impl SidebarView {
1378 1542 let name_style = team_name_style(entry, expanded);
1379 1543 let badge = team_badge(entry, expanded);
1380 1544 let toggle_id = team_id.clone();
1545 let (team_menu_state, team_menu_id, team_hidden) =
1546 (self.state.clone(), team_id.clone(), entry.hidden);
1381 1547 list = list.child(
1382 1548 h_flex()
1383 1549 .id(SharedString::from(format!("team-{team_id}")))
@@ -1417,7 +1583,10 @@ impl SidebarView {
1417 1583 }
1418 1584 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1419 1585 cx.notify();
1420 })),
1586 }))
1587 .context_menu(move |popup, _, _| {
1588 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1589 }),
1421 1590 );
1422 1591 if !expanded {
1423 1592 return list;
@@ -1702,7 +1871,87 @@ fn channel_menu(
1702 1871 channel_id: &str,
1703 1872 notifications: ChannelNotifications,
1704 1873 ) -> PopupMenu {
1705 let channel_id = channel_id.to_owned();
1874 let menu_state = state.read(cx).channel_menu_state(channel_id);
1875 let mut popup = popup;
1876 for entry in channel_menu_entries(menu_state) {
1877 let item = match entry {
1878 MenuEntry::Separator => {
1879 popup = popup.separator();
1880 continue;
1881 }
1882 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1883 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1884 continue;
1885 }
1886 MenuEntry::Item(item) => item,
1887 };
1888 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1889 popup = popup.item(
1890 PopupMenuItem::new(item.label())
1891 .icon(menu_icon(channel_menu_icon(item)))
1892 .disabled(menu_state.disables(item))
1893 .on_click(move |_, _, cx| {
1894 action_state.update(cx, |state, cx| match item {
1895 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1896 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1897 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1898 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1899 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1900 ChannelMenuItem::Notifications => {}
1901 });
1902 }),
1903 );
1904 }
1905 popup
1906 }
1907
1908 fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1909 match item {
1910 ChannelMenuItem::Notifications => IconName::Bell,
1911 ChannelMenuItem::Pin => IconName::Pin,
1912 ChannelMenuItem::Unpin => IconName::PinOff,
1913 ChannelMenuItem::Show => IconName::Eye,
1914 ChannelMenuItem::Hide => IconName::EyeOff,
1915 ChannelMenuItem::CopyLink => IconName::Link,
1916 }
1917 }
1918
1919 fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1920 let mut popup = popup;
1921 for entry in team_menu_entries(hidden) {
1922 let MenuEntry::Item(item) = entry else {
1923 popup = popup.separator();
1924 continue;
1925 };
1926 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1927 popup = popup.item(
1928 PopupMenuItem::new(item.label())
1929 .icon(menu_icon(match item {
1930 TeamMenuItem::Show => IconName::Eye,
1931 TeamMenuItem::Hide => IconName::EyeOff,
1932 TeamMenuItem::CopyLink => IconName::Link,
1933 }))
1934 .on_click(move |_, _, cx| {
1935 action_state.update(cx, |state, cx| match item {
1936 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1937 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1938 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1939 });
1940 }),
1941 );
1942 }
1943 popup
1944 }
1945
1946 fn notifications_submenu(
1947 popup: PopupMenu,
1948 window: &mut Window,
1949 cx: &mut Context<PopupMenu>,
1950 state: &Entity<AppState>,
1951 channel_id: &str,
1952 notifications: ChannelNotifications,
1953 ) -> PopupMenu {
1954 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1706 1955 popup.submenu_with_icon(
1707 1956 Some(menu_icon(IconName::Bell)),
1708 1957 "Notifications",
@@ -1832,9 +2081,15 @@ impl Render for SidebarView {
1832 2081 };
1833 2082 let header = match self.tab {
1834 2083 SidebarTab::Chats => Some(
1835 page_header(self.tab.title())
1836 .child(self.chat_list_menu_button(cx))
1837 .child(self.new_chat_button(cx)),
2084 v_flex()
2085 .flex_none()
2086 .child(
2087 page_header(self.tab.title())
2088 .child(self.chat_list_menu_button(cx))
2089 .child(self.filter_toggle_button(cx))
2090 .child(self.new_chat_button(cx)),
2091 )
2092 .child(self.filter_bar(cx)),
1838 2093 ),
1839 2094 SidebarTab::Channels => {
1840 2095 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
@@ -14,7 +14,7 @@ use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, MessageImportance, SidebarTeam,
15 Store, TeamRecord,
15 Store, TeamRecord,
16};
16};
17use teams_core::is_notes_chat;
17use teams_core::{ChatNotificationMode, DesktopNotifications, is_notes_chat};
18
18
19use super::activity_panel::ActivityPanel;
19use super::activity_panel::ActivityPanel;
20use super::avatar::{spec_avatar, square_avatar, with_presence};
20use super::avatar::{spec_avatar, square_avatar, with_presence};
@@ -22,10 +22,14 @@ use super::calls_tab::calls_body;
22use super::saved_panel::SavedPanel;
22use super::saved_panel::SavedPanel;
23use super::scroll_edge::with_top_edge;
23use super::scroll_edge::with_top_edge;
24use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
25use super::widgets::{count_badge, icon, page_header, symbol, unread_marker};
25use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
26use crate::agents::AgentsPanel;
26use crate::agents::AgentsPanel;
27use crate::app_state::{AppEvent, AppState, Selection};
27use crate::app_state::{AppEvent, AppState, Selection};
28use crate::channel_menu::{
29 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
30};
28use crate::chat_actions::TITLE_LIMIT;
31use crate::chat_actions::TITLE_LIMIT;
32use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
29use crate::data::{Directory, is_pending_folder};
33use crate::data::{Directory, is_pending_folder};
30use crate::format;
34use crate::format;
31use crate::local_previews::LocalPreview;
35use crate::local_previews::LocalPreview;
@@ -39,6 +43,9 @@ use crate::sidebar_model::{
39};
43};
40use crate::theme;
44use crate::theme;
41use app_ui_kit::layout::SIDEBAR_WIDTH;
45use app_ui_kit::layout::SIDEBAR_WIDTH;
46use gpui_kit::component::input::InputState;
47
48pub(crate) mod chat_filter_bar;
42
49
43pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
50pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
44const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
51const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -61,7 +68,6 @@ const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
61const TEAM_ROW_HEIGHT: f32 = 40.;
68const TEAM_ROW_HEIGHT: f32 = 40.;
62const REVEAL_ROW_HEIGHT: f32 = 32.;
69const REVEAL_ROW_HEIGHT: f32 = 32.;
63const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
70const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
64const MENU_ICON_SIZE: f32 = 15.;
65const NOTIFICATION_ICON_SIZE: f32 = 13.;
71const NOTIFICATION_ICON_SIZE: f32 = 13.;
66const MENTION_ICON_SIZE: f32 = 15.;
72const MENTION_ICON_SIZE: f32 = 15.;
67const IMPORTANCE_MARKER_SIZE: f32 = 16.;
73const IMPORTANCE_MARKER_SIZE: f32 = 16.;
@@ -89,6 +95,10 @@ impl SidebarTab {
89 }
95 }
90}
96}
91
97
98pub fn chat_row_selector(chat_id: &str) -> String {
99 format!("chat-row/{chat_id}")
100}
101
92#[derive(Clone)]
102#[derive(Clone)]
93struct DraggedChat {
103struct DraggedChat {
94 id: String,
104 id: String,
@@ -130,10 +140,6 @@ struct MenuContext {
130 folders: Vec<(String, String)>,
140 folders: Vec<(String, String)>,
131}
141}
132
142
133fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
134 icon(name, MENU_ICON_SIZE, theme::text_muted())
135}
136
137fn chat_menu(
143fn chat_menu(
138 popup: PopupMenu,
144 popup: PopupMenu,
139 window: &mut Window,
145 window: &mut Window,
@@ -214,18 +220,18 @@ fn chat_menu(
214 if notes {
220 if notes {
215 return popup;
221 return popup;
216 }
222 }
217 popup = popup
223 popup = popup.item(
218 .item(
224 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
219 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
225 .icon(menu_icon(if muted {
220 .icon(menu_icon(if muted {
226 IconName::Bell
221 IconName::Bell
227 } else {
222 } else {
228 IconName::BellOff
223 IconName::BellOff
229 }))
224 }))
230 .on_click(move |_, _, cx| {
225 .on_click(move |_, _, cx| {
231 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
226 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
232 }),
227 }),
233 );
228 )
234 popup = chat_notifications_submenu(popup, window, cx, context, target)
229 .separator()
235 .separator()
230 .item(
236 .item(
231 PopupMenuItem::new("Hide")
237 PopupMenuItem::new("Hide")
@@ -234,6 +240,17 @@ fn chat_menu(
234 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
240 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
235 }),
241 }),
236 );
242 );
243 if !target.is_group {
244 let remove_state = context.state.clone();
245 let remove_id = target.id.clone();
246 popup = popup.item(
247 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
248 .icon(menu_icon(IconName::Trash))
249 .on_click(move |_, window, cx| {
250 confirm_remove_history(&remove_state, &remove_id, window, cx);
251 }),
252 );
253 }
237 if target.is_group {
254 if target.is_group {
238 let leave_state = context.state.clone();
255 let leave_state = context.state.clone();
239 let leave_id = target.id.clone();
256 let leave_id = target.id.clone();
@@ -243,7 +260,7 @@ fn chat_menu(
243 PopupMenuItem::element(|_, _| {
260 PopupMenuItem::element(|_, _| {
244 div().text_color(theme::red_soft()).child("Leave chat...")
261 div().text_color(theme::red_soft()).child("Leave chat...")
245 })
262 })
246 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
263 .icon(menu_icon(IconName::LogOut).text_color(theme::red_soft()))
247 .on_click(move |_, window, cx| {
264 .on_click(move |_, window, cx| {
248 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
265 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
249 }),
266 }),
@@ -252,6 +269,76 @@ fn chat_menu(
252 popup
269 popup
253}
270}
254
271
272const CHAT_NOTIFICATION_MODES: [(&str, ChatNotificationMode); 2] = [
273 ("All new messages", ChatNotificationMode::AllNewMessages),
274 ("Mute", ChatNotificationMode::Mute),
275];
276
277const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
278 (
279 "Match settings used for all chats",
280 DesktopNotifications::MatchAllChats,
281 ),
282 ("Don't get desktop notifications", DesktopNotifications::Off),
283];
284
285fn chat_notifications_submenu(
286 popup: PopupMenu,
287 window: &mut Window,
288 cx: &mut Context<PopupMenu>,
289 context: &MenuContext,
290 target: &ChatMenuTarget,
291) -> PopupMenu {
292 let state = context.state.clone();
293 let chat_id = target.id.clone();
294 let mode = if target.muted {
295 ChatNotificationMode::Mute
296 } else {
297 ChatNotificationMode::AllNewMessages
298 };
299 let desktop = state.read(cx).chat_desktop_notifications(&chat_id);
300 popup.submenu_with_icon(
301 Some(menu_icon(IconName::Bell)),
302 "Manage notifications",
303 window,
304 cx,
305 move |submenu, _, _| {
306 let choose = |chosen_mode: ChatNotificationMode,
307 chosen_desktop: DesktopNotifications| {
308 let (state, chat_id) = (state.clone(), chat_id.clone());
309 move |_: &ClickEvent, _: &mut Window, cx: &mut App| {
310 state.update(cx, |state, cx| {
311 state.set_chat_notifications(&chat_id, chosen_mode, chosen_desktop, cx)
312 });
313 }
314 };
315 let submenu = submenu.label("Chat notification mode");
316 let submenu =
317 CHAT_NOTIFICATION_MODES
318 .iter()
319 .fold(submenu, |submenu, (label, value)| {
320 submenu.item(
321 PopupMenuItem::new(*label)
322 .checked(*value == mode)
323 .on_click(choose(*value, desktop)),
324 )
325 });
326 let submenu = submenu
327 .separator()
328 .label("Set a desktop notification preference");
329 DESKTOP_NOTIFICATIONS
330 .iter()
331 .fold(submenu, |submenu, (label, value)| {
332 submenu.item(
333 PopupMenuItem::new(*label)
334 .checked(*value == desktop)
335 .on_click(choose(mode, *value)),
336 )
337 })
338 },
339 )
340}
341
255#[derive(Clone)]
342#[derive(Clone)]
256struct SectionMenuTarget {
343struct SectionMenuTarget {
257 id: String,
344 id: String,
@@ -394,7 +481,7 @@ fn section_menu(
394 PopupMenuItem::element(|_, _| {
481 PopupMenuItem::element(|_, _| {
395 div().text_color(theme::red_soft()).child("Delete section")
482 div().text_color(theme::red_soft()).child("Delete section")
396 })
483 })
397 .icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
484 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
398 .disabled(target.read_only)
485 .disabled(target.read_only)
399 .on_click(move |_, window, cx| {
486 .on_click(move |_, window, cx| {
400 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
487 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
@@ -445,6 +532,40 @@ fn leave_description(member_count: usize) -> String {
445 format!("{who} {verb} that you left. You can only come back if someone adds you.")
532 format!("{who} {verb} that you left. You can only come back if someone adds you.")
446}
533}
447
534
535const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
536const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
537const REMOVE_HISTORY_TEXT: &str =
538 "This will remove the chat from your list and search. It affects you only.";
539
540fn confirm_remove_history(
541 state: &Entity<AppState>,
542 chat_id: &str,
543 window: &mut Window,
544 cx: &mut App,
545) {
546 let state = state.clone();
547 let chat_id = chat_id.to_owned();
548 window.open_alert_dialog(cx, move |alert, _, _| {
549 let state = state.clone();
550 let chat_id = chat_id.clone();
551 let cancel = Button::new("remove-history-cancel")
552 .label("Cancel")
553 .on_click(|_, window, cx| window.close_dialog(cx));
554 let remove = Button::new("remove-history-confirm")
555 .label("Remove")
556 .primary()
557 .on_click(move |_, window, cx| {
558 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
559 window.close_dialog(cx);
560 });
561 alert
562 .title(REMOVE_HISTORY_TITLE)
563 .description(REMOVE_HISTORY_TEXT)
564 .footer(DialogFooter::new().child(cancel).child(remove))
565 .on_ok(|_, _, _| false)
566 });
567}
568
448pub(crate) fn confirm_leave(
569pub(crate) fn confirm_leave(
449 state: &Entity<AppState>,
570 state: &Entity<AppState>,
450 chat_id: &str,
571 chat_id: &str,
@@ -478,6 +599,12 @@ pub(crate) fn confirm_leave(
478 });
599 });
479}
600}
480
601
602pub enum SidebarEvent {
603 RestoreFocus,
604}
605
606impl EventEmitter<SidebarEvent> for SidebarView {}
607
481pub struct SidebarView {
608pub struct SidebarView {
482 state: Entity<AppState>,
609 state: Entity<AppState>,
483 tab: SidebarTab,
610 tab: SidebarTab,
@@ -492,6 +619,12 @@ pub struct SidebarView {
492 older_chats_seen: Cell<(bool, bool)>,
619 older_chats_seen: Cell<(bool, bool)>,
493 channels_scroll: ScrollHandle,
620 channels_scroll: ScrollHandle,
494 calls_scroll: ScrollHandle,
621 calls_scroll: ScrollHandle,
622 chat_filter: ChatFilter,
623 filter_box_open: bool,
624 more_filters_open: bool,
625 filter_input: Option<Entity<InputState>>,
626 filter_subscription: Option<Subscription>,
627 _activity_observation: Subscription,
495 _subscription: Subscription,
628 _subscription: Subscription,
496 _state_observation: Subscription,
629 _state_observation: Subscription,
497 _agent_observation: Option<Subscription>,
630 _agent_observation: Option<Subscription>,
@@ -582,6 +715,15 @@ impl SidebarView {
582 SidebarTab::Chats
715 SidebarTab::Chats
583 };
716 };
584 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
717 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
718 let activity = activity_panel.read(cx).activity();
719 let activity_observation = cx.observe(&activity, |view, _, cx| {
720 if view
721 .chat_filter
722 .has(crate::chat_filter::ChatFilterPill::Mentions)
723 {
724 cx.notify();
725 }
726 });
585 cx.spawn(async move |this, cx| {
727 cx.spawn(async move |this, cx| {
586 loop {
728 loop {
587 cx.background_executor().timer(CALLS_REFRESH).await;
729 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -610,6 +752,12 @@ impl SidebarView {
610 older_chats_seen: Cell::new((false, false)),
752 older_chats_seen: Cell::new((false, false)),
611 channels_scroll: ScrollHandle::new(),
753 channels_scroll: ScrollHandle::new(),
612 calls_scroll: ScrollHandle::new(),
754 calls_scroll: ScrollHandle::new(),
755 chat_filter: ChatFilter::default(),
756 filter_box_open: false,
757 more_filters_open: false,
758 filter_input: None,
759 filter_subscription: None,
760 _activity_observation: activity_observation,
613 _subscription: subscription,
761 _subscription: subscription,
614 _state_observation: state_observation,
762 _state_observation: state_observation,
615 _agent_observation: agent_observation,
763 _agent_observation: agent_observation,
@@ -1047,6 +1195,7 @@ impl SidebarView {
1047 };
1195 };
1048 h_flex()
1196 h_flex()
1049 .id(SharedString::from(format!("chat-{}", item.id)))
1197 .id(SharedString::from(format!("chat-{}", item.id)))
1198 .debug_selector(|| chat_row_selector(&item.id))
1050 .mx(px(6.))
1199 .mx(px(6.))
1051 .h(px(ROW_HEIGHT))
1200 .h(px(ROW_HEIGHT))
1052 .flex_none()
1201 .flex_none()
@@ -1097,7 +1246,18 @@ impl SidebarView {
1097 now,
1246 now,
1098 offset,
1247 offset,
1099 };
1248 };
1100 let sections = build_sections(&input);
1249 let sections = if self.chat_filter.is_active() {
1250 let mentioned = self.mentioned_chats(cx);
1251 let selected_id = self.selected_chat_id(cx);
1252 filtered_sections(
1253 &input,
1254 &self.chat_filter,
1255 &mentioned,
1256 selected_id.as_deref(),
1257 )
1258 } else {
1259 build_sections(&input)
1260 };
1101 let menu = MenuContext {
1261 let menu = MenuContext {
1102 state: self.state.clone(),
1262 state: self.state.clone(),
1103 folders: state.directory.move_targets(),
1263 folders: state.directory.move_targets(),
@@ -1222,6 +1382,10 @@ impl SidebarView {
1222 .child(LOADING_OLDER_LABEL),
1382 .child(LOADING_OLDER_LABEL),
1223 );
1383 );
1224 }
1384 }
1385 let selected_chat_id = self.selected_chat_id(cx);
1386 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1387 list = list.child(self.filter_empty_state(cx));
1388 }
1225 list = with_spacer(list, &mut skipped_height);
1389 list = with_spacer(list, &mut skipped_height);
1226 self.request_lazy_data(faces, presence_users, cx);
1390 self.request_lazy_data(faces, presence_users, cx);
1227 let scroll_area = div()
1391 let scroll_area = div()
@@ -1378,6 +1542,8 @@ impl SidebarView {
1378 let name_style = team_name_style(entry, expanded);
1542 let name_style = team_name_style(entry, expanded);
1379 let badge = team_badge(entry, expanded);
1543 let badge = team_badge(entry, expanded);
1380 let toggle_id = team_id.clone();
1544 let toggle_id = team_id.clone();
1545 let (team_menu_state, team_menu_id, team_hidden) =
1546 (self.state.clone(), team_id.clone(), entry.hidden);
1381 list = list.child(
1547 list = list.child(
1382 h_flex()
1548 h_flex()
1383 .id(SharedString::from(format!("team-{team_id}")))
1549 .id(SharedString::from(format!("team-{team_id}")))
@@ -1417,7 +1583,10 @@ impl SidebarView {
1417 }
1583 }
1418 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1584 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1419 cx.notify();
1585 cx.notify();
1420 })),
1586 }))
1587 .context_menu(move |popup, _, _| {
1588 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1589 }),
1421 );
1590 );
1422 if !expanded {
1591 if !expanded {
1423 return list;
1592 return list;
@@ -1702,7 +1871,87 @@ fn channel_menu(
1702 channel_id: &str,
1871 channel_id: &str,
1703 notifications: ChannelNotifications,
1872 notifications: ChannelNotifications,
1704) -> PopupMenu {
1873) -> PopupMenu {
1705 let channel_id = channel_id.to_owned();
1874 let menu_state = state.read(cx).channel_menu_state(channel_id);
1875 let mut popup = popup;
1876 for entry in channel_menu_entries(menu_state) {
1877 let item = match entry {
1878 MenuEntry::Separator => {
1879 popup = popup.separator();
1880 continue;
1881 }
1882 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1883 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1884 continue;
1885 }
1886 MenuEntry::Item(item) => item,
1887 };
1888 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1889 popup = popup.item(
1890 PopupMenuItem::new(item.label())
1891 .icon(menu_icon(channel_menu_icon(item)))
1892 .disabled(menu_state.disables(item))
1893 .on_click(move |_, _, cx| {
1894 action_state.update(cx, |state, cx| match item {
1895 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1896 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1897 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1898 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1899 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1900 ChannelMenuItem::Notifications => {}
1901 });
1902 }),
1903 );
1904 }
1905 popup
1906}
1907
1908fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1909 match item {
1910 ChannelMenuItem::Notifications => IconName::Bell,
1911 ChannelMenuItem::Pin => IconName::Pin,
1912 ChannelMenuItem::Unpin => IconName::PinOff,
1913 ChannelMenuItem::Show => IconName::Eye,
1914 ChannelMenuItem::Hide => IconName::EyeOff,
1915 ChannelMenuItem::CopyLink => IconName::Link,
1916 }
1917}
1918
1919fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1920 let mut popup = popup;
1921 for entry in team_menu_entries(hidden) {
1922 let MenuEntry::Item(item) = entry else {
1923 popup = popup.separator();
1924 continue;
1925 };
1926 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1927 popup = popup.item(
1928 PopupMenuItem::new(item.label())
1929 .icon(menu_icon(match item {
1930 TeamMenuItem::Show => IconName::Eye,
1931 TeamMenuItem::Hide => IconName::EyeOff,
1932 TeamMenuItem::CopyLink => IconName::Link,
1933 }))
1934 .on_click(move |_, _, cx| {
1935 action_state.update(cx, |state, cx| match item {
1936 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1937 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1938 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1939 });
1940 }),
1941 );
1942 }
1943 popup
1944}
1945
1946fn notifications_submenu(
1947 popup: PopupMenu,
1948 window: &mut Window,
1949 cx: &mut Context<PopupMenu>,
1950 state: &Entity<AppState>,
1951 channel_id: &str,
1952 notifications: ChannelNotifications,
1953) -> PopupMenu {
1954 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1706 popup.submenu_with_icon(
1955 popup.submenu_with_icon(
1707 Some(menu_icon(IconName::Bell)),
1956 Some(menu_icon(IconName::Bell)),
1708 "Notifications",
1957 "Notifications",
@@ -1832,9 +2081,15 @@ impl Render for SidebarView {
1832 };
2081 };
1833 let header = match self.tab {
2082 let header = match self.tab {
1834 SidebarTab::Chats => Some(
2083 SidebarTab::Chats => Some(
1835 page_header(self.tab.title())
2084 v_flex()
1836 .child(self.chat_list_menu_button(cx))
2085 .flex_none()
1837 .child(self.new_chat_button(cx)),
2086 .child(
2087 page_header(self.tab.title())
2088 .child(self.chat_list_menu_button(cx))
2089 .child(self.filter_toggle_button(cx))
2090 .child(self.new_chat_button(cx)),
2091 )
2092 .child(self.filter_bar(cx)),
1838 ),
2093 ),
1839 SidebarTab::Channels => {
2094 SidebarTab::Channels => {
1840 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
2095 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
crates/app/src/views/sidebar/chat_filter_bar.rs added +320 −0
@@ -0,0 +1,320 @@
1 use std::collections::HashSet;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
5 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8
9 use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10 use crate::app_state::Selection;
11 use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FEWER_FILTERS,
13 FILTER_PLACEHOLDER, MORE_FILTERS, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14 };
15 use crate::theme;
16 use crate::views::widgets::icon;
17
18 pub const FILTER_TAG: &str = "shell/islands/sidebar/chat-filter";
19 pub const FILTER_INPUT_TAG: &str = "shell/islands/sidebar/chat-filter/input";
20 pub const FILTER_PILLS_TAG: &str = "shell/islands/sidebar/chat-filter/pills";
21 pub const FILTER_EMPTY_TAG: &str = "shell/islands/sidebar/chat-filter-empty";
22 const INPUT_HEIGHT: f32 = 32.;
23 const PILL_HEIGHT: f32 = 24.;
24 const SIDE_INSET: f32 = 16.;
25
26 impl SidebarView {
27 pub fn toggle_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28 if self.tab != SidebarTab::Chats {
29 self.open_tab(SidebarTab::Chats, cx);
30 } else if self.filter_box_open {
31 self.close_filter_box(window, cx);
32 return;
33 }
34 self.filter_box_open = true;
35 let input = self.filter_input(window, cx);
36 input.update(cx, |input, cx| input.focus(window, cx));
37 cx.notify();
38 }
39
40 pub fn toggle_pill(&mut self, pill: ChatFilterPill, cx: &mut Context<Self>) {
41 if self.tab != SidebarTab::Chats {
42 self.open_tab(SidebarTab::Chats, cx);
43 }
44 if self.chat_filter.toggle(pill) {
45 cx.notify();
46 }
47 }
48
49 pub fn clear_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) {
50 self.chat_filter.clear();
51 if let Some(input) = &self.filter_input {
52 input.update(cx, |input, cx| input.set_value("", window, cx));
53 }
54 cx.notify();
55 }
56
57 pub(super) fn mentioned_chats(&self, cx: &App) -> HashSet<String> {
58 if !self.chat_filter.has(ChatFilterPill::Mentions) {
59 return HashSet::new();
60 }
61 let activity = self.activity_panel.read(cx).activity();
62 mentioned_conversations(activity.read(cx).feed().unread_entries())
63 }
64
65 pub(super) fn selected_chat_id(&self, cx: &App) -> Option<String> {
66 match &self.state.read(cx).selection {
67 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
68 _ => None,
69 }
70 }
71
72 fn close_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
73 self.filter_box_open = false;
74 cx.emit(SidebarEvent::RestoreFocus);
75 self.chat_filter.text.clear();
76 if let Some(input) = &self.filter_input {
77 input.update(cx, |input, cx| input.set_value("", window, cx));
78 }
79 cx.notify();
80 }
81
82 fn filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
83 if let Some(input) = &self.filter_input {
84 return input.clone();
85 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 if matches!(event, InputEvent::Change) {
89 this.chat_filter.text = input.read(cx).value().to_string();
90 cx.notify();
91 }
92 });
93 self.filter_subscription = Some(subscription);
94 self.filter_input = Some(input.clone());
95 input
96 }
97
98 pub(super) fn filter_toggle_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
99 let open = self.filter_box_open;
100 let active = open || self.chat_filter.is_active();
101 let label = if open {
102 CLOSE_FILTER_TEXT
103 } else {
104 SHOW_FILTER_TEXT
105 };
106 div()
107 .id("chat-filter-toggle")
108 .size(px(NEW_CHAT_BUTTON_SIZE))
109 .flex_none()
110 .flex()
111 .items_center()
112 .justify_center()
113 .rounded(px(8.))
114 .cursor_pointer()
115 .when(active, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 })
120 .child(icon(
121 IconName::Funnel,
122 16.,
123 if active {
124 theme::accent_text()
125 } else {
126 theme::text_soft()
127 },
128 ))
129 .on_click(cx.listener(|this, _, window, cx| this.toggle_filter_box(window, cx)))
130 }
131
132 pub(super) fn filter_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
133 let input_row = self
134 .filter_input
135 .clone()
136 .filter(|_| self.filter_box_open)
137 .map(|input| self.filter_input_row(&input, cx));
138 v_flex()
139 .debug_selector(|| FILTER_TAG.into())
140 .flex_none()
141 .w_full()
142 .pb(px(8.))
143 .gap(px(8.))
144 .children(input_row)
145 .child(self.filter_pills(cx))
146 }
147
148 fn filter_input_row(&self, input: &Entity<InputState>, cx: &mut Context<Self>) -> Div {
149 let has_text = !self.chat_filter.text.is_empty();
150 h_flex()
151 .debug_selector(|| FILTER_INPUT_TAG.into())
152 .mx(px(SIDE_INSET))
153 .h(px(INPUT_HEIGHT))
154 .flex_none()
155 .pl(px(10.))
156 .pr(px(4.))
157 .gap(px(8.))
158 .items_center()
159 .rounded(px(6.))
160 .bg(theme::surface_raised())
161 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
162 this.close_filter_box(window, cx);
163 cx.stop_propagation();
164 }))
165 .child(icon(IconName::Funnel, 14., theme::text_muted()))
166 .child(
167 div()
168 .flex_1()
169 .min_w_0()
170 .child(Input::new(input).appearance(false).bordered(false)),
171 )
172 .when(has_text, |row| {
173 row.child(
174 div()
175 .id("chat-filter-clear-text")
176 .size(px(PILL_HEIGHT))
177 .flex_none()
178 .flex()
179 .items_center()
180 .justify_center()
181 .rounded(px(6.))
182 .cursor_pointer()
183 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
185 .child(icon(IconName::X, 14., theme::text_muted()))
186 .on_click(cx.listener(|this, _, window, cx| {
187 this.chat_filter.text.clear();
188 if let Some(input) = &this.filter_input {
189 input.update(cx, |input, cx| {
190 input.set_value("", window, cx);
191 input.focus(window, cx);
192 });
193 }
194 cx.notify();
195 })),
196 )
197 })
198 }
199
200 fn filter_pills(&self, cx: &mut Context<Self>) -> impl IntoElement {
201 let overflow_active = ChatFilterPill::OVERFLOW
202 .iter()
203 .any(|pill| self.chat_filter.has(*pill));
204 let show_overflow = self.more_filters_open || overflow_active;
205 let mut pills: Vec<AnyElement> = ChatFilterPill::PRIMARY
206 .into_iter()
207 .map(|pill| self.filter_pill(pill, cx).into_any_element())
208 .collect();
209 if show_overflow {
210 pills.extend(
211 ChatFilterPill::OVERFLOW
212 .into_iter()
213 .map(|pill| self.filter_pill(pill, cx).into_any_element()),
214 );
215 }
216 if !overflow_active {
217 pills.push(self.more_filters_button(cx).into_any_element());
218 }
219 h_flex()
220 .debug_selector(|| FILTER_PILLS_TAG.into())
221 .px(px(SIDE_INSET))
222 .flex_wrap()
223 .gap(px(6.))
224 .children(pills)
225 }
226
227 fn filter_pill(&self, pill: ChatFilterPill, cx: &mut Context<Self>) -> impl IntoElement {
228 let selected = self.chat_filter.has(pill);
229 let disabled = self.chat_filter.is_disabled(pill);
230 div()
231 .id(ElementId::Name(
232 format!("chat-filter-{}", pill.label()).into(),
233 ))
234 .h(px(PILL_HEIGHT))
235 .px(px(12.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .rounded_full()
240 .text_size(px(12.))
241 .when(selected, |chip| {
242 chip.bg(theme::accent()).text_color(theme::on_accent())
243 })
244 .when(!selected && disabled, |chip| {
245 chip.bg(theme::surface_raised())
246 .text_color(theme::text_faint())
247 })
248 .when(!selected && !disabled, |chip| {
249 chip.bg(theme::surface_raised())
250 .text_color(theme::text_soft())
251 .cursor_pointer()
252 .hover(|chip| chip.bg(theme::border_strong()))
253 })
254 .child(pill.label())
255 .when(!disabled, |chip| {
256 chip.on_click(cx.listener(move |this, _, _, cx| this.toggle_pill(pill, cx)))
257 })
258 }
259
260 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
261 let open = self.more_filters_open;
262 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
263 div()
264 .id("chat-filter-more")
265 .size(px(PILL_HEIGHT))
266 .flex()
267 .flex_none()
268 .items_center()
269 .justify_center()
270 .rounded_full()
271 .cursor_pointer()
272 .bg(theme::surface_raised())
273 .hover(|chip| chip.bg(theme::border_strong()))
274 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
275 .child(icon(
276 if open {
277 IconName::ChevronUp
278 } else {
279 IconName::ChevronDown
280 },
281 14.,
282 theme::text_soft(),
283 ))
284 .on_click(cx.listener(|this, _, _, cx| {
285 this.more_filters_open = !this.more_filters_open;
286 cx.notify();
287 }))
288 }
289
290 pub(super) fn filter_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
291 v_flex()
292 .debug_selector(|| FILTER_EMPTY_TAG.into())
293 .w_full()
294 .px(px(SIDE_INSET))
295 .py(px(SIDE_INSET))
296 .gap(px(8.))
297 .items_center()
298 .child(
299 div()
300 .text_size(px(13.))
301 .text_color(theme::text_muted())
302 .child(NO_MATCHES),
303 )
304 .child(
305 div()
306 .id("chat-filter-clear-all")
307 .px(px(8.))
308 .h(px(PILL_HEIGHT))
309 .flex()
310 .items_center()
311 .rounded(px(6.))
312 .cursor_pointer()
313 .text_size(px(12.))
314 .text_color(theme::accent_text())
315 .hover(|button| button.bg(theme::surface_raised()))
316 .child(CLEAR_FILTERS)
317 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
318 )
319 }
320 }
@@ -0,0 +1,320 @@
1use std::collections::HashSet;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::input::{Escape, Input, InputEvent, InputState};
5use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10use crate::app_state::Selection;
11use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill, FEWER_FILTERS,
13 FILTER_PLACEHOLDER, MORE_FILTERS, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
14};
15use crate::theme;
16use crate::views::widgets::icon;
17
18pub const FILTER_TAG: &str = "shell/islands/sidebar/chat-filter";
19pub const FILTER_INPUT_TAG: &str = "shell/islands/sidebar/chat-filter/input";
20pub const FILTER_PILLS_TAG: &str = "shell/islands/sidebar/chat-filter/pills";
21pub const FILTER_EMPTY_TAG: &str = "shell/islands/sidebar/chat-filter-empty";
22const INPUT_HEIGHT: f32 = 32.;
23const PILL_HEIGHT: f32 = 24.;
24const SIDE_INSET: f32 = 16.;
25
26impl SidebarView {
27 pub fn toggle_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
28 if self.tab != SidebarTab::Chats {
29 self.open_tab(SidebarTab::Chats, cx);
30 } else if self.filter_box_open {
31 self.close_filter_box(window, cx);
32 return;
33 }
34 self.filter_box_open = true;
35 let input = self.filter_input(window, cx);
36 input.update(cx, |input, cx| input.focus(window, cx));
37 cx.notify();
38 }
39
40 pub fn toggle_pill(&mut self, pill: ChatFilterPill, cx: &mut Context<Self>) {
41 if self.tab != SidebarTab::Chats {
42 self.open_tab(SidebarTab::Chats, cx);
43 }
44 if self.chat_filter.toggle(pill) {
45 cx.notify();
46 }
47 }
48
49 pub fn clear_filters(&mut self, window: &mut Window, cx: &mut Context<Self>) {
50 self.chat_filter.clear();
51 if let Some(input) = &self.filter_input {
52 input.update(cx, |input, cx| input.set_value("", window, cx));
53 }
54 cx.notify();
55 }
56
57 pub(super) fn mentioned_chats(&self, cx: &App) -> HashSet<String> {
58 if !self.chat_filter.has(ChatFilterPill::Mentions) {
59 return HashSet::new();
60 }
61 let activity = self.activity_panel.read(cx).activity();
62 mentioned_conversations(activity.read(cx).feed().unread_entries())
63 }
64
65 pub(super) fn selected_chat_id(&self, cx: &App) -> Option<String> {
66 match &self.state.read(cx).selection {
67 Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
68 _ => None,
69 }
70 }
71
72 fn close_filter_box(&mut self, window: &mut Window, cx: &mut Context<Self>) {
73 self.filter_box_open = false;
74 cx.emit(SidebarEvent::RestoreFocus);
75 self.chat_filter.text.clear();
76 if let Some(input) = &self.filter_input {
77 input.update(cx, |input, cx| input.set_value("", window, cx));
78 }
79 cx.notify();
80 }
81
82 fn filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
83 if let Some(input) = &self.filter_input {
84 return input.clone();
85 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 if matches!(event, InputEvent::Change) {
89 this.chat_filter.text = input.read(cx).value().to_string();
90 cx.notify();
91 }
92 });
93 self.filter_subscription = Some(subscription);
94 self.filter_input = Some(input.clone());
95 input
96 }
97
98 pub(super) fn filter_toggle_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
99 let open = self.filter_box_open;
100 let active = open || self.chat_filter.is_active();
101 let label = if open {
102 CLOSE_FILTER_TEXT
103 } else {
104 SHOW_FILTER_TEXT
105 };
106 div()
107 .id("chat-filter-toggle")
108 .size(px(NEW_CHAT_BUTTON_SIZE))
109 .flex_none()
110 .flex()
111 .items_center()
112 .justify_center()
113 .rounded(px(8.))
114 .cursor_pointer()
115 .when(active, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 })
120 .child(icon(
121 IconName::Funnel,
122 16.,
123 if active {
124 theme::accent_text()
125 } else {
126 theme::text_soft()
127 },
128 ))
129 .on_click(cx.listener(|this, _, window, cx| this.toggle_filter_box(window, cx)))
130 }
131
132 pub(super) fn filter_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
133 let input_row = self
134 .filter_input
135 .clone()
136 .filter(|_| self.filter_box_open)
137 .map(|input| self.filter_input_row(&input, cx));
138 v_flex()
139 .debug_selector(|| FILTER_TAG.into())
140 .flex_none()
141 .w_full()
142 .pb(px(8.))
143 .gap(px(8.))
144 .children(input_row)
145 .child(self.filter_pills(cx))
146 }
147
148 fn filter_input_row(&self, input: &Entity<InputState>, cx: &mut Context<Self>) -> Div {
149 let has_text = !self.chat_filter.text.is_empty();
150 h_flex()
151 .debug_selector(|| FILTER_INPUT_TAG.into())
152 .mx(px(SIDE_INSET))
153 .h(px(INPUT_HEIGHT))
154 .flex_none()
155 .pl(px(10.))
156 .pr(px(4.))
157 .gap(px(8.))
158 .items_center()
159 .rounded(px(6.))
160 .bg(theme::surface_raised())
161 .capture_action(cx.listener(|this, _: &Escape, window, cx| {
162 this.close_filter_box(window, cx);
163 cx.stop_propagation();
164 }))
165 .child(icon(IconName::Funnel, 14., theme::text_muted()))
166 .child(
167 div()
168 .flex_1()
169 .min_w_0()
170 .child(Input::new(input).appearance(false).bordered(false)),
171 )
172 .when(has_text, |row| {
173 row.child(
174 div()
175 .id("chat-filter-clear-text")
176 .size(px(PILL_HEIGHT))
177 .flex_none()
178 .flex()
179 .items_center()
180 .justify_center()
181 .rounded(px(6.))
182 .cursor_pointer()
183 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
185 .child(icon(IconName::X, 14., theme::text_muted()))
186 .on_click(cx.listener(|this, _, window, cx| {
187 this.chat_filter.text.clear();
188 if let Some(input) = &this.filter_input {
189 input.update(cx, |input, cx| {
190 input.set_value("", window, cx);
191 input.focus(window, cx);
192 });
193 }
194 cx.notify();
195 })),
196 )
197 })
198 }
199
200 fn filter_pills(&self, cx: &mut Context<Self>) -> impl IntoElement {
201 let overflow_active = ChatFilterPill::OVERFLOW
202 .iter()
203 .any(|pill| self.chat_filter.has(*pill));
204 let show_overflow = self.more_filters_open || overflow_active;
205 let mut pills: Vec<AnyElement> = ChatFilterPill::PRIMARY
206 .into_iter()
207 .map(|pill| self.filter_pill(pill, cx).into_any_element())
208 .collect();
209 if show_overflow {
210 pills.extend(
211 ChatFilterPill::OVERFLOW
212 .into_iter()
213 .map(|pill| self.filter_pill(pill, cx).into_any_element()),
214 );
215 }
216 if !overflow_active {
217 pills.push(self.more_filters_button(cx).into_any_element());
218 }
219 h_flex()
220 .debug_selector(|| FILTER_PILLS_TAG.into())
221 .px(px(SIDE_INSET))
222 .flex_wrap()
223 .gap(px(6.))
224 .children(pills)
225 }
226
227 fn filter_pill(&self, pill: ChatFilterPill, cx: &mut Context<Self>) -> impl IntoElement {
228 let selected = self.chat_filter.has(pill);
229 let disabled = self.chat_filter.is_disabled(pill);
230 div()
231 .id(ElementId::Name(
232 format!("chat-filter-{}", pill.label()).into(),
233 ))
234 .h(px(PILL_HEIGHT))
235 .px(px(12.))
236 .flex()
237 .flex_none()
238 .items_center()
239 .rounded_full()
240 .text_size(px(12.))
241 .when(selected, |chip| {
242 chip.bg(theme::accent()).text_color(theme::on_accent())
243 })
244 .when(!selected && disabled, |chip| {
245 chip.bg(theme::surface_raised())
246 .text_color(theme::text_faint())
247 })
248 .when(!selected && !disabled, |chip| {
249 chip.bg(theme::surface_raised())
250 .text_color(theme::text_soft())
251 .cursor_pointer()
252 .hover(|chip| chip.bg(theme::border_strong()))
253 })
254 .child(pill.label())
255 .when(!disabled, |chip| {
256 chip.on_click(cx.listener(move |this, _, _, cx| this.toggle_pill(pill, cx)))
257 })
258 }
259
260 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
261 let open = self.more_filters_open;
262 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
263 div()
264 .id("chat-filter-more")
265 .size(px(PILL_HEIGHT))
266 .flex()
267 .flex_none()
268 .items_center()
269 .justify_center()
270 .rounded_full()
271 .cursor_pointer()
272 .bg(theme::surface_raised())
273 .hover(|chip| chip.bg(theme::border_strong()))
274 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
275 .child(icon(
276 if open {
277 IconName::ChevronUp
278 } else {
279 IconName::ChevronDown
280 },
281 14.,
282 theme::text_soft(),
283 ))
284 .on_click(cx.listener(|this, _, _, cx| {
285 this.more_filters_open = !this.more_filters_open;
286 cx.notify();
287 }))
288 }
289
290 pub(super) fn filter_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
291 v_flex()
292 .debug_selector(|| FILTER_EMPTY_TAG.into())
293 .w_full()
294 .px(px(SIDE_INSET))
295 .py(px(SIDE_INSET))
296 .gap(px(8.))
297 .items_center()
298 .child(
299 div()
300 .text_size(px(13.))
301 .text_color(theme::text_muted())
302 .child(NO_MATCHES),
303 )
304 .child(
305 div()
306 .id("chat-filter-clear-all")
307 .px(px(8.))
308 .h(px(PILL_HEIGHT))
309 .flex()
310 .items_center()
311 .rounded(px(6.))
312 .cursor_pointer()
313 .text_size(px(12.))
314 .text_color(theme::accent_text())
315 .hover(|button| button.bg(theme::surface_raised()))
316 .child(CLEAR_FILTERS)
317 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
318 )
319 }
320}
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/channel_visibility.rs added +497 −0
@@ -0,0 +1,497 @@
1 use serde_json::{Value, json};
2 use session::{Method, Request, Session};
3
4 use crate::error::Result;
5 use crate::members::{threads_url, user_mri};
6 use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7 use crate::pins::DEFAULT_REGION;
8
9 const FAVORITE_PROPERTY: &str = "favorite";
10 const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";
11 const FOLLOWED_PROPERTY: &str = "isfollowed";
12 const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";
13 const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";
14 const FAVORITE_MODE_MANUAL: &str = "manual";
15 const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;
16
17 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18 pub enum ChannelKind {
19 Standard,
20 Private,
21 Shared,
22 }
23
24 impl ChannelKind {
25 pub fn from_membership_type(membership_type: Option<&str>) -> Self {
26 match membership_type.map(str::to_ascii_lowercase).as_deref() {
27 Some("private") => ChannelKind::Private,
28 Some("shared") => ChannelKind::Shared,
29 _ => ChannelKind::Standard,
30 }
31 }
32 }
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
35 pub struct ChannelTarget<'a> {
36 pub channel_id: &'a str,
37 pub general: bool,
38 pub kind: ChannelKind,
39 }
40
41 /// The own member state of a channel conversation that decides Teams' show and hide steps.
42 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43 pub struct ChannelMembership {
44 pub moderator: bool,
45 pub explicitly_added: bool,
46 pub followed: bool,
47 }
48
49 fn truthy(value: Option<&Value>) -> bool {
50 match value {
51 Some(Value::Bool(flag)) => *flag,
52 Some(Value::String(text)) => !text.is_empty(),
53 Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),
54 Some(Value::Array(_) | Value::Object(_)) => true,
55 _ => false,
56 }
57 }
58
59 pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {
60 let member = conversation.get("memberProperties");
61 ChannelMembership {
62 moderator: truthy(member.and_then(|member| member.get("isModerator"))),
63 explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),
64 followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),
65 }
66 }
67
68 /// Teams joins the user to a standard channel thread before it changes the channel's visibility.
69 pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {
70 let permanently_joined = kind == ChannelKind::Private
71 || (kind == ChannelKind::Shared && membership.explicitly_added)
72 || membership.moderator;
73 !permanently_joined
74 }
75
76 pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {
77 if shown {
78 0
79 } else {
80 (now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS
81 }
82 }
83
84 pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {
85 transport: T,
86 conversations_url: String,
87 threads_url: String,
88 }
89
90 impl ChannelVisibility<SessionMessageTransport> {
91 pub fn new(session: &Session) -> Self {
92 ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
93 }
94 }
95
96 impl<T: MessageTransport> ChannelVisibility<T> {
97 pub fn with_transport(transport: T, region: &str) -> Self {
98 ChannelVisibility {
99 transport,
100 conversations_url: format!(
101 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
102 ),
103 threads_url: threads_url(region),
104 }
105 }
106
107 pub fn conversation_request(&self, conversation_id: &str) -> Request {
108 Request::get(format!(
109 "{}/{}?view=msnp24Equivalent",
110 self.conversations_url,
111 encode(conversation_id)
112 ))
113 }
114
115 fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {
116 Request::with_body(
117 Method::Put,
118 format!(
119 "{}/{}/properties?name={name}",
120 self.conversations_url,
121 encode(conversation_id)
122 ),
123 json!({ name: value }),
124 )
125 }
126
127 pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {
128 let mut request =
129 self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));
130 if shown {
131 request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);
132 request
133 .headers
134 .push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));
135 }
136 request
137 }
138
139 pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
140 self.property_request(
141 team_thread_id,
142 GENERAL_FAVORITE_PROPERTY,
143 json!(shown.to_string()),
144 )
145 }
146
147 pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
148 self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))
149 }
150
151 pub fn unfollow_request(&self, channel_id: &str) -> Request {
152 self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))
153 }
154
155 pub fn membership_request(
156 &self,
157 channel_id: &str,
158 own_user_id: &str,
159 shown: bool,
160 now_ms: i64,
161 ) -> Request {
162 Request::with_body(
163 Method::Put,
164 format!(
165 "{}/{}/members/{}",
166 self.threads_url,
167 encode(channel_id),
168 user_mri(own_user_id)
169 ),
170 json!({ "expiration": membership_expiration(shown, now_ms) }),
171 )
172 }
173
174 /// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.
175 pub fn channel_requests(
176 &self,
177 target: &ChannelTarget<'_>,
178 membership: ChannelMembership,
179 own_user_id: &str,
180 shown: bool,
181 now_ms: i64,
182 ) -> Vec<Request> {
183 if target.general {
184 return vec![self.general_favorite_request(target.channel_id, shown)];
185 }
186 let mut requests = Vec::new();
187 if joins_thread(target.kind, membership) {
188 requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));
189 }
190 requests.push(self.favorite_request(target.channel_id, shown));
191 if !shown || membership.followed {
192 requests.push(self.unfollow_request(target.channel_id));
193 }
194 requests
195 }
196
197 pub async fn set_channel_shown(
198 &self,
199 target: &ChannelTarget<'_>,
200 own_user_id: &str,
201 shown: bool,
202 now_ms: i64,
203 ) -> Result<()> {
204 let membership = if target.general {
205 ChannelMembership::default()
206 } else {
207 let answer = self
208 .transport
209 .send(self.conversation_request(target.channel_id))
210 .await?;
211 ensure_success(&answer)?;
212 parse_channel_membership(&answer.body)
213 };
214 for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {
215 ensure_success(&self.transport.send(request).await?)?;
216 }
217 Ok(())
218 }
219
220 pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {
221 let answer = self
222 .transport
223 .send(self.team_favorite_request(team_thread_id, shown))
224 .await?;
225 ensure_success(&answer)
226 }
227 }
228
229 #[cfg(test)]
230 mod tests {
231 use std::collections::VecDeque;
232 use std::sync::Mutex;
233
234 use session::ApiResponse;
235
236 use super::*;
237
238 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";
239 const CHANNEL: &str = "19:abc@thread.tacv2";
240 const ENCODED: &str = "19%3Aabc%40thread.tacv2";
241 const NOW_MS: i64 = 1_791_368_000_500;
242
243 struct Canned {
244 requests: Mutex<Vec<Request>>,
245 answers: Mutex<VecDeque<(u16, Value)>>,
246 }
247
248 impl MessageTransport for &Canned {
249 async fn send(&self, request: Request) -> Result<ApiResponse> {
250 self.requests.lock().unwrap().push(request);
251 let (status, body) = self
252 .answers
253 .lock()
254 .unwrap()
255 .pop_front()
256 .unwrap_or((200, Value::Null));
257 Ok(ApiResponse {
258 status,
259 body,
260 retry_after: None,
261 })
262 }
263 }
264
265 fn canned(answers: Vec<(u16, Value)>) -> Canned {
266 Canned {
267 requests: Mutex::new(Vec::new()),
268 answers: Mutex::new(answers.into()),
269 }
270 }
271
272 fn standard() -> ChannelTarget<'static> {
273 ChannelTarget {
274 channel_id: CHANNEL,
275 general: false,
276 kind: ChannelKind::Standard,
277 }
278 }
279
280 fn summary(request: &Request) -> (String, String, Option<Value>) {
281 (
282 request.method.as_str().to_owned(),
283 request.url.clone(),
284 request.body.clone(),
285 )
286 }
287
288 #[test]
289 fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {
290 let transport = canned(Vec::new());
291 let client = ChannelVisibility::with_transport(&transport, "emea");
292 let requests = client.channel_requests(
293 &standard(),
294 ChannelMembership::default(),
295 "user-1",
296 true,
297 NOW_MS,
298 );
299 let summaries: Vec<_> = requests.iter().map(summary).collect();
300 assert_eq!(
301 summaries,
302 vec![
303 (
304 "PUT".to_owned(),
305 format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
306 Some(json!({"expiration": 0})),
307 ),
308 (
309 "PUT".to_owned(),
310 format!(
311 "{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"
312 ),
313 Some(json!({"favorite": "true"})),
314 ),
315 ]
316 );
317 assert_eq!(
318 requests[1].headers,
319 vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]
320 );
321 }
322
323 #[test]
324 fn hiding_sets_a_two_week_expiration_and_unfollows() {
325 let transport = canned(Vec::new());
326 let client = ChannelVisibility::with_transport(&transport, "emea");
327 let requests = client.channel_requests(
328 &standard(),
329 ChannelMembership::default(),
330 "8:orgid:user-1",
331 false,
332 NOW_MS,
333 );
334 let summaries: Vec<_> = requests.iter().map(summary).collect();
335 assert_eq!(
336 summaries,
337 vec![
338 (
339 "PUT".to_owned(),
340 format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
341 Some(json!({"expiration": 1_791_368_001 + 1_209_600})),
342 ),
343 (
344 "PUT".to_owned(),
345 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
346 Some(json!({"favorite": "false"})),
347 ),
348 (
349 "PUT".to_owned(),
350 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
351 Some(json!({"isfollowed": false})),
352 ),
353 ]
354 );
355 assert!(requests[1].headers.is_empty());
356 }
357
358 #[test]
359 fn moderators_and_private_members_skip_the_join_step() {
360 let transport = canned(Vec::new());
361 let client = ChannelVisibility::with_transport(&transport, "emea");
362 let moderator = ChannelMembership {
363 moderator: true,
364 ..ChannelMembership::default()
365 };
366 let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);
367 assert_eq!(requests.len(), 1);
368 assert!(requests[0].url.contains("name=favorite"));
369 let private = ChannelTarget {
370 kind: ChannelKind::Private,
371 ..standard()
372 };
373 assert!(!joins_thread(private.kind, ChannelMembership::default()));
374 let shared = ChannelMembership {
375 explicitly_added: true,
376 ..ChannelMembership::default()
377 };
378 assert!(!joins_thread(ChannelKind::Shared, shared));
379 assert!(joins_thread(
380 ChannelKind::Shared,
381 ChannelMembership::default()
382 ));
383 }
384
385 #[test]
386 fn showing_a_followed_channel_also_clears_the_follow() {
387 let transport = canned(Vec::new());
388 let client = ChannelVisibility::with_transport(&transport, "emea");
389 let followed = ChannelMembership {
390 moderator: true,
391 followed: true,
392 ..ChannelMembership::default()
393 };
394 let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);
395 assert_eq!(requests.len(), 2);
396 assert!(requests[1].url.ends_with("name=isfollowed"));
397 }
398
399 #[test]
400 fn general_and_team_visibility_write_one_property() {
401 let transport = canned(Vec::new());
402 let client = ChannelVisibility::with_transport(&transport, "emea");
403 let general = ChannelTarget {
404 general: true,
405 ..standard()
406 };
407 let requests =
408 client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);
409 assert_eq!(
410 requests.iter().map(summary).collect::<Vec<_>>(),
411 vec![(
412 "PUT".to_owned(),
413 format!(
414 "{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"
415 ),
416 Some(json!({"isGeneralChannelFavorite": "false"})),
417 )]
418 );
419 let team = client.team_favorite_request(CHANNEL, true);
420 assert_eq!(
421 summary(&team),
422 (
423 "PUT".to_owned(),
424 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
425 Some(json!({"favorite": "true"})),
426 )
427 );
428 assert!(team.headers.is_empty());
429 }
430
431 #[test]
432 fn membership_follows_javascript_truthiness() {
433 let membership = parse_channel_membership(&json!({
434 "memberProperties": {"isModerator": true, "explicitlyAdded": "true"},
435 "properties": {"isfollowed": "false"},
436 }));
437 assert_eq!(
438 membership,
439 ChannelMembership {
440 moderator: true,
441 explicitly_added: true,
442 followed: true,
443 }
444 );
445 assert_eq!(
446 parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),
447 ChannelMembership::default()
448 );
449 assert_eq!(
450 ChannelKind::from_membership_type(Some("private")),
451 ChannelKind::Private
452 );
453 assert_eq!(
454 ChannelKind::from_membership_type(None),
455 ChannelKind::Standard
456 );
457 }
458
459 #[tokio::test]
460 async fn set_channel_shown_reads_the_conversation_first() {
461 let transport = canned(vec![(
462 200,
463 json!({"memberProperties": {"isModerator": true}}),
464 )]);
465 let client = ChannelVisibility::with_transport(&transport, "emea");
466 client
467 .set_channel_shown(&standard(), "user-1", false, NOW_MS)
468 .await
469 .unwrap();
470 let urls: Vec<String> = transport
471 .requests
472 .lock()
473 .unwrap()
474 .iter()
475 .map(|request| request.url.clone())
476 .collect();
477 assert_eq!(
478 urls,
479 vec![
480 format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),
481 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
482 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
483 ]
484 );
485 }
486
487 #[tokio::test]
488 async fn a_failed_step_stops_the_chain() {
489 let transport = canned(vec![(200, json!({})), (403, json!({}))]);
490 let client = ChannelVisibility::with_transport(&transport, "emea");
491 let outcome = client
492 .set_channel_shown(&standard(), "user-1", true, NOW_MS)
493 .await;
494 assert!(outcome.is_err());
495 assert_eq!(transport.requests.lock().unwrap().len(), 2);
496 }
497 }
@@ -0,0 +1,497 @@
1use serde_json::{Value, json};
2use session::{Method, Request, Session};
3
4use crate::error::Result;
5use crate::members::{threads_url, user_mri};
6use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success};
7use crate::pins::DEFAULT_REGION;
8
9const FAVORITE_PROPERTY: &str = "favorite";
10const GENERAL_FAVORITE_PROPERTY: &str = "isGeneralChannelFavorite";
11const FOLLOWED_PROPERTY: &str = "isfollowed";
12const PERMANENT_JOIN_QUERY: &str = "requirePermanentJoinedState=true";
13const FAVORITE_MODE_HEADER: &str = "x-ms-favorite-mode";
14const FAVORITE_MODE_MANUAL: &str = "manual";
15const HIDDEN_MEMBERSHIP_SECONDS: i64 = 1_209_600;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ChannelKind {
19 Standard,
20 Private,
21 Shared,
22}
23
24impl ChannelKind {
25 pub fn from_membership_type(membership_type: Option<&str>) -> Self {
26 match membership_type.map(str::to_ascii_lowercase).as_deref() {
27 Some("private") => ChannelKind::Private,
28 Some("shared") => ChannelKind::Shared,
29 _ => ChannelKind::Standard,
30 }
31 }
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct ChannelTarget<'a> {
36 pub channel_id: &'a str,
37 pub general: bool,
38 pub kind: ChannelKind,
39}
40
41/// The own member state of a channel conversation that decides Teams' show and hide steps.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
43pub struct ChannelMembership {
44 pub moderator: bool,
45 pub explicitly_added: bool,
46 pub followed: bool,
47}
48
49fn truthy(value: Option<&Value>) -> bool {
50 match value {
51 Some(Value::Bool(flag)) => *flag,
52 Some(Value::String(text)) => !text.is_empty(),
53 Some(Value::Number(number)) => number.as_f64().is_some_and(|number| number != 0.),
54 Some(Value::Array(_) | Value::Object(_)) => true,
55 _ => false,
56 }
57}
58
59pub fn parse_channel_membership(conversation: &Value) -> ChannelMembership {
60 let member = conversation.get("memberProperties");
61 ChannelMembership {
62 moderator: truthy(member.and_then(|member| member.get("isModerator"))),
63 explicitly_added: truthy(member.and_then(|member| member.get("explicitlyAdded"))),
64 followed: truthy(conversation.pointer(&format!("/properties/{FOLLOWED_PROPERTY}"))),
65 }
66}
67
68/// Teams joins the user to a standard channel thread before it changes the channel's visibility.
69pub fn joins_thread(kind: ChannelKind, membership: ChannelMembership) -> bool {
70 let permanently_joined = kind == ChannelKind::Private
71 || (kind == ChannelKind::Shared && membership.explicitly_added)
72 || membership.moderator;
73 !permanently_joined
74}
75
76pub fn membership_expiration(shown: bool, now_ms: i64) -> i64 {
77 if shown {
78 0
79 } else {
80 (now_ms + 999).div_euclid(1000) + HIDDEN_MEMBERSHIP_SECONDS
81 }
82}
83
84pub struct ChannelVisibility<T: MessageTransport = SessionMessageTransport> {
85 transport: T,
86 conversations_url: String,
87 threads_url: String,
88}
89
90impl ChannelVisibility<SessionMessageTransport> {
91 pub fn new(session: &Session) -> Self {
92 ChannelVisibility::with_transport(SessionMessageTransport::new(session), DEFAULT_REGION)
93 }
94}
95
96impl<T: MessageTransport> ChannelVisibility<T> {
97 pub fn with_transport(transport: T, region: &str) -> Self {
98 ChannelVisibility {
99 transport,
100 conversations_url: format!(
101 "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations"
102 ),
103 threads_url: threads_url(region),
104 }
105 }
106
107 pub fn conversation_request(&self, conversation_id: &str) -> Request {
108 Request::get(format!(
109 "{}/{}?view=msnp24Equivalent",
110 self.conversations_url,
111 encode(conversation_id)
112 ))
113 }
114
115 fn property_request(&self, conversation_id: &str, name: &str, value: Value) -> Request {
116 Request::with_body(
117 Method::Put,
118 format!(
119 "{}/{}/properties?name={name}",
120 self.conversations_url,
121 encode(conversation_id)
122 ),
123 json!({ name: value }),
124 )
125 }
126
127 pub fn favorite_request(&self, channel_id: &str, shown: bool) -> Request {
128 let mut request =
129 self.property_request(channel_id, FAVORITE_PROPERTY, json!(shown.to_string()));
130 if shown {
131 request.url = format!("{}&{PERMANENT_JOIN_QUERY}", request.url);
132 request
133 .headers
134 .push((FAVORITE_MODE_HEADER.into(), FAVORITE_MODE_MANUAL.into()));
135 }
136 request
137 }
138
139 pub fn general_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
140 self.property_request(
141 team_thread_id,
142 GENERAL_FAVORITE_PROPERTY,
143 json!(shown.to_string()),
144 )
145 }
146
147 pub fn team_favorite_request(&self, team_thread_id: &str, shown: bool) -> Request {
148 self.property_request(team_thread_id, FAVORITE_PROPERTY, json!(shown.to_string()))
149 }
150
151 pub fn unfollow_request(&self, channel_id: &str) -> Request {
152 self.property_request(channel_id, FOLLOWED_PROPERTY, json!(false))
153 }
154
155 pub fn membership_request(
156 &self,
157 channel_id: &str,
158 own_user_id: &str,
159 shown: bool,
160 now_ms: i64,
161 ) -> Request {
162 Request::with_body(
163 Method::Put,
164 format!(
165 "{}/{}/members/{}",
166 self.threads_url,
167 encode(channel_id),
168 user_mri(own_user_id)
169 ),
170 json!({ "expiration": membership_expiration(shown, now_ms) }),
171 )
172 }
173
174 /// Teams' order for a channel other than General: join step, `favorite`, then `isfollowed`.
175 pub fn channel_requests(
176 &self,
177 target: &ChannelTarget<'_>,
178 membership: ChannelMembership,
179 own_user_id: &str,
180 shown: bool,
181 now_ms: i64,
182 ) -> Vec<Request> {
183 if target.general {
184 return vec![self.general_favorite_request(target.channel_id, shown)];
185 }
186 let mut requests = Vec::new();
187 if joins_thread(target.kind, membership) {
188 requests.push(self.membership_request(target.channel_id, own_user_id, shown, now_ms));
189 }
190 requests.push(self.favorite_request(target.channel_id, shown));
191 if !shown || membership.followed {
192 requests.push(self.unfollow_request(target.channel_id));
193 }
194 requests
195 }
196
197 pub async fn set_channel_shown(
198 &self,
199 target: &ChannelTarget<'_>,
200 own_user_id: &str,
201 shown: bool,
202 now_ms: i64,
203 ) -> Result<()> {
204 let membership = if target.general {
205 ChannelMembership::default()
206 } else {
207 let answer = self
208 .transport
209 .send(self.conversation_request(target.channel_id))
210 .await?;
211 ensure_success(&answer)?;
212 parse_channel_membership(&answer.body)
213 };
214 for request in self.channel_requests(target, membership, own_user_id, shown, now_ms) {
215 ensure_success(&self.transport.send(request).await?)?;
216 }
217 Ok(())
218 }
219
220 pub async fn set_team_shown(&self, team_thread_id: &str, shown: bool) -> Result<()> {
221 let answer = self
222 .transport
223 .send(self.team_favorite_request(team_thread_id, shown))
224 .await?;
225 ensure_success(&answer)
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use std::collections::VecDeque;
232 use std::sync::Mutex;
233
234 use session::ApiResponse;
235
236 use super::*;
237
238 const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1";
239 const CHANNEL: &str = "19:abc@thread.tacv2";
240 const ENCODED: &str = "19%3Aabc%40thread.tacv2";
241 const NOW_MS: i64 = 1_791_368_000_500;
242
243 struct Canned {
244 requests: Mutex<Vec<Request>>,
245 answers: Mutex<VecDeque<(u16, Value)>>,
246 }
247
248 impl MessageTransport for &Canned {
249 async fn send(&self, request: Request) -> Result<ApiResponse> {
250 self.requests.lock().unwrap().push(request);
251 let (status, body) = self
252 .answers
253 .lock()
254 .unwrap()
255 .pop_front()
256 .unwrap_or((200, Value::Null));
257 Ok(ApiResponse {
258 status,
259 body,
260 retry_after: None,
261 })
262 }
263 }
264
265 fn canned(answers: Vec<(u16, Value)>) -> Canned {
266 Canned {
267 requests: Mutex::new(Vec::new()),
268 answers: Mutex::new(answers.into()),
269 }
270 }
271
272 fn standard() -> ChannelTarget<'static> {
273 ChannelTarget {
274 channel_id: CHANNEL,
275 general: false,
276 kind: ChannelKind::Standard,
277 }
278 }
279
280 fn summary(request: &Request) -> (String, String, Option<Value>) {
281 (
282 request.method.as_str().to_owned(),
283 request.url.clone(),
284 request.body.clone(),
285 )
286 }
287
288 #[test]
289 fn showing_a_standard_channel_joins_then_favorites_with_the_manual_mode() {
290 let transport = canned(Vec::new());
291 let client = ChannelVisibility::with_transport(&transport, "emea");
292 let requests = client.channel_requests(
293 &standard(),
294 ChannelMembership::default(),
295 "user-1",
296 true,
297 NOW_MS,
298 );
299 let summaries: Vec<_> = requests.iter().map(summary).collect();
300 assert_eq!(
301 summaries,
302 vec![
303 (
304 "PUT".to_owned(),
305 format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
306 Some(json!({"expiration": 0})),
307 ),
308 (
309 "PUT".to_owned(),
310 format!(
311 "{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite&requirePermanentJoinedState=true"
312 ),
313 Some(json!({"favorite": "true"})),
314 ),
315 ]
316 );
317 assert_eq!(
318 requests[1].headers,
319 vec![("x-ms-favorite-mode".to_owned(), "manual".to_owned())]
320 );
321 }
322
323 #[test]
324 fn hiding_sets_a_two_week_expiration_and_unfollows() {
325 let transport = canned(Vec::new());
326 let client = ChannelVisibility::with_transport(&transport, "emea");
327 let requests = client.channel_requests(
328 &standard(),
329 ChannelMembership::default(),
330 "8:orgid:user-1",
331 false,
332 NOW_MS,
333 );
334 let summaries: Vec<_> = requests.iter().map(summary).collect();
335 assert_eq!(
336 summaries,
337 vec![
338 (
339 "PUT".to_owned(),
340 format!("{BASE}/threads/{ENCODED}/members/8:orgid:user-1"),
341 Some(json!({"expiration": 1_791_368_001 + 1_209_600})),
342 ),
343 (
344 "PUT".to_owned(),
345 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
346 Some(json!({"favorite": "false"})),
347 ),
348 (
349 "PUT".to_owned(),
350 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
351 Some(json!({"isfollowed": false})),
352 ),
353 ]
354 );
355 assert!(requests[1].headers.is_empty());
356 }
357
358 #[test]
359 fn moderators_and_private_members_skip_the_join_step() {
360 let transport = canned(Vec::new());
361 let client = ChannelVisibility::with_transport(&transport, "emea");
362 let moderator = ChannelMembership {
363 moderator: true,
364 ..ChannelMembership::default()
365 };
366 let requests = client.channel_requests(&standard(), moderator, "user-1", true, NOW_MS);
367 assert_eq!(requests.len(), 1);
368 assert!(requests[0].url.contains("name=favorite"));
369 let private = ChannelTarget {
370 kind: ChannelKind::Private,
371 ..standard()
372 };
373 assert!(!joins_thread(private.kind, ChannelMembership::default()));
374 let shared = ChannelMembership {
375 explicitly_added: true,
376 ..ChannelMembership::default()
377 };
378 assert!(!joins_thread(ChannelKind::Shared, shared));
379 assert!(joins_thread(
380 ChannelKind::Shared,
381 ChannelMembership::default()
382 ));
383 }
384
385 #[test]
386 fn showing_a_followed_channel_also_clears_the_follow() {
387 let transport = canned(Vec::new());
388 let client = ChannelVisibility::with_transport(&transport, "emea");
389 let followed = ChannelMembership {
390 moderator: true,
391 followed: true,
392 ..ChannelMembership::default()
393 };
394 let requests = client.channel_requests(&standard(), followed, "user-1", true, NOW_MS);
395 assert_eq!(requests.len(), 2);
396 assert!(requests[1].url.ends_with("name=isfollowed"));
397 }
398
399 #[test]
400 fn general_and_team_visibility_write_one_property() {
401 let transport = canned(Vec::new());
402 let client = ChannelVisibility::with_transport(&transport, "emea");
403 let general = ChannelTarget {
404 general: true,
405 ..standard()
406 };
407 let requests =
408 client.channel_requests(&general, ChannelMembership::default(), "u", false, NOW_MS);
409 assert_eq!(
410 requests.iter().map(summary).collect::<Vec<_>>(),
411 vec![(
412 "PUT".to_owned(),
413 format!(
414 "{BASE}/users/ME/conversations/{ENCODED}/properties?name=isGeneralChannelFavorite"
415 ),
416 Some(json!({"isGeneralChannelFavorite": "false"})),
417 )]
418 );
419 let team = client.team_favorite_request(CHANNEL, true);
420 assert_eq!(
421 summary(&team),
422 (
423 "PUT".to_owned(),
424 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
425 Some(json!({"favorite": "true"})),
426 )
427 );
428 assert!(team.headers.is_empty());
429 }
430
431 #[test]
432 fn membership_follows_javascript_truthiness() {
433 let membership = parse_channel_membership(&json!({
434 "memberProperties": {"isModerator": true, "explicitlyAdded": "true"},
435 "properties": {"isfollowed": "false"},
436 }));
437 assert_eq!(
438 membership,
439 ChannelMembership {
440 moderator: true,
441 explicitly_added: true,
442 followed: true,
443 }
444 );
445 assert_eq!(
446 parse_channel_membership(&json!({"properties": {"isfollowed": ""}})),
447 ChannelMembership::default()
448 );
449 assert_eq!(
450 ChannelKind::from_membership_type(Some("private")),
451 ChannelKind::Private
452 );
453 assert_eq!(
454 ChannelKind::from_membership_type(None),
455 ChannelKind::Standard
456 );
457 }
458
459 #[tokio::test]
460 async fn set_channel_shown_reads_the_conversation_first() {
461 let transport = canned(vec![(
462 200,
463 json!({"memberProperties": {"isModerator": true}}),
464 )]);
465 let client = ChannelVisibility::with_transport(&transport, "emea");
466 client
467 .set_channel_shown(&standard(), "user-1", false, NOW_MS)
468 .await
469 .unwrap();
470 let urls: Vec<String> = transport
471 .requests
472 .lock()
473 .unwrap()
474 .iter()
475 .map(|request| request.url.clone())
476 .collect();
477 assert_eq!(
478 urls,
479 vec![
480 format!("{BASE}/users/ME/conversations/{ENCODED}?view=msnp24Equivalent"),
481 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=favorite"),
482 format!("{BASE}/users/ME/conversations/{ENCODED}/properties?name=isfollowed"),
483 ]
484 );
485 }
486
487 #[tokio::test]
488 async fn a_failed_step_stops_the_chain() {
489 let transport = canned(vec![(200, json!({})), (403, json!({}))]);
490 let client = ChannelVisibility::with_transport(&transport, "emea");
491 let outcome = client
492 .set_channel_shown(&standard(), "user-1", true, NOW_MS)
493 .await;
494 assert!(outcome.is_err());
495 assert_eq!(transport.requests.lock().unwrap().len(), 2);
496 }
497}
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 +171 −3
@@ -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;
@@ -10,13 +13,22 @@ use crate::read_horizon::{self, ReadHorizon};
10 13 const PAGE_SIZE: usize = 200;
11 14 const MAX_PAGES: usize = 100;
12 15 const ALERTS_OFF: &str = "false";
16 const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13 17
14 #[derive(Debug, Clone, PartialEq, Eq)]
18 #[derive(Debug, Clone, PartialEq, Eq, Default)]
15 19 pub struct ConversationState {
16 20 pub id: String,
17 21 pub muted: bool,
18 22 pub hidden: Option<bool>,
19 23 pub read: ReadHorizon,
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 }
20 32 }
21 33
22 34 pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +96,44 @@ impl<T: MessageTransport> Conversations<T> {
84 96 ensure_success(&answer)
85 97 }
86 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
124 /// Teams' "Remove chat history": everything up to this time disappears for the current user only.
125 pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
126 let answer = self
127 .transport
128 .send(clear_history_request(
129 &self.base_url,
130 conversation_id,
131 cleared_until_ms,
132 ))
133 .await?;
134 ensure_success(&answer)
135 }
136
87 137 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 138 let url = format!(
89 139 "{}/{}/properties?name={}",
@@ -118,6 +168,29 @@ impl<T: MessageTransport> Conversations<T> {
118 168 }
119 169 }
120 170
171 pub fn clear_history_request(
172 base_url: &str,
173 conversation_id: &str,
174 cleared_until_ms: i64,
175 ) -> Request {
176 Request::with_body(
177 Method::Put,
178 format!(
179 "{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
180 encode(conversation_id)
181 ),
182 json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
183 )
184 }
185
186 fn history_cleared_ms(conversation: &Value) -> Option<i64> {
187 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
188 value
189 .as_i64()
190 .or_else(|| value.as_str()?.parse().ok())
191 .filter(|millis| *millis > 0)
192 }
193
121 194 /// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122 195 pub fn thread_url(region: &str, thread_id: &str) -> String {
123 196 format!(
@@ -167,6 +240,11 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167 240 muted,
168 241 hidden: hidden_flag(conversation),
169 242 read: ReadHorizon::from_conversation(conversation),
243 notification_settings: conversation["properties"]
244 [chat_notifications::PROPERTY_NAME]
245 .as_str()
246 .map(str::to_owned),
247 history_cleared_ms: history_cleared_ms(conversation),
170 248 })
171 249 })
172 250 .collect())
@@ -209,8 +287,7 @@ mod tests {
209 287 ConversationState {
210 288 id: id.to_owned(),
211 289 muted,
212 hidden: None,
213 read: ReadHorizon::default(),
290 ..Default::default()
214 291 }
215 292 }
216 293
@@ -383,6 +460,52 @@ mod tests {
383 460 assert!(states[0].read.is_unread("8:orgid:me"));
384 461 }
385 462
463 #[tokio::test]
464 async fn clear_history_puts_the_time_as_a_number() {
465 let transport = canned(vec![(200, Value::Null)]);
466 Conversations::with_transport(&transport, "emea")
467 .clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
468 .await
469 .unwrap();
470 let requests = transport.requests.lock().unwrap();
471 assert_eq!(requests[0].method, Method::Put);
472 assert_eq!(
473 requests[0].url,
474 format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
475 );
476 assert_eq!(
477 requests[0].body,
478 Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
479 );
480 }
481
482 #[tokio::test]
483 async fn states_carry_the_clear_history_time_as_text_or_number() {
484 let transport = canned(vec![(
485 200,
486 json!({
487 "conversations": [
488 {"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
489 {"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
490 {"id": "19:c", "properties": {"clearHistoryTime": "0"}},
491 {"id": "19:d"},
492 ],
493 }),
494 )]);
495 let states = Conversations::with_transport(&transport, "emea")
496 .conversation_states()
497 .await
498 .unwrap();
499 let cleared: Vec<Option<i64>> = states
500 .iter()
501 .map(|state| state.history_cleared_ms)
502 .collect();
503 assert_eq!(
504 cleared,
505 [Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
506 );
507 }
508
386 509 #[tokio::test]
387 510 async fn set_read_horizon_puts_the_consumption_horizon_property() {
388 511 let transport = canned(vec![(200, Value::Null)]);
@@ -401,4 +524,49 @@ mod tests {
401 524 Some(json!({"consumptionhorizon": "9;10;0"}))
402 525 );
403 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 }
404 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;
@@ -10,13 +13,22 @@ use crate::read_horizon::{self, ReadHorizon};
10const PAGE_SIZE: usize = 200;
13const PAGE_SIZE: usize = 200;
11const MAX_PAGES: usize = 100;
14const MAX_PAGES: usize = 100;
12const ALERTS_OFF: &str = "false";
15const ALERTS_OFF: &str = "false";
16const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
13
17
14#[derive(Debug, Clone, PartialEq, Eq)]
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
15pub struct ConversationState {
19pub struct ConversationState {
16 pub id: String,
20 pub id: String,
17 pub muted: bool,
21 pub muted: bool,
18 pub hidden: Option<bool>,
22 pub hidden: Option<bool>,
19 pub read: ReadHorizon,
23 pub read: ReadHorizon,
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 }
20}
32}
21
33
22pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
34pub struct Conversations<T: MessageTransport = SessionMessageTransport> {
@@ -84,6 +96,44 @@ impl<T: MessageTransport> Conversations<T> {
84 ensure_success(&answer)
96 ensure_success(&answer)
85 }
97 }
86
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
124 /// Teams' "Remove chat history": everything up to this time disappears for the current user only.
125 pub async fn clear_history(&self, conversation_id: &str, cleared_until_ms: i64) -> Result<()> {
126 let answer = self
127 .transport
128 .send(clear_history_request(
129 &self.base_url,
130 conversation_id,
131 cleared_until_ms,
132 ))
133 .await?;
134 ensure_success(&answer)
135 }
136
87 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
137 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
88 let url = format!(
138 let url = format!(
89 "{}/{}/properties?name={}",
139 "{}/{}/properties?name={}",
@@ -118,6 +168,29 @@ impl<T: MessageTransport> Conversations<T> {
118 }
168 }
119}
169}
120
170
171pub fn clear_history_request(
172 base_url: &str,
173 conversation_id: &str,
174 cleared_until_ms: i64,
175) -> Request {
176 Request::with_body(
177 Method::Put,
178 format!(
179 "{base_url}/{}/properties?name={CLEAR_HISTORY_PROPERTY}",
180 encode(conversation_id)
181 ),
182 json!({ CLEAR_HISTORY_PROPERTY: cleared_until_ms }),
183 )
184}
185
186fn history_cleared_ms(conversation: &Value) -> Option<i64> {
187 let value = &conversation["properties"][CLEAR_HISTORY_PROPERTY];
188 value
189 .as_i64()
190 .or_else(|| value.as_str()?.parse().ok())
191 .filter(|millis| *millis > 0)
192}
193
121/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
194/// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
122pub fn thread_url(region: &str, thread_id: &str) -> String {
195pub fn thread_url(region: &str, thread_id: &str) -> String {
123 format!(
196 format!(
@@ -167,6 +240,11 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
167 muted,
240 muted,
168 hidden: hidden_flag(conversation),
241 hidden: hidden_flag(conversation),
169 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),
247 history_cleared_ms: history_cleared_ms(conversation),
170 })
248 })
171 })
249 })
172 .collect())
250 .collect())
@@ -209,8 +287,7 @@ mod tests {
209 ConversationState {
287 ConversationState {
210 id: id.to_owned(),
288 id: id.to_owned(),
211 muted,
289 muted,
212 hidden: None,
290 ..Default::default()
213 read: ReadHorizon::default(),
214 }
291 }
215 }
292 }
216
293
@@ -383,6 +460,52 @@ mod tests {
383 assert!(states[0].read.is_unread("8:orgid:me"));
460 assert!(states[0].read.is_unread("8:orgid:me"));
384 }
461 }
385
462
463 #[tokio::test]
464 async fn clear_history_puts_the_time_as_a_number() {
465 let transport = canned(vec![(200, Value::Null)]);
466 Conversations::with_transport(&transport, "emea")
467 .clear_history("19:a_b@unq.gbl.spaces", 1_792_200_000_001)
468 .await
469 .unwrap();
470 let requests = transport.requests.lock().unwrap();
471 assert_eq!(requests[0].method, Method::Put);
472 assert_eq!(
473 requests[0].url,
474 format!("{BASE}/19%3Aa_b%40unq.gbl.spaces/properties?name=clearHistoryTime")
475 );
476 assert_eq!(
477 requests[0].body,
478 Some(json!({"clearHistoryTime": 1_792_200_000_001_i64}))
479 );
480 }
481
482 #[tokio::test]
483 async fn states_carry_the_clear_history_time_as_text_or_number() {
484 let transport = canned(vec![(
485 200,
486 json!({
487 "conversations": [
488 {"id": "19:a", "properties": {"clearHistoryTime": "1792200000001"}},
489 {"id": "19:b", "properties": {"clearHistoryTime": 1_792_200_000_002_i64}},
490 {"id": "19:c", "properties": {"clearHistoryTime": "0"}},
491 {"id": "19:d"},
492 ],
493 }),
494 )]);
495 let states = Conversations::with_transport(&transport, "emea")
496 .conversation_states()
497 .await
498 .unwrap();
499 let cleared: Vec<Option<i64>> = states
500 .iter()
501 .map(|state| state.history_cleared_ms)
502 .collect();
503 assert_eq!(
504 cleared,
505 [Some(1_792_200_000_001), Some(1_792_200_000_002), None, None]
506 );
507 }
508
386 #[tokio::test]
509 #[tokio::test]
387 async fn set_read_horizon_puts_the_consumption_horizon_property() {
510 async fn set_read_horizon_puts_the_consumption_horizon_property() {
388 let transport = canned(vec![(200, Value::Null)]);
511 let transport = canned(vec![(200, Value::Null)]);
@@ -401,4 +524,49 @@ mod tests {
401 Some(json!({"consumptionhorizon": "9;10;0"}))
524 Some(json!({"consumptionhorizon": "9;10;0"}))
402 );
525 );
403 }
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 }
404}
572}
crates/chatsvc/src/lib.rs +14 −1
@@ -4,6 +4,9 @@ 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;
9 pub mod channel_visibility;
7 10 pub mod conversations;
8 11 pub mod drafts;
9 12 pub mod emotions;
@@ -46,6 +49,13 @@ pub use cards::{
46 49 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
47 50 };
48 51 pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
52 pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
53 pub use chat_settings::{
54 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
55 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
56 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
57 };
58 pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
49 59 pub use conversations::{ConversationState, Conversations};
50 60 pub use drafts::{ScheduledDraft, ScheduledDrafts};
51 61 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -58,7 +68,10 @@ pub use language_settings::{
58 68 };
59 69 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
60 70 pub use mask::mask_conversation_id;
61 pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
71 pub use members::{
72 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
73 TopicProblem, topic_problem,
74 };
62 75 pub use messages::{ConversationRef, Messages};
63 76 pub use pins::{
64 77 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -4,6 +4,9 @@ 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;
9pub mod channel_visibility;
7pub mod conversations;
10pub mod conversations;
8pub mod drafts;
11pub mod drafts;
9pub mod emotions;
12pub mod emotions;
@@ -46,6 +49,13 @@ pub use cards::{
46 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
49 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
47};
50};
48pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
51pub use channel_notifications::{ChannelNotificationLevel, ChannelNotifications, ChannelSettings};
52pub use chat_notifications::{ChatNotificationMode, ChatNotificationWrite, DesktopNotifications};
53pub use chat_settings::{
54 ActivityAlert, ChatAccountSettings, ChatSettingChange, ChatSettingsClient,
55 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
56 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
57};
58pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
49pub use conversations::{ConversationState, Conversations};
59pub use conversations::{ConversationState, Conversations};
50pub use drafts::{ScheduledDraft, ScheduledDrafts};
60pub use drafts::{ScheduledDraft, ScheduledDrafts};
51pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
61pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -58,7 +68,10 @@ pub use language_settings::{
58};
68};
59pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
69pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
60pub use mask::mask_conversation_id;
70pub use mask::mask_conversation_id;
61pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
71pub use members::{
72 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
73 TopicProblem, topic_problem,
74};
62pub use messages::{ConversationRef, Messages};
75pub use messages::{ConversationRef, Messages};
63pub use pins::{
76pub use pins::{
64 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
77 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
crates/chatsvc/src/members.rs +66 −0
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8 8 const ORGID_PREFIX: &str = "8:orgid:";
9 9 const MEMBER_ROLE: &str = "Admin";
10 10 const DAY_MS: i64 = 86_400_000;
11 const TOPIC_PROPERTY: &str = "topic";
12 pub const MAX_TOPIC_LENGTH: usize = 250;
13 pub const INVALID_TOPIC_CHARACTER: char = ':';
11 14 pub const MAX_HISTORY_DAYS: u32 = 999;
12 15
13 16 /// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80 83 ))
81 84 }
82 85
86 /// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87 pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 Request::with_body(
89 Method::Put,
90 format!(
91 "{}/{}/properties?name={TOPIC_PROPERTY}",
92 threads_url(region),
93 encode(thread_id)
94 ),
95 json!({ TOPIC_PROPERTY: topic }),
96 )
97 }
98
99 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
100 pub enum TopicProblem {
101 TooLong,
102 InvalidCharacter,
103 }
104
105 pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106 if topic.chars().count() > MAX_TOPIC_LENGTH {
107 Some(TopicProblem::TooLong)
108 } else if topic.contains(INVALID_TOPIC_CHARACTER) {
109 Some(TopicProblem::InvalidCharacter)
110 } else {
111 None
112 }
113 }
114
83 115 pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 116 transport: T,
85 117 region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114 146 let request = remove_member_request(&self.region, thread_id, user_id);
115 147 ensure_success(&self.transport.send(request).await?)
116 148 }
149
150 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 let request = topic_request(&self.region, thread_id, topic);
152 ensure_success(&self.transport.send(request).await?)
153 }
117 154 }
118 155
119 156 #[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124 161
125 162 use super::*;
126 163
164 #[test]
165 fn topic_is_put_as_the_thread_property() {
166 let request = topic_request("emea", THREAD, "Release crew");
167 assert_eq!(request.method, Method::Put);
168 assert_eq!(
169 request.url,
170 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171 );
172 assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173 assert_eq!(
174 topic_request("emea", THREAD, "").body,
175 Some(json!({"topic": ""}))
176 );
177 }
178
179 #[test]
180 fn topic_rules_follow_teams() {
181 assert_eq!(topic_problem("Release crew"), None);
182 assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183 assert_eq!(
184 topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185 Some(TopicProblem::TooLong)
186 );
187 assert_eq!(
188 topic_problem("Team: ops"),
189 Some(TopicProblem::InvalidCharacter)
190 );
191 }
192
127 193 const NOW: i64 = 1_792_200_000_000;
128 194 const THREAD: &str = "19:abc@thread.v2";
129 195
@@ -8,6 +8,9 @@ use crate::pins::DEFAULT_REGION;
8const ORGID_PREFIX: &str = "8:orgid:";
8const ORGID_PREFIX: &str = "8:orgid:";
9const MEMBER_ROLE: &str = "Admin";
9const MEMBER_ROLE: &str = "Admin";
10const DAY_MS: i64 = 86_400_000;
10const DAY_MS: i64 = 86_400_000;
11const TOPIC_PROPERTY: &str = "topic";
12pub const MAX_TOPIC_LENGTH: usize = 250;
13pub const INVALID_TOPIC_CHARACTER: char = ':';
11pub const MAX_HISTORY_DAYS: u32 = 999;
14pub const MAX_HISTORY_DAYS: u32 = 999;
12
15
13/// How much chat history new members see, as the Teams add-people dialog offers it.
16/// How much chat history new members see, as the Teams add-people dialog offers it.
@@ -80,6 +83,35 @@ pub fn remove_member_request(region: &str, thread_id: &str, user_id: &str) -> Re
80 ))
83 ))
81}
84}
82
85
86/// Teams renames a group chat by setting the thread property `topic`; an empty topic removes the name.
87pub fn topic_request(region: &str, thread_id: &str, topic: &str) -> Request {
88 Request::with_body(
89 Method::Put,
90 format!(
91 "{}/{}/properties?name={TOPIC_PROPERTY}",
92 threads_url(region),
93 encode(thread_id)
94 ),
95 json!({ TOPIC_PROPERTY: topic }),
96 )
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub enum TopicProblem {
101 TooLong,
102 InvalidCharacter,
103}
104
105pub fn topic_problem(topic: &str) -> Option<TopicProblem> {
106 if topic.chars().count() > MAX_TOPIC_LENGTH {
107 Some(TopicProblem::TooLong)
108 } else if topic.contains(INVALID_TOPIC_CHARACTER) {
109 Some(TopicProblem::InvalidCharacter)
110 } else {
111 None
112 }
113}
114
83pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
115pub struct ThreadMembers<T: MessageTransport = SessionMessageTransport> {
84 transport: T,
116 transport: T,
85 region: String,
117 region: String,
@@ -114,6 +146,11 @@ impl<T: MessageTransport> ThreadMembers<T> {
114 let request = remove_member_request(&self.region, thread_id, user_id);
146 let request = remove_member_request(&self.region, thread_id, user_id);
115 ensure_success(&self.transport.send(request).await?)
147 ensure_success(&self.transport.send(request).await?)
116 }
148 }
149
150 pub async fn set_topic(&self, thread_id: &str, topic: &str) -> Result<()> {
151 let request = topic_request(&self.region, thread_id, topic);
152 ensure_success(&self.transport.send(request).await?)
153 }
117}
154}
118
155
119#[cfg(test)]
156#[cfg(test)]
@@ -124,6 +161,35 @@ mod tests {
124
161
125 use super::*;
162 use super::*;
126
163
164 #[test]
165 fn topic_is_put_as_the_thread_property() {
166 let request = topic_request("emea", THREAD, "Release crew");
167 assert_eq!(request.method, Method::Put);
168 assert_eq!(
169 request.url,
170 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/threads/19%3Aabc%40thread.v2/properties?name=topic"
171 );
172 assert_eq!(request.body, Some(json!({"topic": "Release crew"})));
173 assert_eq!(
174 topic_request("emea", THREAD, "").body,
175 Some(json!({"topic": ""}))
176 );
177 }
178
179 #[test]
180 fn topic_rules_follow_teams() {
181 assert_eq!(topic_problem("Release crew"), None);
182 assert_eq!(topic_problem(&"a".repeat(MAX_TOPIC_LENGTH)), None);
183 assert_eq!(
184 topic_problem(&"a".repeat(MAX_TOPIC_LENGTH + 1)),
185 Some(TopicProblem::TooLong)
186 );
187 assert_eq!(
188 topic_problem("Team: ops"),
189 Some(TopicProblem::InvalidCharacter)
190 );
191 }
192
127 const NOW: i64 = 1_792_200_000_000;
193 const NOW: i64 = 1_792_200_000_000;
128 const THREAD: &str = "19:abc@thread.v2";
194 const THREAD: &str = "19:abc@thread.v2";
129
195
crates/chatsvc/src/settings.rs +72 −0
@@ -9,6 +9,7 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9 9 const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10 10 const TEAMS_ORDER_KEY: &str = "teamsOrder";
11 11 const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12 const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
12 13 const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
13 14 const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
14 15 const MAX_SKIN_TONE: u8 = 5;
@@ -100,6 +101,11 @@ impl<T: MessageTransport> UserSettings<T> {
100 101 .await
101 102 }
102 103
104 pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
105 self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))
106 .await
107 }
108
103 109 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
104 110 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
105 111 let properties = self.properties().await?;
@@ -161,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {
161 167 (tone <= MAX_SKIN_TONE).then_some(tone)
162 168 }
163 169
170 pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {
171 let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {
172 Value::String(text) => serde_json::from_str::<Value>(text).ok()?,
173 other => other.clone(),
174 };
175 entries.as_array().map(|entries| {
176 entries
177 .iter()
178 .filter_map(Value::as_str)
179 .filter(|reaction_id| !reaction_id.is_empty())
180 .map(str::to_owned)
181 .collect()
182 })
183 }
184
185 pub fn default_reactions_value(reaction_ids: &[String]) -> Value {
186 Value::String(Value::from(reaction_ids.to_vec()).to_string())
187 }
188
164 189 pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
165 190 let entries = match properties.get(TEAMS_ORDER_KEY) {
166 191 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
@@ -290,6 +315,53 @@ mod tests {
290 315 assert_eq!(parse_skin_tone(&json!({})), None);
291 316 }
292 317
318 #[test]
319 fn default_reactions_are_read_from_the_json_string_or_an_array() {
320 assert_eq!(
321 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),
322 Some(vec![
323 "like".to_owned(),
324 "heart".to_owned(),
325 "fire".to_owned()
326 ])
327 );
328 assert_eq!(
329 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),
330 Some(vec!["yes".to_owned()])
331 );
332 assert_eq!(
333 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),
334 Some(Vec::new())
335 );
336 assert_eq!(parse_default_reactions(&json!({})), None);
337 assert_eq!(
338 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),
339 None
340 );
341 }
342
343 #[tokio::test]
344 async fn default_reactions_are_put_as_a_json_string() {
345 let transport = Canned {
346 answers: Mutex::new(vec![(200, Value::Null)].into()),
347 requests: Mutex::new(Vec::new()),
348 };
349 UserSettings::with_transport(&transport, "emea")
350 .set_default_reactions(&["like".to_owned(), "fire".to_owned()])
351 .await
352 .unwrap();
353 let requests = transport.requests.lock().unwrap();
354 assert_eq!(requests[0].method, Method::Put);
355 assert_eq!(
356 requests[0].url,
357 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"
358 );
359 assert_eq!(
360 requests[0].body,
361 Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))
362 );
363 }
364
293 365 #[test]
294 366 fn unset_fields_use_the_teams_defaults() {
295 367 let parsed = parse_chat_sections(&json!({}));
@@ -9,6 +9,7 @@ const SETTINGS_KEY: &str = "simpleCollabUserSettings";
9const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
9const SETTINGS_ID: &str = "simpleCollabUserSettingsId";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
10const TEAMS_ORDER_KEY: &str = "teamsOrder";
11const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
11const SKIN_TONE_KEY: &str = "preferredSkinToneIndex";
12const DEFAULT_REACTIONS_KEY: &str = "defaultMessageReactions";
12const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
13const APP_HORIZON_KEY: &str = "appConsumptionHorizon";
13const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
14const APP_HORIZON_APPS: [&str; 3] = ["chat", "channel", "engage_community"];
14const MAX_SKIN_TONE: u8 = 5;
15const MAX_SKIN_TONE: u8 = 5;
@@ -100,6 +101,11 @@ impl<T: MessageTransport> UserSettings<T> {
100 .await
101 .await
101 }
102 }
102
103
104 pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
105 self.set_property(DEFAULT_REACTIONS_KEY, default_reactions_value(reaction_ids))
106 .await
107 }
108
103 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
109 /// Teams' "Mark all as read" for channels: one write, the channel entry of `appConsumptionHorizon` moves to now.
104 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
110 pub async fn mark_all_channels_read(&self, now_ms: i64) -> Result<AppConsumptionHorizon> {
105 let properties = self.properties().await?;
111 let properties = self.properties().await?;
@@ -161,6 +167,25 @@ pub fn parse_skin_tone(properties: &Value) -> Option<u8> {
161 (tone <= MAX_SKIN_TONE).then_some(tone)
167 (tone <= MAX_SKIN_TONE).then_some(tone)
162}
168}
163
169
170pub fn parse_default_reactions(properties: &Value) -> Option<Vec<String>> {
171 let entries = match properties.get(DEFAULT_REACTIONS_KEY)? {
172 Value::String(text) => serde_json::from_str::<Value>(text).ok()?,
173 other => other.clone(),
174 };
175 entries.as_array().map(|entries| {
176 entries
177 .iter()
178 .filter_map(Value::as_str)
179 .filter(|reaction_id| !reaction_id.is_empty())
180 .map(str::to_owned)
181 .collect()
182 })
183}
184
185pub fn default_reactions_value(reaction_ids: &[String]) -> Value {
186 Value::String(Value::from(reaction_ids.to_vec()).to_string())
187}
188
164pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
189pub fn parse_teams_order(properties: &Value) -> Vec<(String, i64)> {
165 let entries = match properties.get(TEAMS_ORDER_KEY) {
190 let entries = match properties.get(TEAMS_ORDER_KEY) {
166 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
191 Some(Value::String(text)) => serde_json::from_str::<Value>(text).ok(),
@@ -290,6 +315,53 @@ mod tests {
290 assert_eq!(parse_skin_tone(&json!({})), None);
315 assert_eq!(parse_skin_tone(&json!({})), None);
291 }
316 }
292
317
318 #[test]
319 fn default_reactions_are_read_from_the_json_string_or_an_array() {
320 assert_eq!(
321 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: r#"["like","heart","fire"]"#})),
322 Some(vec![
323 "like".to_owned(),
324 "heart".to_owned(),
325 "fire".to_owned()
326 ])
327 );
328 assert_eq!(
329 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: ["yes", "", 3]})),
330 Some(vec!["yes".to_owned()])
331 );
332 assert_eq!(
333 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "[]"})),
334 Some(Vec::new())
335 );
336 assert_eq!(parse_default_reactions(&json!({})), None);
337 assert_eq!(
338 parse_default_reactions(&json!({DEFAULT_REACTIONS_KEY: "not json"})),
339 None
340 );
341 }
342
343 #[tokio::test]
344 async fn default_reactions_are_put_as_a_json_string() {
345 let transport = Canned {
346 answers: Mutex::new(vec![(200, Value::Null)].into()),
347 requests: Mutex::new(Vec::new()),
348 };
349 UserSettings::with_transport(&transport, "emea")
350 .set_default_reactions(&["like".to_owned(), "fire".to_owned()])
351 .await
352 .unwrap();
353 let requests = transport.requests.lock().unwrap();
354 assert_eq!(requests[0].method, Method::Put);
355 assert_eq!(
356 requests[0].url,
357 "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/properties?name=defaultMessageReactions"
358 );
359 assert_eq!(
360 requests[0].body,
361 Some(json!({"defaultMessageReactions": r#"["like","fire"]"#}))
362 );
363 }
364
293 #[test]
365 #[test]
294 fn unset_fields_use_the_teams_defaults() {
366 fn unset_fields_use_the_teams_defaults() {
295 let parsed = parse_chat_sections(&json!({}));
367 let parsed = parse_chat_sections(&json!({}));
crates/core/src/actions.rs +29 −0
@@ -9,6 +9,7 @@ use store::MessageRecord;
9 9 use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10 10 use crate::error::{Error, Result};
11 11 use crate::external_image::external_image_url;
12 use crate::hidden_chats::cleared_until_ms;
12 13 use crate::links::LinkPreview;
13 14 use crate::mapping::message_record;
14 15 use crate::markdown::markdown_to_html;
@@ -482,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {
482 483 Ok(())
483 484 }
484 485
486 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
487 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
488 let last_message_at = self
489 .store
490 .chat(chat_id)?
491 .and_then(|chat| chat.last_message_at);
492 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
493 self.remote
494 .clear_chat_history(chat_id, cleared_until_ms)
495 .await?;
496 self.with_locally_hidden(|locally| {
497 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
498 })?;
499 self.store.remove_chats(&[chat_id.to_owned()])?;
500 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
501 Ok(())
502 }
503
504 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
505 self.remote.set_chat_topic(chat_id, topic).await?;
506 if let Some(mut chat) = self.store.chat(chat_id)? {
507 chat.title = topic.to_owned();
508 self.store.upsert_chats(std::slice::from_ref(&chat))?;
509 }
510 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
511 Ok(())
512 }
513
485 514 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
486 515 let user_id = self.my_user_id().await?;
487 516 self.remote.remove_chat_member(chat_id, &user_id).await?;
@@ -9,6 +9,7 @@ use store::MessageRecord;
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9use crate::engine::{Conversation, META_USER_ID, SyncEngine};
10use crate::error::{Error, Result};
10use crate::error::{Error, Result};
11use crate::external_image::external_image_url;
11use crate::external_image::external_image_url;
12use crate::hidden_chats::cleared_until_ms;
12use crate::links::LinkPreview;
13use crate::links::LinkPreview;
13use crate::mapping::message_record;
14use crate::mapping::message_record;
14use crate::markdown::markdown_to_html;
15use crate::markdown::markdown_to_html;
@@ -482,6 +483,34 @@ impl<R: Remote> SyncEngine<R> {
482 Ok(())
483 Ok(())
483 }
484 }
484
485
486 /// Teams' "Remove chat history": the chat stays hidden until a message newer than the last one.
487 pub async fn remove_chat_history(&self, chat_id: &str) -> Result<()> {
488 let last_message_at = self
489 .store
490 .chat(chat_id)?
491 .and_then(|chat| chat.last_message_at);
492 let cleared_until_ms = cleared_until_ms(last_message_at, Utc::now());
493 self.remote
494 .clear_chat_history(chat_id, cleared_until_ms)
495 .await?;
496 self.with_locally_hidden(|locally| {
497 locally.hide(chat_id, last_message_at.unwrap_or_else(Utc::now))
498 })?;
499 self.store.remove_chats(&[chat_id.to_owned()])?;
500 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
501 Ok(())
502 }
503
504 pub async fn rename_chat(&self, chat_id: &str, topic: &str) -> Result<()> {
505 self.remote.set_chat_topic(chat_id, topic).await?;
506 if let Some(mut chat) = self.store.chat(chat_id)? {
507 chat.title = topic.to_owned();
508 self.store.upsert_chats(std::slice::from_ref(&chat))?;
509 }
510 let _ = self.events.send(crate::events::CoreEvent::SidebarChanged);
511 Ok(())
512 }
513
485 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
514 pub async fn leave_chat(&self, chat_id: &str) -> Result<()> {
486 let user_id = self.my_user_id().await?;
515 let user_id = self.my_user_id().await?;
487 self.remote.remove_chat_member(chat_id, &user_id).await?;
516 self.remote.remove_chat_member(chat_id, &user_id).await?;
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/channel_visibility.rs added +76 −0
@@ -0,0 +1,76 @@
1 use chatsvc::{ChannelKind, ChannelTarget};
2 use chrono::Utc;
3
4 use crate::engine::SyncEngine;
5 use crate::error::{Error, Result};
6 use crate::events::CoreEvent;
7 use crate::message_link::{ChannelAddress, channel_link, team_link};
8 use crate::remote::Remote;
9
10 impl<R: Remote> SyncEngine<R> {
11 pub async fn set_channel_pinned(&self, channel_id: &str, pinned: bool) -> Result<()> {
12 let channel_ids = self
13 .folder_source()?
14 .set_channel_pinned(channel_id, pinned)
15 .await?;
16 self.store.replace_pinned_channels(&channel_ids)?;
17 let _ = self.events.send(CoreEvent::FoldersChanged);
18 Ok(())
19 }
20
21 pub async fn set_channel_shown(&self, channel_id: &str, shown: bool) -> Result<()> {
22 let channel = self
23 .store
24 .channel(channel_id)?
25 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
26 let general = self.store.team_thread_id(&channel.team_id)?.as_deref() == Some(channel_id);
27 let own_user_id = self.my_user_id().await?;
28 let target = ChannelTarget {
29 channel_id,
30 general,
31 kind: ChannelKind::from_membership_type(channel.membership_type.as_deref()),
32 };
33 self.folder_source()?
34 .set_channel_shown(target, &own_user_id, shown, Utc::now().timestamp_millis())
35 .await?;
36 self.store.set_channel_hidden(channel_id, !shown)?;
37 let _ = self.events.send(CoreEvent::SidebarChanged);
38 Ok(())
39 }
40
41 pub async fn set_team_shown(&self, team_id: &str, shown: bool) -> Result<()> {
42 let team_thread_id = self.known_team_thread_id(team_id)?;
43 self.folder_source()?
44 .set_team_shown(&team_thread_id, shown)
45 .await?;
46 self.store.set_team_hidden(team_id, !shown)?;
47 let _ = self.events.send(CoreEvent::SidebarChanged);
48 Ok(())
49 }
50
51 pub async fn channel_link(&self, channel_id: &str) -> Result<String> {
52 let channel = self
53 .store
54 .channel(channel_id)?
55 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
56 Ok(channel_link(&ChannelAddress {
57 tenant_id: self.my_tenant_id_from_any_chat().await?,
58 group_id: channel.team_id,
59 channel_id: channel.id,
60 channel_name: channel.name,
61 membership_type: channel.membership_type,
62 }))
63 }
64
65 pub async fn team_link(&self, team_id: &str) -> Result<String> {
66 let team_thread_id = self.known_team_thread_id(team_id)?;
67 let tenant_id = self.my_tenant_id_from_any_chat().await?;
68 Ok(team_link(&team_thread_id, team_id, &tenant_id))
69 }
70
71 fn known_team_thread_id(&self, team_id: &str) -> Result<String> {
72 self.store
73 .team_thread_id(team_id)?
74 .ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
75 }
76 }
@@ -0,0 +1,76 @@
1use chatsvc::{ChannelKind, ChannelTarget};
2use chrono::Utc;
3
4use crate::engine::SyncEngine;
5use crate::error::{Error, Result};
6use crate::events::CoreEvent;
7use crate::message_link::{ChannelAddress, channel_link, team_link};
8use crate::remote::Remote;
9
10impl<R: Remote> SyncEngine<R> {
11 pub async fn set_channel_pinned(&self, channel_id: &str, pinned: bool) -> Result<()> {
12 let channel_ids = self
13 .folder_source()?
14 .set_channel_pinned(channel_id, pinned)
15 .await?;
16 self.store.replace_pinned_channels(&channel_ids)?;
17 let _ = self.events.send(CoreEvent::FoldersChanged);
18 Ok(())
19 }
20
21 pub async fn set_channel_shown(&self, channel_id: &str, shown: bool) -> Result<()> {
22 let channel = self
23 .store
24 .channel(channel_id)?
25 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
26 let general = self.store.team_thread_id(&channel.team_id)?.as_deref() == Some(channel_id);
27 let own_user_id = self.my_user_id().await?;
28 let target = ChannelTarget {
29 channel_id,
30 general,
31 kind: ChannelKind::from_membership_type(channel.membership_type.as_deref()),
32 };
33 self.folder_source()?
34 .set_channel_shown(target, &own_user_id, shown, Utc::now().timestamp_millis())
35 .await?;
36 self.store.set_channel_hidden(channel_id, !shown)?;
37 let _ = self.events.send(CoreEvent::SidebarChanged);
38 Ok(())
39 }
40
41 pub async fn set_team_shown(&self, team_id: &str, shown: bool) -> Result<()> {
42 let team_thread_id = self.known_team_thread_id(team_id)?;
43 self.folder_source()?
44 .set_team_shown(&team_thread_id, shown)
45 .await?;
46 self.store.set_team_hidden(team_id, !shown)?;
47 let _ = self.events.send(CoreEvent::SidebarChanged);
48 Ok(())
49 }
50
51 pub async fn channel_link(&self, channel_id: &str) -> Result<String> {
52 let channel = self
53 .store
54 .channel(channel_id)?
55 .ok_or_else(|| Error::UnknownConversation(channel_id.to_owned()))?;
56 Ok(channel_link(&ChannelAddress {
57 tenant_id: self.my_tenant_id_from_any_chat().await?,
58 group_id: channel.team_id,
59 channel_id: channel.id,
60 channel_name: channel.name,
61 membership_type: channel.membership_type,
62 }))
63 }
64
65 pub async fn team_link(&self, team_id: &str) -> Result<String> {
66 let team_thread_id = self.known_team_thread_id(team_id)?;
67 let tenant_id = self.my_tenant_id_from_any_chat().await?;
68 Ok(team_link(&team_thread_id, team_id, &tenant_id))
69 }
70
71 fn known_team_thread_id(&self, team_id: &str) -> Result<String> {
72 self.store
73 .team_thread_id(team_id)?
74 .ok_or_else(|| Error::UnknownConversation(team_id.to_owned()))
75 }
76}
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/default_reactions.rs added +51 −0
@@ -0,0 +1,51 @@
1 use store::Store;
2
3 use crate::error::Result;
4
5 const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";
6 pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];
7 pub const DEFAULT_REACTION_SLOTS: usize = 5;
8
9 pub fn store_account_default_reactions(
10 store: &Store,
11 reaction_ids: Option<&[String]>,
12 ) -> Result<()> {
13 let value = reaction_ids
14 .map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())
15 .unwrap_or_default();
16 Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)
17 }
18
19 /// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.
20 pub fn default_reactions(store: &Store) -> Vec<String> {
21 store
22 .meta(META_ACCOUNT_DEFAULT_REACTIONS)
23 .ok()
24 .flatten()
25 .filter(|stored| !stored.is_empty())
26 .and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())
27 .unwrap_or_else(|| {
28 TEAMS_DEFAULT_REACTIONS
29 .iter()
30 .map(|reaction_id| (*reaction_id).to_owned())
31 .collect()
32 })
33 }
34
35 #[cfg(test)]
36 mod tests {
37 use super::*;
38
39 #[test]
40 fn falls_back_to_the_teams_set_until_the_account_has_one() {
41 let store = Store::open_in_memory().unwrap();
42 assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
43 let saved = vec!["fire".to_owned(), "like".to_owned()];
44 store_account_default_reactions(&store, Some(&saved)).unwrap();
45 assert_eq!(default_reactions(&store), saved);
46 store_account_default_reactions(&store, Some(&[])).unwrap();
47 assert!(default_reactions(&store).is_empty());
48 store_account_default_reactions(&store, None).unwrap();
49 assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
50 }
51 }
@@ -0,0 +1,51 @@
1use store::Store;
2
3use crate::error::Result;
4
5const META_ACCOUNT_DEFAULT_REACTIONS: &str = "default_reactions_account";
6pub const TEAMS_DEFAULT_REACTIONS: [&str; 4] = ["like", "heart", "laugh", "surprised"];
7pub const DEFAULT_REACTION_SLOTS: usize = 5;
8
9pub fn store_account_default_reactions(
10 store: &Store,
11 reaction_ids: Option<&[String]>,
12) -> Result<()> {
13 let value = reaction_ids
14 .map(|reaction_ids| serde_json::Value::from(reaction_ids.to_vec()).to_string())
15 .unwrap_or_default();
16 Ok(store.set_meta(META_ACCOUNT_DEFAULT_REACTIONS, &value)?)
17}
18
19/// The account setting `defaultMessageReactions`, Teams' own default set when it was never saved.
20pub fn default_reactions(store: &Store) -> Vec<String> {
21 store
22 .meta(META_ACCOUNT_DEFAULT_REACTIONS)
23 .ok()
24 .flatten()
25 .filter(|stored| !stored.is_empty())
26 .and_then(|stored| serde_json::from_str::<Vec<String>>(&stored).ok())
27 .unwrap_or_else(|| {
28 TEAMS_DEFAULT_REACTIONS
29 .iter()
30 .map(|reaction_id| (*reaction_id).to_owned())
31 .collect()
32 })
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn falls_back_to_the_teams_set_until_the_account_has_one() {
41 let store = Store::open_in_memory().unwrap();
42 assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
43 let saved = vec!["fire".to_owned(), "like".to_owned()];
44 store_account_default_reactions(&store, Some(&saved)).unwrap();
45 assert_eq!(default_reactions(&store), saved);
46 store_account_default_reactions(&store, Some(&[])).unwrap();
47 assert!(default_reactions(&store).is_empty());
48 store_account_default_reactions(&store, None).unwrap();
49 assert_eq!(default_reactions(&store), TEAMS_DEFAULT_REACTIONS);
50 }
51}
crates/core/src/folders.rs +120 −9
@@ -3,10 +3,13 @@ use std::future::Future;
3 3 use std::pin::Pin;
4 4 use std::sync::{Arc, Mutex};
5 5
6 use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
6 use chatsvc::settings::{
7 parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8 };
7 9 use chatsvc::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
9 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
10 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
11 ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
12 pins::SessionTransport,
10 13 };
11 14 use chrono::Utc;
12 15 use serde_json::Value;
@@ -70,6 +73,15 @@ pub trait FolderSource: Send + Sync {
70 73 fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
71 74 Box::pin(async { Ok(()) })
72 75 }
76 fn default_reactions(&self) -> Option<Vec<String>> {
77 None
78 }
79 fn set_default_reactions<'a>(
80 &'a self,
81 _reaction_ids: &'a [String],
82 ) -> BoxFuture<'a, Result<()>> {
83 Box::pin(async { Ok(()) })
84 }
73 85 fn set_section_enabled(&self, section: ChatSection, enabled: bool)
74 86 -> BoxFuture<'_, Result<()>>;
75 87 fn set_folder_expanded<'a>(
@@ -89,14 +101,39 @@ pub trait FolderSource: Send + Sync {
89 101 folder_id: &'a str,
90 102 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91 103 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
104 fn set_channel_pinned<'a>(
105 &'a self,
106 _channel_id: &'a str,
107 _pinned: bool,
108 ) -> BoxFuture<'a, Result<Vec<String>>> {
109 Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })
110 }
111 fn set_channel_shown<'a>(
112 &'a self,
113 _target: ChannelTarget<'a>,
114 _own_user_id: &'a str,
115 _shown: bool,
116 _now_ms: i64,
117 ) -> BoxFuture<'a, Result<()>> {
118 Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })
119 }
120 fn set_team_shown<'a>(
121 &'a self,
122 _team_thread_id: &'a str,
123 _shown: bool,
124 ) -> BoxFuture<'a, Result<()>> {
125 Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
126 }
92 127 }
93 128
94 129 pub struct ChatsvcFolderSource {
95 130 pins: Pins<SessionTransport>,
131 visibility: ChannelVisibility,
96 132 settings: UserSettings,
97 133 channel_settings: ChannelSettings,
98 134 properties: Mutex<Option<Value>>,
99 135 skin_tone: Mutex<Option<u8>>,
136 default_reactions: Mutex<Option<Vec<String>>>,
100 137 group_ids: Mutex<HashMap<String, String>>,
101 138 }
102 139
@@ -104,10 +141,12 @@ impl ChatsvcFolderSource {
104 141 pub fn new(session: &Session) -> Self {
105 142 ChatsvcFolderSource {
106 143 pins: Pins::new(session),
144 visibility: ChannelVisibility::new(session),
107 145 settings: UserSettings::new(session),
108 146 channel_settings: ChannelSettings::new(session),
109 147 properties: Mutex::new(None),
110 148 skin_tone: Mutex::new(None),
149 default_reactions: Mutex::new(None),
111 150 group_ids: Mutex::new(HashMap::new()),
112 151 }
113 152 }
@@ -122,6 +161,49 @@ impl FolderSource for ChatsvcFolderSource {
122 161 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
123 162 }
124 163
164 fn set_channel_pinned<'a>(
165 &'a self,
166 channel_id: &'a str,
167 pinned: bool,
168 ) -> BoxFuture<'a, Result<Vec<String>>> {
169 Box::pin(async move {
170 let answer = if pinned {
171 self.pins.pin_channel(channel_id).await?
172 } else {
173 self.pins.unpin_channel(channel_id).await?
174 };
175 Ok(answer.channel_ids)
176 })
177 }
178
179 fn set_channel_shown<'a>(
180 &'a self,
181 target: ChannelTarget<'a>,
182 own_user_id: &'a str,
183 shown: bool,
184 now_ms: i64,
185 ) -> BoxFuture<'a, Result<()>> {
186 Box::pin(async move {
187 Ok(self
188 .visibility
189 .set_channel_shown(&target, own_user_id, shown, now_ms)
190 .await?)
191 })
192 }
193
194 fn set_team_shown<'a>(
195 &'a self,
196 team_thread_id: &'a str,
197 shown: bool,
198 ) -> BoxFuture<'a, Result<()>> {
199 Box::pin(async move {
200 Ok(self
201 .visibility
202 .set_team_shown(team_thread_id, shown)
203 .await?)
204 })
205 }
206
125 207 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
126 208 Box::pin(async {
127 209 let layout = self.pins.team_layout().await?;
@@ -152,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {
152 234 let properties = self.settings.properties().await?;
153 235 let sections = parse_chat_sections(&properties);
154 236 *self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
237 *self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);
155 238 *self.properties.lock().unwrap() = Some(properties);
156 239 Ok(sections)
157 240 })
@@ -165,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {
165 248 Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
166 249 }
167 250
251 fn default_reactions(&self) -> Option<Vec<String>> {
252 self.default_reactions.lock().unwrap().clone()
253 }
254
255 fn set_default_reactions<'a>(
256 &'a self,
257 reaction_ids: &'a [String],
258 ) -> BoxFuture<'a, Result<()>> {
259 Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })
260 }
261
168 262 fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
169 263 Box::pin(async {
170 264 let cached = self.properties.lock().unwrap().take();
@@ -480,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {
480 574
481 575 async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
482 576 let outcome = match source.section_settings().await {
483 Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {
484 match source.preferred_skin_tone() {
577 Ok(settings) => self
578 .apply_section_settings(&settings)
579 .and_then(|()| match source.preferred_skin_tone() {
485 580 Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
486 581 None => Ok(()),
487 }
488 }),
582 })
583 .and_then(|()| {
584 crate::default_reactions::store_account_default_reactions(
585 &self.store,
586 source.default_reactions().as_deref(),
587 )
588 }),
489 589 Err(error) => Err(error),
490 590 };
491 591 if let Err(error) = outcome {
@@ -512,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {
512 612 crate::skin_tone::store_account_skin_tone(&self.store, tone)
513 613 }
514 614
615 pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
616 self.folder_source()?
617 .set_default_reactions(reaction_ids)
618 .await?;
619 crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))
620 }
621
515 622 pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
516 623 self.folder_source()?
517 624 .set_folder_expanded(folder_id, expanded)
@@ -567,13 +674,17 @@ impl<R: Remote> SyncEngine<R> {
567 674 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
568 675 }
569 676
570 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
677 pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
571 678 self.folder_source
572 679 .as_ref()
573 680 .ok_or(Error::Unsupported("chat folders without a folder source"))
574 681 }
575 682
576 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
683 pub(crate) fn store_folders(
684 &self,
685 folders: &[ChatFolder],
686 channel_ids: &[String],
687 ) -> Result<()> {
577 688 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
578 689 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
579 690 self.store.replace_folders(&records, channel_ids)?;
@@ -3,10 +3,13 @@ use std::future::Future;
3use std::pin::Pin;
3use std::pin::Pin;
4use std::sync::{Arc, Mutex};
4use std::sync::{Arc, Mutex};
5
5
6use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
6use chatsvc::settings::{
7 parse_chat_sections, parse_default_reactions, parse_skin_tone, parse_teams_order,
8};
7use chatsvc::{
9use chatsvc::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
10 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
9 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
11 ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
12 pins::SessionTransport,
10};
13};
11use chrono::Utc;
14use chrono::Utc;
12use serde_json::Value;
15use serde_json::Value;
@@ -70,6 +73,15 @@ pub trait FolderSource: Send + Sync {
70 fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
73 fn set_skin_tone(&self, _tone: u8) -> BoxFuture<'_, Result<()>> {
71 Box::pin(async { Ok(()) })
74 Box::pin(async { Ok(()) })
72 }
75 }
76 fn default_reactions(&self) -> Option<Vec<String>> {
77 None
78 }
79 fn set_default_reactions<'a>(
80 &'a self,
81 _reaction_ids: &'a [String],
82 ) -> BoxFuture<'a, Result<()>> {
83 Box::pin(async { Ok(()) })
84 }
73 fn set_section_enabled(&self, section: ChatSection, enabled: bool)
85 fn set_section_enabled(&self, section: ChatSection, enabled: bool)
74 -> BoxFuture<'_, Result<()>>;
86 -> BoxFuture<'_, Result<()>>;
75 fn set_folder_expanded<'a>(
87 fn set_folder_expanded<'a>(
@@ -89,14 +101,39 @@ pub trait FolderSource: Send + Sync {
89 folder_id: &'a str,
101 folder_id: &'a str,
90 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
102 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
103 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
104 fn set_channel_pinned<'a>(
105 &'a self,
106 _channel_id: &'a str,
107 _pinned: bool,
108 ) -> BoxFuture<'a, Result<Vec<String>>> {
109 Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })
110 }
111 fn set_channel_shown<'a>(
112 &'a self,
113 _target: ChannelTarget<'a>,
114 _own_user_id: &'a str,
115 _shown: bool,
116 _now_ms: i64,
117 ) -> BoxFuture<'a, Result<()>> {
118 Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })
119 }
120 fn set_team_shown<'a>(
121 &'a self,
122 _team_thread_id: &'a str,
123 _shown: bool,
124 ) -> BoxFuture<'a, Result<()>> {
125 Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
126 }
92}
127}
93
128
94pub struct ChatsvcFolderSource {
129pub struct ChatsvcFolderSource {
95 pins: Pins<SessionTransport>,
130 pins: Pins<SessionTransport>,
131 visibility: ChannelVisibility,
96 settings: UserSettings,
132 settings: UserSettings,
97 channel_settings: ChannelSettings,
133 channel_settings: ChannelSettings,
98 properties: Mutex<Option<Value>>,
134 properties: Mutex<Option<Value>>,
99 skin_tone: Mutex<Option<u8>>,
135 skin_tone: Mutex<Option<u8>>,
136 default_reactions: Mutex<Option<Vec<String>>>,
100 group_ids: Mutex<HashMap<String, String>>,
137 group_ids: Mutex<HashMap<String, String>>,
101}
138}
102
139
@@ -104,10 +141,12 @@ impl ChatsvcFolderSource {
104 pub fn new(session: &Session) -> Self {
141 pub fn new(session: &Session) -> Self {
105 ChatsvcFolderSource {
142 ChatsvcFolderSource {
106 pins: Pins::new(session),
143 pins: Pins::new(session),
144 visibility: ChannelVisibility::new(session),
107 settings: UserSettings::new(session),
145 settings: UserSettings::new(session),
108 channel_settings: ChannelSettings::new(session),
146 channel_settings: ChannelSettings::new(session),
109 properties: Mutex::new(None),
147 properties: Mutex::new(None),
110 skin_tone: Mutex::new(None),
148 skin_tone: Mutex::new(None),
149 default_reactions: Mutex::new(None),
111 group_ids: Mutex::new(HashMap::new()),
150 group_ids: Mutex::new(HashMap::new()),
112 }
151 }
113 }
152 }
@@ -122,6 +161,49 @@ impl FolderSource for ChatsvcFolderSource {
122 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
161 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
123 }
162 }
124
163
164 fn set_channel_pinned<'a>(
165 &'a self,
166 channel_id: &'a str,
167 pinned: bool,
168 ) -> BoxFuture<'a, Result<Vec<String>>> {
169 Box::pin(async move {
170 let answer = if pinned {
171 self.pins.pin_channel(channel_id).await?
172 } else {
173 self.pins.unpin_channel(channel_id).await?
174 };
175 Ok(answer.channel_ids)
176 })
177 }
178
179 fn set_channel_shown<'a>(
180 &'a self,
181 target: ChannelTarget<'a>,
182 own_user_id: &'a str,
183 shown: bool,
184 now_ms: i64,
185 ) -> BoxFuture<'a, Result<()>> {
186 Box::pin(async move {
187 Ok(self
188 .visibility
189 .set_channel_shown(&target, own_user_id, shown, now_ms)
190 .await?)
191 })
192 }
193
194 fn set_team_shown<'a>(
195 &'a self,
196 team_thread_id: &'a str,
197 shown: bool,
198 ) -> BoxFuture<'a, Result<()>> {
199 Box::pin(async move {
200 Ok(self
201 .visibility
202 .set_team_shown(team_thread_id, shown)
203 .await?)
204 })
205 }
206
125 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
207 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
126 Box::pin(async {
208 Box::pin(async {
127 let layout = self.pins.team_layout().await?;
209 let layout = self.pins.team_layout().await?;
@@ -152,6 +234,7 @@ impl FolderSource for ChatsvcFolderSource {
152 let properties = self.settings.properties().await?;
234 let properties = self.settings.properties().await?;
153 let sections = parse_chat_sections(&properties);
235 let sections = parse_chat_sections(&properties);
154 *self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
236 *self.skin_tone.lock().unwrap() = parse_skin_tone(&properties);
237 *self.default_reactions.lock().unwrap() = parse_default_reactions(&properties);
155 *self.properties.lock().unwrap() = Some(properties);
238 *self.properties.lock().unwrap() = Some(properties);
156 Ok(sections)
239 Ok(sections)
157 })
240 })
@@ -165,6 +248,17 @@ impl FolderSource for ChatsvcFolderSource {
165 Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
248 Box::pin(async move { Ok(self.settings.set_skin_tone(tone).await?) })
166 }
249 }
167
250
251 fn default_reactions(&self) -> Option<Vec<String>> {
252 self.default_reactions.lock().unwrap().clone()
253 }
254
255 fn set_default_reactions<'a>(
256 &'a self,
257 reaction_ids: &'a [String],
258 ) -> BoxFuture<'a, Result<()>> {
259 Box::pin(async move { Ok(self.settings.set_default_reactions(reaction_ids).await?) })
260 }
261
168 fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
262 fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> {
169 Box::pin(async {
263 Box::pin(async {
170 let cached = self.properties.lock().unwrap().take();
264 let cached = self.properties.lock().unwrap().take();
@@ -480,12 +574,18 @@ impl<R: Remote> SyncEngine<R> {
480
574
481 async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
575 async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
482 let outcome = match source.section_settings().await {
576 let outcome = match source.section_settings().await {
483 Ok(settings) => self.apply_section_settings(&settings).and_then(|()| {
577 Ok(settings) => self
484 match source.preferred_skin_tone() {
578 .apply_section_settings(&settings)
579 .and_then(|()| match source.preferred_skin_tone() {
485 Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
580 Some(tone) => crate::skin_tone::store_account_skin_tone(&self.store, tone),
486 None => Ok(()),
581 None => Ok(()),
487 }
582 })
488 }),
583 .and_then(|()| {
584 crate::default_reactions::store_account_default_reactions(
585 &self.store,
586 source.default_reactions().as_deref(),
587 )
588 }),
489 Err(error) => Err(error),
589 Err(error) => Err(error),
490 };
590 };
491 if let Err(error) = outcome {
591 if let Err(error) = outcome {
@@ -512,6 +612,13 @@ impl<R: Remote> SyncEngine<R> {
512 crate::skin_tone::store_account_skin_tone(&self.store, tone)
612 crate::skin_tone::store_account_skin_tone(&self.store, tone)
513 }
613 }
514
614
615 pub async fn set_default_reactions(&self, reaction_ids: &[String]) -> Result<()> {
616 self.folder_source()?
617 .set_default_reactions(reaction_ids)
618 .await?;
619 crate::default_reactions::store_account_default_reactions(&self.store, Some(reaction_ids))
620 }
621
515 pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
622 pub async fn set_folder_expanded(&self, folder_id: &str, expanded: bool) -> Result<()> {
516 self.folder_source()?
623 self.folder_source()?
517 .set_folder_expanded(folder_id, expanded)
624 .set_folder_expanded(folder_id, expanded)
@@ -567,13 +674,17 @@ impl<R: Remote> SyncEngine<R> {
567 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
674 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
568 }
675 }
569
676
570 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
677 pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
571 self.folder_source
678 self.folder_source
572 .as_ref()
679 .as_ref()
573 .ok_or(Error::Unsupported("chat folders without a folder source"))
680 .ok_or(Error::Unsupported("chat folders without a folder source"))
574 }
681 }
575
682
576 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
683 pub(crate) fn store_folders(
684 &self,
685 folders: &[ChatFolder],
686 channel_ids: &[String],
687 ) -> Result<()> {
577 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
688 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
578 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
689 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
579 self.store.replace_folders(&records, channel_ids)?;
690 self.store.replace_folders(&records, channel_ids)?;
crates/core/src/hidden_chats.rs +57 −0
@@ -112,6 +112,12 @@ pub(crate) fn resolve_hidden(
112 112 return false;
113 113 }
114 114 }
115 let cleared_until_ms = states
116 .get(&chat.id)
117 .and_then(|state| state.history_cleared_ms);
118 if history_cleared(chat, cleared_until_ms) {
119 return true;
120 }
115 121 if reported == Some(true) {
116 122 locally.hidden_after.remove(&chat.id);
117 123 return true;
@@ -129,6 +135,19 @@ pub(crate) fn resolve_hidden(
129 135 reported.unwrap_or_else(|| graph_hidden(chat))
130 136 }
131 137
138 /// Teams stores the last message time plus one millisecond, or now when the chat has no message.
139 pub(crate) fn cleared_until_ms(last_message_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> i64 {
140 last_message_at.map_or(now.timestamp_millis(), |last| last.timestamp_millis() + 1)
141 }
142
143 /// Teams hides a chat whose history was removed until a newer message arrives.
144 pub(crate) fn history_cleared(chat: &Chat, cleared_until_ms: Option<i64>) -> bool {
145 cleared_until_ms.is_some_and(|cleared_until_ms| {
146 chat.last_message_time()
147 .is_none_or(|newest| newest.timestamp_millis() <= cleared_until_ms)
148 })
149 }
150
132 151 impl<R: Remote> SyncEngine<R> {
133 152 pub(crate) fn with_locally_hidden<T>(
134 153 &self,
@@ -173,10 +192,48 @@ mod tests {
173 192 muted: false,
174 193 hidden,
175 194 read: chatsvc::ReadHorizon::default(),
195 notification_settings: None,
196 history_cleared_ms: None,
176 197 },
177 198 )])
178 199 }
179 200
201 #[test]
202 fn removed_history_ends_one_millisecond_after_the_last_message() {
203 let last = at("2026-10-01T10:00:00Z");
204 assert_eq!(
205 cleared_until_ms(Some(last), now()),
206 last.timestamp_millis() + 1
207 );
208 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
209 }
210
211 #[test]
212 fn removed_history_hides_the_chat_until_a_newer_message() {
213 let mut locally = LocallyHidden::default();
214 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
215 let mut cleared = states(Some(false));
216 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
217 assert!(resolve_hidden(
218 &chat(Some("2026-10-01T10:00:00Z"), false),
219 &cleared,
220 &mut locally,
221 now()
222 ));
223 assert!(resolve_hidden(
224 &chat(None, false),
225 &cleared,
226 &mut locally,
227 now()
228 ));
229 assert!(!resolve_hidden(
230 &chat(Some("2026-10-02T08:00:00Z"), false),
231 &cleared,
232 &mut locally,
233 now()
234 ));
235 }
236
180 237 fn hidden_after(text: &str) -> LocallyHidden {
181 238 let mut locally = LocallyHidden::default();
182 239 locally.hide("19:a", at(text));
@@ -112,6 +112,12 @@ pub(crate) fn resolve_hidden(
112 return false;
112 return false;
113 }
113 }
114 }
114 }
115 let cleared_until_ms = states
116 .get(&chat.id)
117 .and_then(|state| state.history_cleared_ms);
118 if history_cleared(chat, cleared_until_ms) {
119 return true;
120 }
115 if reported == Some(true) {
121 if reported == Some(true) {
116 locally.hidden_after.remove(&chat.id);
122 locally.hidden_after.remove(&chat.id);
117 return true;
123 return true;
@@ -129,6 +135,19 @@ pub(crate) fn resolve_hidden(
129 reported.unwrap_or_else(|| graph_hidden(chat))
135 reported.unwrap_or_else(|| graph_hidden(chat))
130}
136}
131
137
138/// Teams stores the last message time plus one millisecond, or now when the chat has no message.
139pub(crate) fn cleared_until_ms(last_message_at: Option<DateTime<Utc>>, now: DateTime<Utc>) -> i64 {
140 last_message_at.map_or(now.timestamp_millis(), |last| last.timestamp_millis() + 1)
141}
142
143/// Teams hides a chat whose history was removed until a newer message arrives.
144pub(crate) fn history_cleared(chat: &Chat, cleared_until_ms: Option<i64>) -> bool {
145 cleared_until_ms.is_some_and(|cleared_until_ms| {
146 chat.last_message_time()
147 .is_none_or(|newest| newest.timestamp_millis() <= cleared_until_ms)
148 })
149}
150
132impl<R: Remote> SyncEngine<R> {
151impl<R: Remote> SyncEngine<R> {
133 pub(crate) fn with_locally_hidden<T>(
152 pub(crate) fn with_locally_hidden<T>(
134 &self,
153 &self,
@@ -173,10 +192,48 @@ mod tests {
173 muted: false,
192 muted: false,
174 hidden,
193 hidden,
175 read: chatsvc::ReadHorizon::default(),
194 read: chatsvc::ReadHorizon::default(),
195 notification_settings: None,
196 history_cleared_ms: None,
176 },
197 },
177 )])
198 )])
178 }
199 }
179
200
201 #[test]
202 fn removed_history_ends_one_millisecond_after_the_last_message() {
203 let last = at("2026-10-01T10:00:00Z");
204 assert_eq!(
205 cleared_until_ms(Some(last), now()),
206 last.timestamp_millis() + 1
207 );
208 assert_eq!(cleared_until_ms(None, now()), now().timestamp_millis());
209 }
210
211 #[test]
212 fn removed_history_hides_the_chat_until_a_newer_message() {
213 let mut locally = LocallyHidden::default();
214 let cleared_ms = at("2026-10-01T10:00:00Z").timestamp_millis() + 1;
215 let mut cleared = states(Some(false));
216 cleared.get_mut("19:a").unwrap().history_cleared_ms = Some(cleared_ms);
217 assert!(resolve_hidden(
218 &chat(Some("2026-10-01T10:00:00Z"), false),
219 &cleared,
220 &mut locally,
221 now()
222 ));
223 assert!(resolve_hidden(
224 &chat(None, false),
225 &cleared,
226 &mut locally,
227 now()
228 ));
229 assert!(!resolve_hidden(
230 &chat(Some("2026-10-02T08:00:00Z"), false),
231 &cleared,
232 &mut locally,
233 now()
234 ));
235 }
236
180 fn hidden_after(text: &str) -> LocallyHidden {
237 fn hidden_after(text: &str) -> LocallyHidden {
181 let mut locally = LocallyHidden::default();
238 let mut locally = LocallyHidden::default();
182 locally.hide("19:a", at(text));
239 locally.hide("19:a", at(text));
crates/core/src/lib.rs +15 −1
@@ -13,7 +13,10 @@ mod card_widgets;
13 13 mod card_width;
14 14 mod channel_mentions;
15 15 mod channel_sync;
16 mod chat_settings_sync;
17 mod channel_visibility;
16 18 mod chat_paging;
19 mod default_reactions;
17 20 mod download;
18 21 mod draft;
19 22 mod emoticon_tags;
@@ -101,12 +104,22 @@ pub use chatsvc::{
101 104 ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
102 105 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
103 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 };
104 113 pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
105 114 pub use chatsvc::{
106 115 Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
107 116 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
108 117 parse_language_settings, target_patch,
109 118 };
119 pub use default_reactions::{
120 DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
121 store_account_default_reactions,
122 };
110 123 pub use download::LibraryFile;
111 124 pub use draft::{
112 125 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -140,7 +153,8 @@ pub use meeting_join::{
140 153 };
141 154 pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
142 155 pub use message_link::{
143 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
156 ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
157 chat_message_link, team_link,
144 158 };
145 159 pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
146 160 pub use notes_chat::{is_notes_chat, notes_chat_title};
@@ -13,7 +13,10 @@ 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;
17mod channel_visibility;
16mod chat_paging;
18mod chat_paging;
19mod default_reactions;
17mod download;
20mod download;
18mod draft;
21mod draft;
19mod emoticon_tags;
22mod emoticon_tags;
@@ -101,12 +104,22 @@ pub use chatsvc::{
101 ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
104 ForwardResult, Gif, PinnedMessage, PresenceStatus, SavedMessage, ScheduledDraft, StatusNote,
102 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
105 WindowDirection, WorkLocation, WorkLocationKind, WorkLocationSource,
103};
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};
104pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
113pub use chatsvc::{ChatSection, ChatSectionSettings, RecordingPolicy};
105pub use chatsvc::{
114pub use chatsvc::{
106 Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
115 Language, LanguageSettings, MessageLanguage, Translation, TranslationBehavior,
107 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
116 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
108 parse_language_settings, target_patch,
117 parse_language_settings, target_patch,
109};
118};
119pub use default_reactions::{
120 DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
121 store_account_default_reactions,
122};
110pub use download::LibraryFile;
123pub use download::LibraryFile;
111pub use draft::{
124pub use draft::{
112 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
125 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -140,7 +153,8 @@ pub use meeting_join::{
140};
153};
141pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
154pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
142pub use message_link::{
155pub use message_link::{
143 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
156 ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
157 chat_message_link, team_link,
144};
158};
145pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
159pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
146pub use notes_chat::{is_notes_chat, notes_chat_title};
160pub use notes_chat::{is_notes_chat, notes_chat_title};
crates/core/src/notes_chat.rs +2 −0
@@ -116,6 +116,8 @@ mod tests {
116 116 last_message_from: Some(format!("8:orgid:{from}")),
117 117 ..ReadHorizon::default()
118 118 },
119 notification_settings: None,
120 history_cleared_ms: None,
119 121 }
120 122 }
121 123
@@ -116,6 +116,8 @@ 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,
120 history_cleared_ms: None,
119 }
121 }
120 }
122 }
121
123
crates/core/src/remote.rs +59 −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,
@@ -139,6 +140,12 @@ pub trait Remote {
139 140 share: HistoryShare,
140 141 ) -> Result<()>;
141 142 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
143 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
144 Err(Error::Unsupported("removing chat history"))
145 }
146 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
147 Err(Error::Unsupported("renaming a chat"))
148 }
142 149 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
143 150 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
144 151 async fn set_channel_notifications(
@@ -479,6 +486,24 @@ pub trait Remote {
479 486 Err(Error::Unsupported("sound settings"))
480 487 }
481 488
489 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
490 Err(Error::Unsupported("chat settings"))
491 }
492
493 async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
494 Err(Error::Unsupported("chat settings"))
495 }
496
497 async fn set_chat_notifications(
498 &self,
499 _chat_id: &str,
500 _current_settings: Option<&str>,
501 _mode: ChatNotificationMode,
502 _desktop: DesktopNotifications,
503 ) -> Result<ChatNotificationWrite> {
504 Err(Error::Unsupported("chat notifications"))
505 }
506
482 507 async fn save_sound_settings(
483 508 &self,
484 509 _user_mri: &str,
@@ -743,6 +768,18 @@ impl Remote for Graph {
743 768 .await?)
744 769 }
745 770
771 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
772 Ok(Conversations::new(self.session())
773 .clear_history(chat_id, cleared_until_ms)
774 .await?)
775 }
776
777 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
778 Ok(ThreadMembers::new(self.session())
779 .set_topic(chat_id, topic)
780 .await?)
781 }
782
746 783 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
747 784 Ok(Conversations::new(self.session())
748 785 .set_alerts(chat_id, !muted)
@@ -1249,6 +1286,26 @@ impl Remote for Graph {
1249 1286 Ok(SoundSettingsClient::new(self.session()).read().await?)
1250 1287 }
1251 1288
1289 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1290 Ok(ChatSettingsClient::new(self.session()).read().await?)
1291 }
1292
1293 async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1294 Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1295 }
1296
1297 async fn set_chat_notifications(
1298 &self,
1299 chat_id: &str,
1300 current_settings: Option<&str>,
1301 mode: ChatNotificationMode,
1302 desktop: DesktopNotifications,
1303 ) -> Result<ChatNotificationWrite> {
1304 Ok(Conversations::new(self.session())
1305 .set_chat_notifications(chat_id, current_settings, mode, desktop)
1306 .await?)
1307 }
1308
1252 1309 async fn save_sound_settings(
1253 1310 &self,
1254 1311 user_mri: &str,
@@ -3,8 +3,9 @@ use chatsvc::substrate_search::{
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
3 QueryRequest, QueryResults, SearchIdentity, SearchSession, SubstrateSearch, Suggestions,
4};
4};
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,
@@ -139,6 +140,12 @@ pub trait Remote {
139 share: HistoryShare,
140 share: HistoryShare,
140 ) -> Result<()>;
141 ) -> Result<()>;
141 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
142 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
143 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
144 Err(Error::Unsupported("removing chat history"))
145 }
146 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
147 Err(Error::Unsupported("renaming a chat"))
148 }
142 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
149 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
143 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
150 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
144 async fn set_channel_notifications(
151 async fn set_channel_notifications(
@@ -479,6 +486,24 @@ pub trait Remote {
479 Err(Error::Unsupported("sound settings"))
486 Err(Error::Unsupported("sound settings"))
480 }
487 }
481
488
489 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
490 Err(Error::Unsupported("chat settings"))
491 }
492
493 async fn save_chat_setting(&self, _change: ChatSettingChange) -> Result<ChatSettingsDocument> {
494 Err(Error::Unsupported("chat settings"))
495 }
496
497 async fn set_chat_notifications(
498 &self,
499 _chat_id: &str,
500 _current_settings: Option<&str>,
501 _mode: ChatNotificationMode,
502 _desktop: DesktopNotifications,
503 ) -> Result<ChatNotificationWrite> {
504 Err(Error::Unsupported("chat notifications"))
505 }
506
482 async fn save_sound_settings(
507 async fn save_sound_settings(
483 &self,
508 &self,
484 _user_mri: &str,
509 _user_mri: &str,
@@ -743,6 +768,18 @@ impl Remote for Graph {
743 .await?)
768 .await?)
744 }
769 }
745
770
771 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
772 Ok(Conversations::new(self.session())
773 .clear_history(chat_id, cleared_until_ms)
774 .await?)
775 }
776
777 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
778 Ok(ThreadMembers::new(self.session())
779 .set_topic(chat_id, topic)
780 .await?)
781 }
782
746 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
783 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
747 Ok(Conversations::new(self.session())
784 Ok(Conversations::new(self.session())
748 .set_alerts(chat_id, !muted)
785 .set_alerts(chat_id, !muted)
@@ -1249,6 +1286,26 @@ impl Remote for Graph {
1249 Ok(SoundSettingsClient::new(self.session()).read().await?)
1286 Ok(SoundSettingsClient::new(self.session()).read().await?)
1250 }
1287 }
1251
1288
1289 async fn chat_settings(&self) -> Result<ChatSettingsDocument> {
1290 Ok(ChatSettingsClient::new(self.session()).read().await?)
1291 }
1292
1293 async fn save_chat_setting(&self, change: ChatSettingChange) -> Result<ChatSettingsDocument> {
1294 Ok(ChatSettingsClient::new(self.session()).write(change).await?)
1295 }
1296
1297 async fn set_chat_notifications(
1298 &self,
1299 chat_id: &str,
1300 current_settings: Option<&str>,
1301 mode: ChatNotificationMode,
1302 desktop: DesktopNotifications,
1303 ) -> Result<ChatNotificationWrite> {
1304 Ok(Conversations::new(self.session())
1305 .set_chat_notifications(chat_id, current_settings, mode, desktop)
1306 .await?)
1307 }
1308
1252 async fn save_sound_settings(
1309 async fn save_sound_settings(
1253 &self,
1310 &self,
1254 user_mri: &str,
1311 user_mri: &str,
crates/core/src/roster_event.rs +41 −0
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6 6 const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7 7 const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8 8 const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9 const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9 10 const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10 11 const DAY_SECONDS: i64 = 86_400;
11 12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14 15 Added,
15 16 Removed,
16 17 Left,
18 Renamed,
17 19 }
18 20
19 21 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33 35 pub member_names: Vec<Option<String>>,
34 36 #[serde(default)]
35 37 pub history: SharedHistory,
38 #[serde(default)]
39 pub topic: Option<String>,
36 40 }
37 41
38 42 #[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67 71 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 72 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 73 MEMBERS_DELETED_TYPE => RosterChange::Removed,
74 CHAT_RENAMED_TYPE => RosterChange::Renamed,
70 75 _ => return None,
71 76 };
72 77 let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86 91 member_ids,
87 92 member_names,
88 93 history,
94 topic: (change == RosterChange::Renamed)
95 .then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96 .flatten()
97 .map(str::trim)
98 .filter(|topic| !topic.is_empty())
99 .map(str::to_owned),
89 100 })
90 101 }
91 102
@@ -114,6 +125,10 @@ impl RosterEvent {
114 125 let targets = join_targets(&targets);
115 126 match self.change {
116 127 RosterChange::Left => format!("{initiator} left the chat."),
128 RosterChange::Renamed => match &self.topic {
129 Some(topic) => format!("{initiator} changed the group name to {topic}."),
130 None => format!("{initiator} removed the group name for this conversation."),
131 },
117 132 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 133 RosterChange::Added => match self.history {
119 134 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210 225 name.or(user_id).unwrap_or("Unknown").to_owned()
211 226 }
212 227
228 #[test]
229 fn a_rename_reads_like_teams() {
230 let renamed = |name: Value| {
231 RosterEvent::from_graph(
232 &json!({
233 "@odata.type": CHAT_RENAMED_TYPE,
234 "chatDisplayName": name,
235 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236 }),
237 created(),
238 )
239 .unwrap()
240 };
241 let event = renamed(json!("Release crew"));
242 assert_eq!(event.change, RosterChange::Renamed);
243 assert_eq!(
244 event.text(plain_names),
245 "Daniel changed the group name to Release crew."
246 );
247 assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248 assert_eq!(
249 renamed(json!(null)).text(plain_names),
250 "Daniel removed the group name for this conversation."
251 );
252 }
253
213 254 #[test]
214 255 fn added_without_history_reads_like_teams() {
215 256 let event = added(
@@ -6,6 +6,7 @@ use store::{MemberRecord, MessageRecord};
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
6const MEMBERS_ADDED_TYPE: &str = "#microsoft.graph.membersAddedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
7const MEMBERS_DELETED_TYPE: &str = "#microsoft.graph.membersDeletedEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
8const MEMBERS_LEFT_TYPE: &str = "#microsoft.graph.membersLeftEventMessageDetail";
9const CHAT_RENAMED_TYPE: &str = "#microsoft.graph.chatRenamedEventMessageDetail";
9const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10const UNRESOLVED_NAME_PREFIX: &str = "orgid:";
10const DAY_SECONDS: i64 = 86_400;
11const DAY_SECONDS: i64 = 86_400;
11
12
@@ -14,6 +15,7 @@ pub enum RosterChange {
14 Added,
15 Added,
15 Removed,
16 Removed,
16 Left,
17 Left,
18 Renamed,
17}
19}
18
20
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
@@ -33,6 +35,8 @@ pub struct RosterEvent {
33 pub member_names: Vec<Option<String>>,
35 pub member_names: Vec<Option<String>>,
34 #[serde(default)]
36 #[serde(default)]
35 pub history: SharedHistory,
37 pub history: SharedHistory,
38 #[serde(default)]
39 pub topic: Option<String>,
36}
40}
37
41
38#[derive(Serialize, Deserialize)]
42#[derive(Serialize, Deserialize)]
@@ -67,6 +71,7 @@ impl RosterEvent {
67 MEMBERS_LEFT_TYPE => RosterChange::Left,
71 MEMBERS_LEFT_TYPE => RosterChange::Left,
68 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
72 MEMBERS_DELETED_TYPE if only_initiator => RosterChange::Left,
69 MEMBERS_DELETED_TYPE => RosterChange::Removed,
73 MEMBERS_DELETED_TYPE => RosterChange::Removed,
74 CHAT_RENAMED_TYPE => RosterChange::Renamed,
70 _ => return None,
75 _ => return None,
71 };
76 };
72 let history = match change {
77 let history = match change {
@@ -86,6 +91,12 @@ impl RosterEvent {
86 member_ids,
91 member_ids,
87 member_names,
92 member_names,
88 history,
93 history,
94 topic: (change == RosterChange::Renamed)
95 .then(|| detail.get("chatDisplayName").and_then(Value::as_str))
96 .flatten()
97 .map(str::trim)
98 .filter(|topic| !topic.is_empty())
99 .map(str::to_owned),
89 })
100 })
90 }
101 }
91
102
@@ -114,6 +125,10 @@ impl RosterEvent {
114 let targets = join_targets(&targets);
125 let targets = join_targets(&targets);
115 match self.change {
126 match self.change {
116 RosterChange::Left => format!("{initiator} left the chat."),
127 RosterChange::Left => format!("{initiator} left the chat."),
128 RosterChange::Renamed => match &self.topic {
129 Some(topic) => format!("{initiator} changed the group name to {topic}."),
130 None => format!("{initiator} removed the group name for this conversation."),
131 },
117 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
132 RosterChange::Removed => format!("{initiator} removed {targets} from the chat."),
118 RosterChange::Added => match self.history {
133 RosterChange::Added => match self.history {
119 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
134 SharedHistory::None => format!("{initiator} added {targets} to the chat."),
@@ -210,6 +225,32 @@ mod tests {
210 name.or(user_id).unwrap_or("Unknown").to_owned()
225 name.or(user_id).unwrap_or("Unknown").to_owned()
211 }
226 }
212
227
228 #[test]
229 fn a_rename_reads_like_teams() {
230 let renamed = |name: Value| {
231 RosterEvent::from_graph(
232 &json!({
233 "@odata.type": CHAT_RENAMED_TYPE,
234 "chatDisplayName": name,
235 "initiator": {"user": {"id": "me", "displayName": "Daniel"}},
236 }),
237 created(),
238 )
239 .unwrap()
240 };
241 let event = renamed(json!("Release crew"));
242 assert_eq!(event.change, RosterChange::Renamed);
243 assert_eq!(
244 event.text(plain_names),
245 "Daniel changed the group name to Release crew."
246 );
247 assert_eq!(RosterEvent::from_json(&event.to_json()).unwrap(), event);
248 assert_eq!(
249 renamed(json!(null)).text(plain_names),
250 "Daniel removed the group name for this conversation."
251 );
252 }
253
213 #[test]
254 #[test]
214 fn added_without_history_reads_like_teams() {
255 fn added_without_history_reads_like_teams() {
215 let event = added(
256 let event = added(
crates/core/tests/engine.rs +137 −0
@@ -584,6 +584,8 @@ impl Remote for Handle {
584 584 muted,
585 585 hidden: None,
586 586 read: chatsvc::ReadHorizon::default(),
587 notification_settings: None,
588 history_cleared_ms: None,
587 589 })
588 590 .collect();
589 591 states.extend(
@@ -594,6 +596,8 @@ impl Remote for Handle {
594 596 muted: false,
595 597 hidden: Some(hidden),
596 598 read: chatsvc::ReadHorizon::default(),
599 notification_settings: None,
600 history_cleared_ms: None,
597 601 }),
598 602 );
599 603 let read = self.read_states.lock().unwrap().clone();
@@ -604,6 +608,8 @@ impl Remote for Handle {
604 608 muted: false,
605 609 hidden: None,
606 610 read,
611 notification_settings: None,
612 history_cleared_ms: None,
607 613 }),
608 614 );
609 615 Ok(states)
@@ -3209,6 +3215,137 @@ impl FolderSource for FakeFolders {
3209 3215 Ok(state.clone())
3210 3216 })
3211 3217 }
3218
3219 fn set_channel_pinned<'a>(
3220 &'a self,
3221 channel_id: &'a str,
3222 pinned: bool,
3223 ) -> BoxFuture<'a, Result<Vec<String>>> {
3224 Box::pin(async move {
3225 self.calls
3226 .lock()
3227 .unwrap()
3228 .push(format!("pin channel {channel_id} {pinned}"));
3229 let mut channel_ids = self.channels.clone();
3230 channel_ids.retain(|id| id != channel_id);
3231 if pinned {
3232 channel_ids.push(channel_id.to_owned());
3233 }
3234 Ok(channel_ids)
3235 })
3236 }
3237
3238 fn set_channel_shown<'a>(
3239 &'a self,
3240 target: chatsvc::ChannelTarget<'a>,
3241 own_user_id: &'a str,
3242 shown: bool,
3243 _now_ms: i64,
3244 ) -> BoxFuture<'a, Result<()>> {
3245 Box::pin(async move {
3246 self.calls.lock().unwrap().push(format!(
3247 "show channel {} general={} {:?} {own_user_id} {shown}",
3248 target.channel_id, target.general, target.kind
3249 ));
3250 Ok(())
3251 })
3252 }
3253
3254 fn set_team_shown<'a>(
3255 &'a self,
3256 team_thread_id: &'a str,
3257 shown: bool,
3258 ) -> BoxFuture<'a, Result<()>> {
3259 Box::pin(async move {
3260 self.calls
3261 .lock()
3262 .unwrap()
3263 .push(format!("show team {team_thread_id} {shown}"));
3264 Ok(())
3265 })
3266 }
3267 }
3268
3269 fn store_alpha_team(engine: &SyncEngine<Handle>) {
3270 engine
3271 .store()
3272 .upsert_teams(&[TeamRecord {
3273 id: "alpha".into(),
3274 name: "Alpha".into(),
3275 }])
3276 .unwrap();
3277 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3278 id: id.into(),
3279 team_id: "alpha".into(),
3280 name: name.into(),
3281 membership_type: membership_type.map(str::to_owned),
3282 last_message_at: None,
3283 unread: false,
3284 };
3285 engine
3286 .store()
3287 .upsert_channels(&[
3288 channel("19:general@thread.tacv2", "General", Some("standard")),
3289 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3290 ])
3291 .unwrap();
3292 }
3293
3294 #[tokio::test]
3295 async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3296 let fake = Arc::new(Fake::default());
3297 let source = FakeFolders::new();
3298 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3299 store_alpha_team(&engine);
3300 let mut events = engine.subscribe();
3301
3302 engine.set_channel_pinned("ch3", true).await.unwrap();
3303 assert_eq!(
3304 engine.pinned_channels().unwrap(),
3305 ids(&["ch1", "ch2", "ch3"])
3306 );
3307 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3308 engine.set_channel_pinned("ch1", false).await.unwrap();
3309 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3310
3311 engine
3312 .set_channel_shown("19:secret@thread.tacv2", false)
3313 .await
3314 .unwrap();
3315 engine
3316 .set_channel_shown("19:general@thread.tacv2", false)
3317 .await
3318 .unwrap();
3319 engine.set_team_shown("alpha", false).await.unwrap();
3320 let team = engine.store().sidebar().unwrap().teams.remove(0);
3321 assert!(team.hidden);
3322 assert_eq!(team.hidden_channel_ids.len(), 2);
3323 let calls = source.calls.lock().unwrap().clone();
3324 assert_eq!(
3325 calls[2..],
3326 [
3327 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3328 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3329 "show team 19:general@thread.tacv2 false".to_owned(),
3330 ]
3331 );
3332 }
3333
3334 #[tokio::test]
3335 async fn channel_and_team_links_use_the_cached_tenant() {
3336 let fake = Arc::new(Fake::default());
3337 let engine = engine_with(&fake, SyncConfig::default());
3338 store_alpha_team(&engine);
3339 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3340
3341 assert_eq!(
3342 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3343 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3344 );
3345 assert_eq!(
3346 engine.team_link("alpha").await.unwrap(),
3347 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3348 );
3212 3349 }
3213 3350
3214 3351 #[tokio::test]
@@ -584,6 +584,8 @@ 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,
588 history_cleared_ms: None,
587 })
589 })
588 .collect();
590 .collect();
589 states.extend(
591 states.extend(
@@ -594,6 +596,8 @@ impl Remote for Handle {
594 muted: false,
596 muted: false,
595 hidden: Some(hidden),
597 hidden: Some(hidden),
596 read: chatsvc::ReadHorizon::default(),
598 read: chatsvc::ReadHorizon::default(),
599 notification_settings: None,
600 history_cleared_ms: None,
597 }),
601 }),
598 );
602 );
599 let read = self.read_states.lock().unwrap().clone();
603 let read = self.read_states.lock().unwrap().clone();
@@ -604,6 +608,8 @@ impl Remote for Handle {
604 muted: false,
608 muted: false,
605 hidden: None,
609 hidden: None,
606 read,
610 read,
611 notification_settings: None,
612 history_cleared_ms: None,
607 }),
613 }),
608 );
614 );
609 Ok(states)
615 Ok(states)
@@ -3209,6 +3215,137 @@ impl FolderSource for FakeFolders {
3209 Ok(state.clone())
3215 Ok(state.clone())
3210 })
3216 })
3211 }
3217 }
3218
3219 fn set_channel_pinned<'a>(
3220 &'a self,
3221 channel_id: &'a str,
3222 pinned: bool,
3223 ) -> BoxFuture<'a, Result<Vec<String>>> {
3224 Box::pin(async move {
3225 self.calls
3226 .lock()
3227 .unwrap()
3228 .push(format!("pin channel {channel_id} {pinned}"));
3229 let mut channel_ids = self.channels.clone();
3230 channel_ids.retain(|id| id != channel_id);
3231 if pinned {
3232 channel_ids.push(channel_id.to_owned());
3233 }
3234 Ok(channel_ids)
3235 })
3236 }
3237
3238 fn set_channel_shown<'a>(
3239 &'a self,
3240 target: chatsvc::ChannelTarget<'a>,
3241 own_user_id: &'a str,
3242 shown: bool,
3243 _now_ms: i64,
3244 ) -> BoxFuture<'a, Result<()>> {
3245 Box::pin(async move {
3246 self.calls.lock().unwrap().push(format!(
3247 "show channel {} general={} {:?} {own_user_id} {shown}",
3248 target.channel_id, target.general, target.kind
3249 ));
3250 Ok(())
3251 })
3252 }
3253
3254 fn set_team_shown<'a>(
3255 &'a self,
3256 team_thread_id: &'a str,
3257 shown: bool,
3258 ) -> BoxFuture<'a, Result<()>> {
3259 Box::pin(async move {
3260 self.calls
3261 .lock()
3262 .unwrap()
3263 .push(format!("show team {team_thread_id} {shown}"));
3264 Ok(())
3265 })
3266 }
3267}
3268
3269fn store_alpha_team(engine: &SyncEngine<Handle>) {
3270 engine
3271 .store()
3272 .upsert_teams(&[TeamRecord {
3273 id: "alpha".into(),
3274 name: "Alpha".into(),
3275 }])
3276 .unwrap();
3277 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3278 id: id.into(),
3279 team_id: "alpha".into(),
3280 name: name.into(),
3281 membership_type: membership_type.map(str::to_owned),
3282 last_message_at: None,
3283 unread: false,
3284 };
3285 engine
3286 .store()
3287 .upsert_channels(&[
3288 channel("19:general@thread.tacv2", "General", Some("standard")),
3289 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3290 ])
3291 .unwrap();
3292}
3293
3294#[tokio::test]
3295async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3296 let fake = Arc::new(Fake::default());
3297 let source = FakeFolders::new();
3298 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3299 store_alpha_team(&engine);
3300 let mut events = engine.subscribe();
3301
3302 engine.set_channel_pinned("ch3", true).await.unwrap();
3303 assert_eq!(
3304 engine.pinned_channels().unwrap(),
3305 ids(&["ch1", "ch2", "ch3"])
3306 );
3307 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3308 engine.set_channel_pinned("ch1", false).await.unwrap();
3309 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3310
3311 engine
3312 .set_channel_shown("19:secret@thread.tacv2", false)
3313 .await
3314 .unwrap();
3315 engine
3316 .set_channel_shown("19:general@thread.tacv2", false)
3317 .await
3318 .unwrap();
3319 engine.set_team_shown("alpha", false).await.unwrap();
3320 let team = engine.store().sidebar().unwrap().teams.remove(0);
3321 assert!(team.hidden);
3322 assert_eq!(team.hidden_channel_ids.len(), 2);
3323 let calls = source.calls.lock().unwrap().clone();
3324 assert_eq!(
3325 calls[2..],
3326 [
3327 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3328 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3329 "show team 19:general@thread.tacv2 false".to_owned(),
3330 ]
3331 );
3332}
3333
3334#[tokio::test]
3335async fn channel_and_team_links_use_the_cached_tenant() {
3336 let fake = Arc::new(Fake::default());
3337 let engine = engine_with(&fake, SyncConfig::default());
3338 store_alpha_team(&engine);
3339 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3340
3341 assert_eq!(
3342 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3343 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3344 );
3345 assert_eq!(
3346 engine.team_link("alpha").await.unwrap(),
3347 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3348 );
3212}
3349}
3213
3350
3214#[tokio::test]
3351#[tokio::test]
crates/store/src/folders.rs +15 −0
@@ -89,4 +89,19 @@ impl Store {
89 89 let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
90 90 Ok(rows.collect::<rusqlite::Result<_>>()?)
91 91 }
92
93 pub fn replace_pinned_channels(&self, channel_ids: &[String]) -> Result<()> {
94 let mut connection = self.lock()?;
95 let transaction = connection.transaction()?;
96 transaction.execute("DELETE FROM pinned_channels", [])?;
97 {
98 let mut insert_channel = transaction.prepare_cached(
99 "INSERT INTO pinned_channels (position, channel_id) VALUES (?1, ?2)",
100 )?;
101 for (position, channel_id) in channel_ids.iter().enumerate() {
102 insert_channel.execute(params![position as i64, channel_id])?;
103 }
104 }
105 Ok(transaction.commit()?)
106 }
92 107 }
@@ -89,4 +89,19 @@ impl Store {
89 let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
89 let rows = statement.query_map([], |row| row.get::<_, String>(0))?;
90 Ok(rows.collect::<rusqlite::Result<_>>()?)
90 Ok(rows.collect::<rusqlite::Result<_>>()?)
91 }
91 }
92
93 pub fn replace_pinned_channels(&self, channel_ids: &[String]) -> Result<()> {
94 let mut connection = self.lock()?;
95 let transaction = connection.transaction()?;
96 transaction.execute("DELETE FROM pinned_channels", [])?;
97 {
98 let mut insert_channel = transaction.prepare_cached(
99 "INSERT INTO pinned_channels (position, channel_id) VALUES (?1, ?2)",
100 )?;
101 for (position, channel_id) in channel_ids.iter().enumerate() {
102 insert_channel.execute(params![position as i64, channel_id])?;
103 }
104 }
105 Ok(transaction.commit()?)
106 }
92}
107}
crates/store/src/sidebar.rs +20 −0
@@ -234,6 +234,26 @@ impl Store {
234 234 )?;
235 235 Ok(())
236 236 }
237
238 pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {
239 self.lock()?.execute(
240 "INSERT INTO channel_layout (channel_id, general, hidden)
241 SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1
242 ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",
243 params![channel_id, GENERAL_FALLBACK_NAME, hidden],
244 )?;
245 Ok(())
246 }
247
248 pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {
249 self.lock()?.execute(
250 "INSERT INTO team_layout (team_id, position, hidden)
251 SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true
252 ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",
253 params![team_id, hidden],
254 )?;
255 Ok(())
256 }
237 257 }
238 258
239 259 impl Store {
@@ -234,6 +234,26 @@ impl Store {
234 )?;
234 )?;
235 Ok(())
235 Ok(())
236 }
236 }
237
238 pub fn set_channel_hidden(&self, channel_id: &str, hidden: bool) -> Result<()> {
239 self.lock()?.execute(
240 "INSERT INTO channel_layout (channel_id, general, hidden)
241 SELECT id, name = ?2, ?3 FROM channels WHERE id = ?1
242 ON CONFLICT (channel_id) DO UPDATE SET hidden = excluded.hidden",
243 params![channel_id, GENERAL_FALLBACK_NAME, hidden],
244 )?;
245 Ok(())
246 }
247
248 pub fn set_team_hidden(&self, team_id: &str, hidden: bool) -> Result<()> {
249 self.lock()?.execute(
250 "INSERT INTO team_layout (team_id, position, hidden)
251 SELECT ?1, COALESCE(MAX(position) + 1, 0), ?2 FROM team_layout WHERE true
252 ON CONFLICT (team_id) DO UPDATE SET hidden = excluded.hidden",
253 params![team_id, hidden],
254 )?;
255 Ok(())
256 }
237}
257}
238
258
239impl Store {
259impl Store {
crates/store/tests/store.rs +41 −0
@@ -1675,3 +1675,44 @@ fn setting_read_horizons_replaces_the_conversation_only() {
1675 1675 assert_eq!(store.read_horizons("c").unwrap(), second);
1676 1676 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1677 1677 }
1678
1679 #[test]
1680 fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1681 let store = Store::open_in_memory().unwrap();
1682 store
1683 .upsert_teams(&[TeamRecord {
1684 id: "t1".to_owned(),
1685 name: "Alpha".to_owned(),
1686 }])
1687 .unwrap();
1688 let channel = |id: &str, name: &str| ChannelRecord {
1689 id: id.to_owned(),
1690 team_id: "t1".to_owned(),
1691 name: name.to_owned(),
1692 membership_type: None,
1693 last_message_at: None,
1694 unread: false,
1695 };
1696 store
1697 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1698 .unwrap();
1699 let team = || store.sidebar().unwrap().teams.remove(0);
1700
1701 store.set_channel_hidden("c2", true).unwrap();
1702 store.set_team_hidden("t1", true).unwrap();
1703 let hidden = team();
1704 assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1705 assert!(hidden.hidden);
1706 assert_eq!(hidden.channels[0].name, "General");
1707
1708 store.set_channel_hidden("c2", false).unwrap();
1709 store.set_team_hidden("t1", false).unwrap();
1710 let shown = team();
1711 assert!(shown.hidden_channel_ids.is_empty());
1712 assert!(!shown.hidden);
1713
1714 store
1715 .replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1716 .unwrap();
1717 assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1718 }
@@ -1675,3 +1675,44 @@ fn setting_read_horizons_replaces_the_conversation_only() {
1675 assert_eq!(store.read_horizons("c").unwrap(), second);
1675 assert_eq!(store.read_horizons("c").unwrap(), second);
1676 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1676 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1677}
1677}
1678
1679#[test]
1680fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1681 let store = Store::open_in_memory().unwrap();
1682 store
1683 .upsert_teams(&[TeamRecord {
1684 id: "t1".to_owned(),
1685 name: "Alpha".to_owned(),
1686 }])
1687 .unwrap();
1688 let channel = |id: &str, name: &str| ChannelRecord {
1689 id: id.to_owned(),
1690 team_id: "t1".to_owned(),
1691 name: name.to_owned(),
1692 membership_type: None,
1693 last_message_at: None,
1694 unread: false,
1695 };
1696 store
1697 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1698 .unwrap();
1699 let team = || store.sidebar().unwrap().teams.remove(0);
1700
1701 store.set_channel_hidden("c2", true).unwrap();
1702 store.set_team_hidden("t1", true).unwrap();
1703 let hidden = team();
1704 assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1705 assert!(hidden.hidden);
1706 assert_eq!(hidden.channels[0].name, "General");
1707
1708 store.set_channel_hidden("c2", false).unwrap();
1709 store.set_team_hidden("t1", false).unwrap();
1710 let shown = team();
1711 assert!(shown.hidden_channel_ids.is_empty());
1712 assert!(!shown.hidden);
1713
1714 store
1715 .replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1716 .unwrap();
1717 assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1718}
scripts/build-windows.sh +3 −0
@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse
37 37 text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
38 38 open(path, 'w').write(text)
39 39 PY
40 for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do
41 patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"
42 done
40 43 # A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
41 44 if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
42 45 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
@@ -37,6 +37,9 @@ text = re.sub(r'fn main\(\) \{.*?\n\}\n', 'fn main() {\n #[cfg(not(debug_asse
37text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
37text = re.sub(r'(pub fn find_latest_windows_sdk_binary\(.*?\) -> Result<[^{]*\{).*?(\n /// You can set)', r'\1\n let _ = binary;\n Ok(None)\n }\n\2', text, count=1, flags=re.S)
38open(path, 'w').write(text)
38open(path, 'w').write(text)
39PY
39PY
40for patchFile in "$repoRoot"/scripts/gpui-windows-patches/*.patch; do
41 patch --directory="$stagingDir" --strip=1 --forward --batch --no-backup-if-mismatch --quiet < "$patchFile"
42done
40# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
43# A fresh copy gets new mtimes, and Cargo then rebuilds gpui and everything above it.
41if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
44if ! diff -rq "$stagingDir" "$patchedDir" >/dev/null 2>&1; then
42 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
45 rm -rf "$patchedDir"; mkdir -p "$(dirname "$patchedDir")"; cp -rp "$stagingDir" "$patchedDir"
scripts/gpui-windows-patches/touch-input.patch added +177 −0
@@ -0,0 +1,177 @@
1 diff -ruN a/src/events.rs b/src/events.rs
2 --- a/src/events.rs
3 +++ b/src/events.rs
4 @@ -10,7 +10,7 @@
5 UI::{
6 Controls::*,
7 HiDpi::*,
8 - Input::{Ime::*, KeyboardAndMouse::*},
9 + Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},
10 WindowsAndMessaging::*,
11 },
12 },
13 @@ -31,6 +31,7 @@
14 pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;
15
16 const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
17 +const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;
18
19 /// Coordinates window draws on the UI thread. Owned by the platform and
20 /// shared with every window (like `WindowsPlatformState::cursor_visible`),
21 @@ -149,6 +150,10 @@
22 }
23 WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
24 WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
25 + WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),
26 + WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),
27 + WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),
28 + WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),
29 WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
30 WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
31 WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),
32 @@ -647,6 +652,62 @@
33 if handled { Some(0) } else { Some(1) }
34 }
35
36 + fn handle_touch_pointer_msg(
37 + &self,
38 + handle: HWND,
39 + wparam: WPARAM,
40 + lparam: LPARAM,
41 + phase: TouchPhase,
42 + ) -> Option<isize> {
43 + let pointer_id = wparam.loword() as u32;
44 + let mut pointer_type = POINTER_INPUT_TYPE::default();
45 + unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;
46 + if pointer_type != PT_TOUCH {
47 + return None;
48 + }
49 + let phase = if phase == TouchPhase::Ended
50 + && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 0
51 + {
52 + TouchPhase::Cancelled
53 + } else {
54 + phase
55 + };
56 + let mut cursor_point = POINT {
57 + x: lparam.signed_loword().into(),
58 + y: lparam.signed_hiword().into(),
59 + };
60 + unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
61 + let position = logical_point(
62 + cursor_point.x as f32,
63 + cursor_point.y as f32,
64 + self.state.scale_factor.get(),
65 + );
66 + if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {
67 + self.dispatch_touch(touch_id, phase, position);
68 + }
69 + Some(0)
70 + }
71 +
72 + fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {
73 + let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;
74 + self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);
75 + Some(0)
76 + }
77 +
78 + fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {
79 + let Some(mut func) = self.state.callbacks.input.take() else {
80 + return;
81 + };
82 + func(PlatformInput::Touch(TouchEvent {
83 + id: touch_id,
84 + phase,
85 + position,
86 + predicted_position: None,
87 + force: None,
88 + }));
89 + self.state.callbacks.input.set(Some(func));
90 + }
91 +
92 fn retrieve_caret_position(&self) -> Option<POINT> {
93 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
94 let caret_range = input_handler.selected_text_range(false)?;
95 diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs
96 --- a/src/gpui_windows.rs
97 +++ b/src/gpui_windows.rs
98 @@ -15,6 +15,7 @@
99 mod platform;
100 mod system_notifications;
101 mod system_settings;
102 +mod touch;
103 mod util;
104 mod vsync;
105 mod window;
106 @@ -33,6 +34,7 @@
107 pub(crate) use platform::*;
108 pub(crate) use system_notifications::*;
109 pub(crate) use system_settings::*;
110 +pub(crate) use touch::*;
111 pub(crate) use util::*;
112 pub(crate) use vsync::*;
113 pub(crate) use window::*;
114 diff -ruN a/src/touch.rs b/src/touch.rs
115 --- a/src/touch.rs
116 +++ b/src/touch.rs
117 @@ -0,0 +1,41 @@
118 +use std::cell::{Cell, RefCell};
119 +use std::collections::HashMap;
120 +
121 +use gpui::{Pixels, Point, TouchId, TouchPhase};
122 +
123 +#[derive(Default)]
124 +pub(crate) struct TouchPointers {
125 + next_touch_id: Cell<u64>,
126 + active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,
127 +}
128 +
129 +impl TouchPointers {
130 + pub(crate) fn track(
131 + &self,
132 + pointer_id: u32,
133 + phase: TouchPhase,
134 + position: Point<Pixels>,
135 + ) -> Option<TouchId> {
136 + let mut active = self.active.borrow_mut();
137 + match phase {
138 + TouchPhase::Started => {
139 + let touch_id = TouchId(self.next_touch_id.get());
140 + self.next_touch_id.set(self.next_touch_id.get() + 1);
141 + active.insert(pointer_id, (touch_id, position));
142 + Some(touch_id)
143 + }
144 + TouchPhase::Moved => {
145 + let entry = active.get_mut(&pointer_id)?;
146 + entry.1 = position;
147 + Some(entry.0)
148 + }
149 + TouchPhase::Ended | TouchPhase::Cancelled => {
150 + active.remove(&pointer_id).map(|(touch_id, _)| touch_id)
151 + }
152 + }
153 + }
154 +
155 + pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {
156 + self.active.borrow_mut().remove(&pointer_id)
157 + }
158 +}
159 diff -ruN a/src/window.rs b/src/window.rs
160 --- a/src/window.rs
161 +++ b/src/window.rs
162 @@ -63,6 +63,7 @@
163 pub hovered: Cell<bool>,
164 pub last_visibility: Cell<Option<WindowVisibility>>,
165 pub direct_manipulation: DirectManipulationHandler,
166 + pub touch_pointers: TouchPointers,
167
168 pub renderer: RefCell<DirectXRenderer>,
169 /// Set when the next `draw_window` call must be treated as a forced
170 @@ -190,6 +191,7 @@
171 invalidate_devices,
172 draw_coordinator,
173 direct_manipulation,
174 + touch_pointers: TouchPointers::default(),
175 a11y: RefCell::new(None),
176 })
177 }
@@ -0,0 +1,177 @@
1diff -ruN a/src/events.rs b/src/events.rs
2--- a/src/events.rs
3+++ b/src/events.rs
4@@ -10,7 +10,7 @@
5 UI::{
6 Controls::*,
7 HiDpi::*,
8- Input::{Ime::*, KeyboardAndMouse::*},
9+ Input::{Ime::*, KeyboardAndMouse::*, Pointer::GetPointerType},
10 WindowsAndMessaging::*,
11 },
12 },
13@@ -31,6 +31,7 @@
14 pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;
15
16 const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;
17+const POINTER_MESSAGE_FLAG_CANCELED: u16 = 0x8000;
18
19 /// Coordinates window draws on the UI thread. Owned by the platform and
20 /// shared with every window (like `WindowsPlatformState::cursor_visible`),
21@@ -149,6 +150,10 @@
22 }
23 WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),
24 WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),
25+ WM_POINTERDOWN => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Started),
26+ WM_POINTERUPDATE => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Moved),
27+ WM_POINTERUP => self.handle_touch_pointer_msg(handle, wparam, lparam, TouchPhase::Ended),
28+ WM_POINTERCAPTURECHANGED => self.handle_touch_pointer_capture_changed_msg(wparam),
29 WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),
30 WM_KEYUP => self.handle_keyup_msg(wparam, lparam),
31 WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),
32@@ -647,6 +652,62 @@
33 if handled { Some(0) } else { Some(1) }
34 }
35
36+ fn handle_touch_pointer_msg(
37+ &self,
38+ handle: HWND,
39+ wparam: WPARAM,
40+ lparam: LPARAM,
41+ phase: TouchPhase,
42+ ) -> Option<isize> {
43+ let pointer_id = wparam.loword() as u32;
44+ let mut pointer_type = POINTER_INPUT_TYPE::default();
45+ unsafe { GetPointerType(pointer_id, &mut pointer_type) }.ok()?;
46+ if pointer_type != PT_TOUCH {
47+ return None;
48+ }
49+ let phase = if phase == TouchPhase::Ended
50+ && wparam.hiword() & POINTER_MESSAGE_FLAG_CANCELED != 0
51+ {
52+ TouchPhase::Cancelled
53+ } else {
54+ phase
55+ };
56+ let mut cursor_point = POINT {
57+ x: lparam.signed_loword().into(),
58+ y: lparam.signed_hiword().into(),
59+ };
60+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };
61+ let position = logical_point(
62+ cursor_point.x as f32,
63+ cursor_point.y as f32,
64+ self.state.scale_factor.get(),
65+ );
66+ if let Some(touch_id) = self.state.touch_pointers.track(pointer_id, phase, position) {
67+ self.dispatch_touch(touch_id, phase, position);
68+ }
69+ Some(0)
70+ }
71+
72+ fn handle_touch_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {
73+ let (touch_id, position) = self.state.touch_pointers.cancel(wparam.loword() as u32)?;
74+ self.dispatch_touch(touch_id, TouchPhase::Cancelled, position);
75+ Some(0)
76+ }
77+
78+ fn dispatch_touch(&self, touch_id: TouchId, phase: TouchPhase, position: Point<Pixels>) {
79+ let Some(mut func) = self.state.callbacks.input.take() else {
80+ return;
81+ };
82+ func(PlatformInput::Touch(TouchEvent {
83+ id: touch_id,
84+ phase,
85+ position,
86+ predicted_position: None,
87+ force: None,
88+ }));
89+ self.state.callbacks.input.set(Some(func));
90+ }
91+
92 fn retrieve_caret_position(&self) -> Option<POINT> {
93 self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {
94 let caret_range = input_handler.selected_text_range(false)?;
95diff -ruN a/src/gpui_windows.rs b/src/gpui_windows.rs
96--- a/src/gpui_windows.rs
97+++ b/src/gpui_windows.rs
98@@ -15,6 +15,7 @@
99 mod platform;
100 mod system_notifications;
101 mod system_settings;
102+mod touch;
103 mod util;
104 mod vsync;
105 mod window;
106@@ -33,6 +34,7 @@
107 pub(crate) use platform::*;
108 pub(crate) use system_notifications::*;
109 pub(crate) use system_settings::*;
110+pub(crate) use touch::*;
111 pub(crate) use util::*;
112 pub(crate) use vsync::*;
113 pub(crate) use window::*;
114diff -ruN a/src/touch.rs b/src/touch.rs
115--- a/src/touch.rs
116+++ b/src/touch.rs
117@@ -0,0 +1,41 @@
118+use std::cell::{Cell, RefCell};
119+use std::collections::HashMap;
120+
121+use gpui::{Pixels, Point, TouchId, TouchPhase};
122+
123+#[derive(Default)]
124+pub(crate) struct TouchPointers {
125+ next_touch_id: Cell<u64>,
126+ active: RefCell<HashMap<u32, (TouchId, Point<Pixels>)>>,
127+}
128+
129+impl TouchPointers {
130+ pub(crate) fn track(
131+ &self,
132+ pointer_id: u32,
133+ phase: TouchPhase,
134+ position: Point<Pixels>,
135+ ) -> Option<TouchId> {
136+ let mut active = self.active.borrow_mut();
137+ match phase {
138+ TouchPhase::Started => {
139+ let touch_id = TouchId(self.next_touch_id.get());
140+ self.next_touch_id.set(self.next_touch_id.get() + 1);
141+ active.insert(pointer_id, (touch_id, position));
142+ Some(touch_id)
143+ }
144+ TouchPhase::Moved => {
145+ let entry = active.get_mut(&pointer_id)?;
146+ entry.1 = position;
147+ Some(entry.0)
148+ }
149+ TouchPhase::Ended | TouchPhase::Cancelled => {
150+ active.remove(&pointer_id).map(|(touch_id, _)| touch_id)
151+ }
152+ }
153+ }
154+
155+ pub(crate) fn cancel(&self, pointer_id: u32) -> Option<(TouchId, Point<Pixels>)> {
156+ self.active.borrow_mut().remove(&pointer_id)
157+ }
158+}
159diff -ruN a/src/window.rs b/src/window.rs
160--- a/src/window.rs
161+++ b/src/window.rs
162@@ -63,6 +63,7 @@
163 pub hovered: Cell<bool>,
164 pub last_visibility: Cell<Option<WindowVisibility>>,
165 pub direct_manipulation: DirectManipulationHandler,
166+ pub touch_pointers: TouchPointers,
167
168 pub renderer: RefCell<DirectXRenderer>,
169 /// Set when the next `draw_window` call must be treated as a forced
170@@ -190,6 +191,7 @@
171 invalidate_devices,
172 draw_coordinator,
173 direct_manipulation,
174+ touch_pointers: TouchPointers::default(),
175 a11y: RefCell::new(None),
176 })
177 }
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