BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/chat-settings

# Conflicts:
#	crates/chatsvc/src/conversations.rs
#	crates/chatsvc/src/lib.rs
#	crates/core/src/hidden_chats.rs
#	crates/core/src/lib.rs
#	crates/core/src/notes_chat.rs
#	crates/core/tests/engine.rs

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
267c8fa4ad7fd3adb5be51621066c4ef10f97ca2
47 files changed +5274 −87
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 +74 −5
@@ -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,19 +300,90 @@ 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;
@@ -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,19 +300,90 @@ 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;
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/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,
@@ -1414,6 +1424,7 @@ fn settings_card() -> serde_json::Value {
1414 1424 })
1415 1425 }
1416 1426
1427 pub const DEMO_TENANT_ID: &str = "demo-tenant";
1417 1428 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";
1418 1429
1419 1430 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,
@@ -1414,6 +1424,7 @@ fn settings_card() -> serde_json::Value {
1414 })
1424 })
1415}
1425}
1416
1426
1427pub const DEMO_TENANT_ID: &str = "demo-tenant";
1417const 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";
1428const 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";
1418
1429
1419fn meeting_link_messages() -> Vec<MessageRecord> {
1430fn 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 +4 −0
@@ -9,11 +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;
14 17 pub mod chat_settings_actions;
15 18 pub mod connection_banner;
16 19 pub mod data;
20 pub mod default_reactions;
17 21 pub mod demo;
18 22 pub mod demo_meetings;
19 23 pub mod demo_profiles;
@@ -9,11 +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;
14pub mod chat_settings_actions;
17pub mod chat_settings_actions;
15pub mod connection_banner;
18pub mod connection_banner;
16pub mod data;
19pub mod data;
20pub mod default_reactions;
17pub mod demo;
21pub mod demo;
18pub mod demo_meetings;
22pub mod demo_meetings;
19pub mod demo_profiles;
23pub mod demo_profiles;
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/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/src/layout_guard.rs +97 −3
@@ -180,8 +180,14 @@ mod frames {
180 180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 182 };
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
183 use crate::views::conversation::{
184 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
185 CHANNEL_DETAILS_TAG,
186 };
184 187 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
188 use crate::views::find_panel::{
189 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 };
185 191 use crate::views::message_row::BUBBLE_TAGS;
186 192 use crate::views::pin_banner::PIN_BANNER_TAG;
187 193 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -191,9 +197,13 @@ mod frames {
191 197 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
192 198 };
193 199 use crate::views::shortcuts::{
194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
200 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
201 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
195 202 };
196 203 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
204 use crate::views::sidebar::chat_filter_bar::{
205 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
206 };
197 207 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
198 208
199 209 const GUARDED: &[&str] = &[
@@ -216,6 +226,14 @@ mod frames {
216 226 "shell/islands/main/call-controls/leave",
217 227 ];
218 228 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
229 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
230 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
231 const FIND_TAGS: &[&str] = &[
232 FIND_PANEL_TAG,
233 FIND_DIVIDER_TAG,
234 FIND_INPUT_TAG,
235 FIND_RESULTS_TAG,
236 ];
219 237 const CALLS_TAGS: &[&str] = &[
220 238 "shell/islands/sidebar/calls-actions",
221 239 "shell/islands/sidebar/calls-actions/meet-now",
@@ -556,6 +574,9 @@ mod frames {
556 574 .iter()
557 575 .chain(CALL_GUARDED)
558 576 .chain(CALLS_TAGS)
577 .chain(CHAT_FILTER_TAGS)
578 .chain(CHAT_FILTER_OPEN_TAGS)
579 .chain(FIND_TAGS)
559 580 .chain(PREJOIN_TAGS)
560 581 .chain(SHARE_GUARDED)
561 582 .chain(CONSULT_GUARDED)
@@ -766,7 +787,26 @@ mod frames {
766 787 size: size(px(width), px(height)),
767 788 };
768 789 let screens = [
769 Screen::Tab("chats", None),
790 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
791 Screen::Tab(
792 "chat-filter",
793 Some(|visual| {
794 visual.dispatch_action(OpenChatsTab);
795 visual.dispatch_action(OpenChatFilter);
796 visual.dispatch_action(FilterMutedChats);
797 visual.run_until_parked();
798 visual.simulate_input("zzz");
799 }),
800 ),
801 Screen::Tab(
802 "find",
803 Some(|visual| {
804 visual.dispatch_action(OpenChatsTab);
805 visual.dispatch_action(FindInChat);
806 visual.run_until_parked();
807 visual.simulate_input("access");
808 }),
809 ),
770 810 Screen::Tab(
771 811 "activity",
772 812 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -899,6 +939,12 @@ mod frames {
899 939 expected.push(MENU);
900 940 }
901 941 match screen_name {
942 "chats" => expected.extend(CHAT_FILTER_TAGS),
943 "chat-filter" => {
944 expected.extend(CHAT_FILTER_TAGS);
945 expected.extend(CHAT_FILTER_OPEN_TAGS);
946 }
947 "find" => expected.extend(FIND_TAGS),
902 948 "calls" => expected.extend(CALLS_TAGS),
903 949 "agents" => expected.push(AGENTS_LIST),
904 950 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -938,6 +984,15 @@ mod frames {
938 984 })
939 985 });
940 986 }
987 if screen_name == "find" {
988 visual.dispatch_action(gpui_kit::component::input::Escape);
989 visual.run_until_parked();
990 }
991 if screen_name == "chat-filter" {
992 visual.dispatch_action(ClearChatFilters);
993 visual.dispatch_action(OpenChatFilter);
994 visual.run_until_parked();
995 }
941 996 if screen_name == "prejoin" {
942 997 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
943 998 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
@@ -1509,6 +1564,45 @@ mod frames {
1509 1564 );
1510 1565 }
1511 1566
1567 #[gpui_kit::test]
1568 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1569 let (handle, state) = mount(cx);
1570 let mut visual = VisualTestContext::from_window(handle, cx);
1571 visual.simulate_resize(size(px(1280.), px(800.)));
1572 visual.update(|_, cx| {
1573 state.update(cx, |state, cx| {
1574 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1575 })
1576 });
1577 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1578 let button = visual
1579 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1580 .expect("channel details button");
1581 visual.simulate_click(button.center(), Default::default());
1582 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1583 let pane = visual
1584 .debug_bounds(CHANNEL_DETAILS_TAG)
1585 .expect("details pane");
1586 let pinned = visual
1587 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1588 .expect("pinned section");
1589 let shared = visual
1590 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1591 .expect("shared section");
1592 assert!(
1593 pinned.bottom() <= shared.top(),
1594 "pinned {pinned:?} must come before shared {shared:?}"
1595 );
1596 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1597 let left = f32::from(section.left() - pane.left());
1598 let right = f32::from(pane.right() - section.right());
1599 assert!(
1600 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1601 "{name} section insets left {left} right {right} must match"
1602 );
1603 }
1604 }
1605
1512 1606 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1513 1607 collect(visual, Some(COMPOSER_SEND_TAG));
1514 1608 let mut bounds_of = |path: &'static str| {
@@ -180,8 +180,14 @@ mod frames {
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
180 COMPOSER_BOX_TAG, COMPOSER_FORMAT_BAR_TAG, COMPOSER_FORMAT_DIVIDER_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
181 COMPOSER_FORMAT_TAG, COMPOSER_LEADING_TAG, COMPOSER_SEND_TAG,
182 };
182 };
183 use crate::views::conversation::{CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_TAG};
183 use crate::views::conversation::{
184 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
185 CHANNEL_DETAILS_TAG,
186 };
184 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
187 use crate::views::conversation::{HEADER_DIVIDER, MEMBERS_BUTTON, TIMELINE_TAG};
188 use crate::views::find_panel::{
189 FIND_DIVIDER_TAG, FIND_INPUT_TAG, FIND_PANEL_TAG, FIND_RESULTS_TAG,
190 };
185 use crate::views::message_row::BUBBLE_TAGS;
191 use crate::views::message_row::BUBBLE_TAGS;
186 use crate::views::pin_banner::PIN_BANNER_TAG;
192 use crate::views::pin_banner::PIN_BANNER_TAG;
187 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
193 use crate::views::proposal_card::{PROPOSAL_BUTTONS, PROPOSAL_CARD, PROPOSAL_THUMBNAILS};
@@ -191,9 +197,13 @@ mod frames {
191 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
197 AppShell, Startup, bind_keys, install_globals, sidebar_hidden_in_call,
192 };
198 };
193 use crate::views::shortcuts::{
199 use crate::views::shortcuts::{
194 OpenActivity, OpenAgents, OpenCallsTab, OpenChannelsTab, OpenSaved,
200 ClearChatFilters, FilterMutedChats, FindInChat, OpenActivity, OpenAgents, OpenCallsTab,
201 OpenChannelsTab, OpenChatFilter, OpenChatsTab, OpenSaved,
195 };
202 };
196 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
203 use crate::views::sidebar::SIDEBAR_SCROLL_DIVIDER;
204 use crate::views::sidebar::chat_filter_bar::{
205 FILTER_EMPTY_TAG, FILTER_INPUT_TAG, FILTER_PILLS_TAG, FILTER_TAG,
206 };
197 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
207 use crate::views::status_menu::{OWN_AVATAR_DISC, TITLE_AVATAR_SIZE};
198
208
199 const GUARDED: &[&str] = &[
209 const GUARDED: &[&str] = &[
@@ -216,6 +226,14 @@ mod frames {
216 "shell/islands/main/call-controls/leave",
226 "shell/islands/main/call-controls/leave",
217 ];
227 ];
218 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
228 const AGENTS_LIST: &str = "shell/islands/sidebar/agents";
229 const CHAT_FILTER_TAGS: &[&str] = &[FILTER_TAG, FILTER_PILLS_TAG];
230 const CHAT_FILTER_OPEN_TAGS: &[&str] = &[FILTER_INPUT_TAG, FILTER_EMPTY_TAG];
231 const FIND_TAGS: &[&str] = &[
232 FIND_PANEL_TAG,
233 FIND_DIVIDER_TAG,
234 FIND_INPUT_TAG,
235 FIND_RESULTS_TAG,
236 ];
219 const CALLS_TAGS: &[&str] = &[
237 const CALLS_TAGS: &[&str] = &[
220 "shell/islands/sidebar/calls-actions",
238 "shell/islands/sidebar/calls-actions",
221 "shell/islands/sidebar/calls-actions/meet-now",
239 "shell/islands/sidebar/calls-actions/meet-now",
@@ -556,6 +574,9 @@ mod frames {
556 .iter()
574 .iter()
557 .chain(CALL_GUARDED)
575 .chain(CALL_GUARDED)
558 .chain(CALLS_TAGS)
576 .chain(CALLS_TAGS)
577 .chain(CHAT_FILTER_TAGS)
578 .chain(CHAT_FILTER_OPEN_TAGS)
579 .chain(FIND_TAGS)
559 .chain(PREJOIN_TAGS)
580 .chain(PREJOIN_TAGS)
560 .chain(SHARE_GUARDED)
581 .chain(SHARE_GUARDED)
561 .chain(CONSULT_GUARDED)
582 .chain(CONSULT_GUARDED)
@@ -766,7 +787,26 @@ mod frames {
766 size: size(px(width), px(height)),
787 size: size(px(width), px(height)),
767 };
788 };
768 let screens = [
789 let screens = [
769 Screen::Tab("chats", None),
790 Screen::Tab("chats", Some(|visual| visual.dispatch_action(OpenChatsTab))),
791 Screen::Tab(
792 "chat-filter",
793 Some(|visual| {
794 visual.dispatch_action(OpenChatsTab);
795 visual.dispatch_action(OpenChatFilter);
796 visual.dispatch_action(FilterMutedChats);
797 visual.run_until_parked();
798 visual.simulate_input("zzz");
799 }),
800 ),
801 Screen::Tab(
802 "find",
803 Some(|visual| {
804 visual.dispatch_action(OpenChatsTab);
805 visual.dispatch_action(FindInChat);
806 visual.run_until_parked();
807 visual.simulate_input("access");
808 }),
809 ),
770 Screen::Tab(
810 Screen::Tab(
771 "activity",
811 "activity",
772 Some(|visual| visual.dispatch_action(OpenActivity)),
812 Some(|visual| visual.dispatch_action(OpenActivity)),
@@ -899,6 +939,12 @@ mod frames {
899 expected.push(MENU);
939 expected.push(MENU);
900 }
940 }
901 match screen_name {
941 match screen_name {
942 "chats" => expected.extend(CHAT_FILTER_TAGS),
943 "chat-filter" => {
944 expected.extend(CHAT_FILTER_TAGS);
945 expected.extend(CHAT_FILTER_OPEN_TAGS);
946 }
947 "find" => expected.extend(FIND_TAGS),
902 "calls" => expected.extend(CALLS_TAGS),
948 "calls" => expected.extend(CALLS_TAGS),
903 "agents" => expected.push(AGENTS_LIST),
949 "agents" => expected.push(AGENTS_LIST),
904 "prejoin" => expected.extend(PREJOIN_TAGS),
950 "prejoin" => expected.extend(PREJOIN_TAGS),
@@ -938,6 +984,15 @@ mod frames {
938 })
984 })
939 });
985 });
940 }
986 }
987 if screen_name == "find" {
988 visual.dispatch_action(gpui_kit::component::input::Escape);
989 visual.run_until_parked();
990 }
991 if screen_name == "chat-filter" {
992 visual.dispatch_action(ClearChatFilters);
993 visual.dispatch_action(OpenChatFilter);
994 visual.run_until_parked();
995 }
941 if screen_name == "prejoin" {
996 if screen_name == "prejoin" {
942 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
997 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
943 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
998 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
@@ -1509,6 +1564,45 @@ mod frames {
1509 );
1564 );
1510 }
1565 }
1511
1566
1567 #[gpui_kit::test]
1568 fn the_channel_details_sections_follow_teams_order_with_equal_insets(cx: &mut TestAppContext) {
1569 let (handle, state) = mount(cx);
1570 let mut visual = VisualTestContext::from_window(handle, cx);
1571 visual.simulate_resize(size(px(1280.), px(800.)));
1572 visual.update(|_, cx| {
1573 state.update(cx, |state, cx| {
1574 state.select(Selection::Channel(PINNED_CHANNEL.to_owned()), cx)
1575 })
1576 });
1577 collect(&mut visual, Some(CHANNEL_DETAILS_BUTTON));
1578 let button = visual
1579 .debug_bounds(CHANNEL_DETAILS_BUTTON)
1580 .expect("channel details button");
1581 visual.simulate_click(button.center(), Default::default());
1582 collect(&mut visual, Some(CHANNEL_DETAILS_SHARED_TAG));
1583 let pane = visual
1584 .debug_bounds(CHANNEL_DETAILS_TAG)
1585 .expect("details pane");
1586 let pinned = visual
1587 .debug_bounds(CHANNEL_DETAILS_PINNED_TAG)
1588 .expect("pinned section");
1589 let shared = visual
1590 .debug_bounds(CHANNEL_DETAILS_SHARED_TAG)
1591 .expect("shared section");
1592 assert!(
1593 pinned.bottom() <= shared.top(),
1594 "pinned {pinned:?} must come before shared {shared:?}"
1595 );
1596 for (name, section) in [("pinned", pinned), ("shared", shared)] {
1597 let left = f32::from(section.left() - pane.left());
1598 let right = f32::from(pane.right() - section.right());
1599 assert!(
1600 (left - right).abs() < INSET_TOLERANCE && left > 0.,
1601 "{name} section insets left {left} right {right} must match"
1602 );
1603 }
1604 }
1605
1512 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1606 fn composer_button_insets(visual: &mut VisualTestContext) -> [f32; 6] {
1513 collect(visual, Some(COMPOSER_SEND_TAG));
1607 collect(visual, Some(COMPOSER_SEND_TAG));
1514 let mut bounds_of = |path: &'static str| {
1608 let mut bounds_of = |path: &'static str| {
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/conversation.rs +110 −12
@@ -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;
@@ -44,7 +47,9 @@ use super::call_controls::header_call_controls;
44 47 use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
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};
@@ -101,6 +106,7 @@ const HEADER_PADDING: f32 = 20.;
101 106 const HEADER_GAP: f32 = 12.;
102 107 const HEADER_LEAD_SIZE: f32 = 36.;
103 108 const TABS_INLINE_MIN_WIDTH: f32 = 560.;
109 const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
104 110 const TABS_ROW_HEIGHT: f32 = 36.;
105 111 const CHAT_OPEN_LIMIT: usize = 60;
106 112 const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -240,6 +246,8 @@ pub struct ConversationView {
240 246 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
241 247 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
242 248 receipt_fade: receipt_fade::ReceiptFade,
249 find_panel: Option<Entity<FindPanel>>,
250 find_subscription: Option<Subscription>,
243 251 _subscriptions: Vec<Subscription>,
244 252 }
245 253
@@ -571,6 +579,8 @@ impl ConversationView {
571 579 agent_runs: Rc::new(RefCell::new(HashMap::new())),
572 580 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
573 581 receipt_fade: receipt_fade::ReceiptFade::default(),
582 find_panel: None,
583 find_subscription: None,
574 584 _subscriptions: subscriptions,
575 585 };
576 586 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -640,7 +650,7 @@ impl ConversationView {
640 650 .as_ref()
641 651 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
642 652 if is_current {
643 if self.shared_active() || self.recap_active() {
653 if self.shared_active() || self.recap_active() || self.channel_details_open {
644 654 self.refresh_shared_items(cx);
645 655 }
646 656 self.rebuild(false, cx);
@@ -847,6 +857,14 @@ impl ConversationView {
847 857 }
848 858
849 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 }
850 868 self.stop_typing(cx);
851 869 self.stop_reply_typing(cx);
852 870 self.new_post_open = false;
@@ -3033,6 +3051,7 @@ impl ConversationView {
3033 3051 let saved = self
3034 3052 .conversation_id()
3035 3053 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3054 let quick = state.quick_reactions();
3036 3055 let in_chat = chat_id.is_some();
3037 3056 let pin_conversation_id = self.pin_conversation_id();
3038 3057 let pinned = pin_conversation_id
@@ -3058,7 +3077,8 @@ impl ConversationView {
3058 3077 translate_label,
3059 3078 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3060 3079 saved,
3061 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3080 toggle_pinned: pinnable
3081 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3062 3082 pinned,
3063 3083 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3064 3084 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3070,7 +3090,7 @@ impl ConversationView {
3070 3090 pin,
3071 3091 hover,
3072 3092 picker: self.picker.clone(),
3073 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3093 quick,
3074 3094 mine,
3075 3095 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3076 3096 }
@@ -3237,6 +3257,51 @@ impl ConversationView {
3237 3257 )
3238 3258 }
3239 3259
3260 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3261 if self.pinned || self.draft_active {
3262 return;
3263 }
3264 let Some(selection) = self
3265 .current
3266 .as_ref()
3267 .map(|current| current.selection.clone())
3268 else {
3269 return;
3270 };
3271 self.channel_details_open = false;
3272 if let Some(panel) = &self.find_panel {
3273 panel.update(cx, |panel, cx| panel.focus(window, cx));
3274 return;
3275 }
3276 let app = self.app.clone();
3277 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3278 let subscription = cx.subscribe_in(
3279 &panel,
3280 window,
3281 move |this, _, event: &FindPanelEvent, window, cx| match event {
3282 FindPanelEvent::Close => this.close_find(window, cx),
3283 FindPanelEvent::Jump(message_id) => {
3284 let (selection, message_id) = (selection.clone(), message_id.clone());
3285 this.app.update(cx, |state, cx| {
3286 state.jump_to_message(selection, message_id, cx)
3287 });
3288 }
3289 },
3290 );
3291 panel.update(cx, |panel, cx| panel.focus(window, cx));
3292 self.find_panel = Some(panel);
3293 self.find_subscription = Some(subscription);
3294 cx.notify();
3295 }
3296
3297 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3298 self.find_panel = None;
3299 self.find_subscription = None;
3300 self.composer
3301 .update(cx, |composer, cx| composer.focus(window, cx));
3302 cx.notify();
3303 }
3304
3240 3305 fn header_width(&self, window: &Window) -> f32 {
3241 3306 match self.header_width.get() {
3242 3307 width if width > 0. => width,
@@ -3265,6 +3330,7 @@ impl ConversationView {
3265 3330 let mut lead: Option<AnyElement> = None;
3266 3331 let mut subline = String::new();
3267 3332 let mut stack: Option<AnyElement> = None;
3333 let mut rename: Option<AnyElement> = None;
3268 3334 match &current.selection {
3269 3335 Selection::Chat(chat_id) => {
3270 3336 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3300,6 +3366,15 @@ impl ConversationView {
3300 3366 stack = Some(add_people_button(&self.app, chat_id));
3301 3367 }
3302 3368 } else {
3369 if chat.kind == GROUP_KIND
3370 && me.is_some_and(|me| {
3371 chat.members
3372 .iter()
3373 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3374 })
3375 {
3376 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3377 }
3303 3378 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3304 3379 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3305 3380 subline = format!("{} participants", chat.members.len());
@@ -3402,12 +3477,19 @@ impl ConversationView {
3402 3477 .overflow_hidden()
3403 3478 .gap(px(1.))
3404 3479 .child(
3405 div()
3406 .truncate()
3407 .text_size(px(15.))
3408 .font_weight(FontWeight::SEMIBOLD)
3409 .text_color(theme::text())
3410 .child(current.title.clone()),
3480 h_flex()
3481 .min_w_0()
3482 .gap(px(2.))
3483 .items_center()
3484 .child(
3485 div()
3486 .truncate()
3487 .text_size(px(15.))
3488 .font_weight(FontWeight::SEMIBOLD)
3489 .text_color(theme::text())
3490 .child(current.title.clone()),
3491 )
3492 .children(rename),
3411 3493 )
3412 3494 .when(!subline.is_empty(), |column| {
3413 3495 column.child(
@@ -3425,6 +3507,8 @@ impl ConversationView {
3425 3507 }
3426 3508 }
3427 3509
3510 const GROUP_KIND: &str = "group";
3511
3428 3512 impl Render for ConversationView {
3429 3513 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3430 3514 let background = theme::surface();
@@ -3657,6 +3741,8 @@ impl Render for ConversationView {
3657 3741 scroller.into_any_element()
3658 3742 };
3659 3743 let channel_details = self.render_channel_details(cx);
3744 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3745 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3660 3746 let content = v_flex()
3661 3747 .relative()
3662 3748 .flex_1()
@@ -3684,12 +3770,24 @@ impl Render for ConversationView {
3684 3770 .child(self.render_drop_overlay(cx));
3685 3771 root.child(
3686 3772 h_flex()
3773 .relative()
3687 3774 .flex_1()
3688 3775 .min_h_0()
3689 3776 .w_full()
3690 3777 .items_stretch()
3691 3778 .child(content)
3692 .children(channel_details),
3779 .children(channel_details)
3780 .children(find_panel.map(|panel| {
3781 div()
3782 .h_full()
3783 .w(px(FIND_PANEL_WIDTH))
3784 .min_w_0()
3785 .flex_shrink(1.)
3786 .when(find_overlays, |slot| {
3787 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3788 })
3789 .child(panel)
3790 })),
3693 3791 )
3694 3792 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3695 3793 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;
@@ -44,7 +47,9 @@ use super::call_controls::header_call_controls;
44use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
47use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
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};
@@ -101,6 +106,7 @@ const HEADER_PADDING: f32 = 20.;
101const HEADER_GAP: f32 = 12.;
106const HEADER_GAP: f32 = 12.;
102const HEADER_LEAD_SIZE: f32 = 36.;
107const HEADER_LEAD_SIZE: f32 = 36.;
103const TABS_INLINE_MIN_WIDTH: f32 = 560.;
108const TABS_INLINE_MIN_WIDTH: f32 = 560.;
109const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
104const TABS_ROW_HEIGHT: f32 = 36.;
110const TABS_ROW_HEIGHT: f32 = 36.;
105const CHAT_OPEN_LIMIT: usize = 60;
111const CHAT_OPEN_LIMIT: usize = 60;
106const CHANNEL_OPEN_LIMIT: usize = 300;
112const CHANNEL_OPEN_LIMIT: usize = 300;
@@ -240,6 +246,8 @@ pub struct ConversationView {
240 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
246 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
241 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
247 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
242 receipt_fade: receipt_fade::ReceiptFade,
248 receipt_fade: receipt_fade::ReceiptFade,
249 find_panel: Option<Entity<FindPanel>>,
250 find_subscription: Option<Subscription>,
243 _subscriptions: Vec<Subscription>,
251 _subscriptions: Vec<Subscription>,
244}
252}
245
253
@@ -571,6 +579,8 @@ impl ConversationView {
571 agent_runs: Rc::new(RefCell::new(HashMap::new())),
579 agent_runs: Rc::new(RefCell::new(HashMap::new())),
572 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
580 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
573 receipt_fade: receipt_fade::ReceiptFade::default(),
581 receipt_fade: receipt_fade::ReceiptFade::default(),
582 find_panel: None,
583 find_subscription: None,
574 _subscriptions: subscriptions,
584 _subscriptions: subscriptions,
575 };
585 };
576 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()) {
@@ -640,7 +650,7 @@ impl ConversationView {
640 .as_ref()
650 .as_ref()
641 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
651 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
642 if is_current {
652 if is_current {
643 if self.shared_active() || self.recap_active() {
653 if self.shared_active() || self.recap_active() || self.channel_details_open {
644 self.refresh_shared_items(cx);
654 self.refresh_shared_items(cx);
645 }
655 }
646 self.rebuild(false, cx);
656 self.rebuild(false, cx);
@@ -847,6 +857,14 @@ impl ConversationView {
847 }
857 }
848
858
849 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 }
850 self.stop_typing(cx);
868 self.stop_typing(cx);
851 self.stop_reply_typing(cx);
869 self.stop_reply_typing(cx);
852 self.new_post_open = false;
870 self.new_post_open = false;
@@ -3033,6 +3051,7 @@ impl ConversationView {
3033 let saved = self
3051 let saved = self
3034 .conversation_id()
3052 .conversation_id()
3035 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3053 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3054 let quick = state.quick_reactions();
3036 let in_chat = chat_id.is_some();
3055 let in_chat = chat_id.is_some();
3037 let pin_conversation_id = self.pin_conversation_id();
3056 let pin_conversation_id = self.pin_conversation_id();
3038 let pinned = pin_conversation_id
3057 let pinned = pin_conversation_id
@@ -3058,7 +3077,8 @@ impl ConversationView {
3058 translate_label,
3077 translate_label,
3059 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3078 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3060 saved,
3079 saved,
3061 toggle_pinned: pinnable.then(|| action(|this, key, _, cx| this.toggle_pinned(key, cx))),
3080 toggle_pinned: pinnable
3081 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3062 pinned,
3082 pinned,
3063 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3083 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3064 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3084 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
@@ -3070,7 +3090,7 @@ impl ConversationView {
3070 pin,
3090 pin,
3071 hover,
3091 hover,
3072 picker: self.picker.clone(),
3092 picker: self.picker.clone(),
3073 quick: self.recent.read(cx).most_used(QUICK_REACTION_COUNT),
3093 quick,
3074 mine,
3094 mine,
3075 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3095 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3076 }
3096 }
@@ -3237,6 +3257,51 @@ impl ConversationView {
3237 )
3257 )
3238 }
3258 }
3239
3259
3260 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3261 if self.pinned || self.draft_active {
3262 return;
3263 }
3264 let Some(selection) = self
3265 .current
3266 .as_ref()
3267 .map(|current| current.selection.clone())
3268 else {
3269 return;
3270 };
3271 self.channel_details_open = false;
3272 if let Some(panel) = &self.find_panel {
3273 panel.update(cx, |panel, cx| panel.focus(window, cx));
3274 return;
3275 }
3276 let app = self.app.clone();
3277 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3278 let subscription = cx.subscribe_in(
3279 &panel,
3280 window,
3281 move |this, _, event: &FindPanelEvent, window, cx| match event {
3282 FindPanelEvent::Close => this.close_find(window, cx),
3283 FindPanelEvent::Jump(message_id) => {
3284 let (selection, message_id) = (selection.clone(), message_id.clone());
3285 this.app.update(cx, |state, cx| {
3286 state.jump_to_message(selection, message_id, cx)
3287 });
3288 }
3289 },
3290 );
3291 panel.update(cx, |panel, cx| panel.focus(window, cx));
3292 self.find_panel = Some(panel);
3293 self.find_subscription = Some(subscription);
3294 cx.notify();
3295 }
3296
3297 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3298 self.find_panel = None;
3299 self.find_subscription = None;
3300 self.composer
3301 .update(cx, |composer, cx| composer.focus(window, cx));
3302 cx.notify();
3303 }
3304
3240 fn header_width(&self, window: &Window) -> f32 {
3305 fn header_width(&self, window: &Window) -> f32 {
3241 match self.header_width.get() {
3306 match self.header_width.get() {
3242 width if width > 0. => width,
3307 width if width > 0. => width,
@@ -3265,6 +3330,7 @@ impl ConversationView {
3265 let mut lead: Option<AnyElement> = None;
3330 let mut lead: Option<AnyElement> = None;
3266 let mut subline = String::new();
3331 let mut subline = String::new();
3267 let mut stack: Option<AnyElement> = None;
3332 let mut stack: Option<AnyElement> = None;
3333 let mut rename: Option<AnyElement> = None;
3268 match &current.selection {
3334 match &current.selection {
3269 Selection::Chat(chat_id) => {
3335 Selection::Chat(chat_id) => {
3270 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3336 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
@@ -3300,6 +3366,15 @@ impl ConversationView {
3300 stack = Some(add_people_button(&self.app, chat_id));
3366 stack = Some(add_people_button(&self.app, chat_id));
3301 }
3367 }
3302 } else {
3368 } else {
3369 if chat.kind == GROUP_KIND
3370 && me.is_some_and(|me| {
3371 chat.members
3372 .iter()
3373 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3374 })
3375 {
3376 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3377 }
3303 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3378 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3304 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3379 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3305 subline = format!("{} participants", chat.members.len());
3380 subline = format!("{} participants", chat.members.len());
@@ -3402,12 +3477,19 @@ impl ConversationView {
3402 .overflow_hidden()
3477 .overflow_hidden()
3403 .gap(px(1.))
3478 .gap(px(1.))
3404 .child(
3479 .child(
3405 div()
3480 h_flex()
3406 .truncate()
3481 .min_w_0()
3407 .text_size(px(15.))
3482 .gap(px(2.))
3408 .font_weight(FontWeight::SEMIBOLD)
3483 .items_center()
3409 .text_color(theme::text())
3484 .child(
3410 .child(current.title.clone()),
3485 div()
3486 .truncate()
3487 .text_size(px(15.))
3488 .font_weight(FontWeight::SEMIBOLD)
3489 .text_color(theme::text())
3490 .child(current.title.clone()),
3491 )
3492 .children(rename),
3411 )
3493 )
3412 .when(!subline.is_empty(), |column| {
3494 .when(!subline.is_empty(), |column| {
3413 column.child(
3495 column.child(
@@ -3425,6 +3507,8 @@ impl ConversationView {
3425 }
3507 }
3426}
3508}
3427
3509
3510const GROUP_KIND: &str = "group";
3511
3428impl Render for ConversationView {
3512impl Render for ConversationView {
3429 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3513 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3430 let background = theme::surface();
3514 let background = theme::surface();
@@ -3657,6 +3741,8 @@ impl Render for ConversationView {
3657 scroller.into_any_element()
3741 scroller.into_any_element()
3658 };
3742 };
3659 let channel_details = self.render_channel_details(cx);
3743 let channel_details = self.render_channel_details(cx);
3744 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3745 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3660 let content = v_flex()
3746 let content = v_flex()
3661 .relative()
3747 .relative()
3662 .flex_1()
3748 .flex_1()
@@ -3684,12 +3770,24 @@ impl Render for ConversationView {
3684 .child(self.render_drop_overlay(cx));
3770 .child(self.render_drop_overlay(cx));
3685 root.child(
3771 root.child(
3686 h_flex()
3772 h_flex()
3773 .relative()
3687 .flex_1()
3774 .flex_1()
3688 .min_h_0()
3775 .min_h_0()
3689 .w_full()
3776 .w_full()
3690 .items_stretch()
3777 .items_stretch()
3691 .child(content)
3778 .child(content)
3692 .children(channel_details),
3779 .children(channel_details)
3780 .children(find_panel.map(|panel| {
3781 div()
3782 .h_full()
3783 .w(px(FIND_PANEL_WIDTH))
3784 .min_w_0()
3785 .flex_shrink(1.)
3786 .when(find_overlays, |slot| {
3787 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3788 })
3789 .child(panel)
3790 })),
3693 )
3791 )
3694 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3792 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3695 if this.reaction_details.is_some() {
3793 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/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/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/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/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 +14 −1
@@ -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};
@@ -233,7 +233,20 @@ impl Render for MeetingForm {
233 233 }
234 234
235 235 pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
236 open_new_meeting_with(state, Vec::new(), window, cx);
237 }
238
239 pub fn open_new_meeting_with(
240 state: Entity<AppState>,
241 people: Vec<Pick>,
242 window: &mut Window,
243 cx: &mut App,
244 ) {
236 245 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
246 if !people.is_empty() {
247 let draft = form.read(cx).people.clone();
248 draft.update(cx, |draft, cx| draft.set_chips(people, cx));
249 }
237 250 let first_field = form.read(cx).title.clone();
238 251 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239 252 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};
@@ -233,7 +233,20 @@ impl Render for MeetingForm {
233}
233}
234
234
235pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
235pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
236 open_new_meeting_with(state, Vec::new(), window, cx);
237}
238
239pub fn open_new_meeting_with(
240 state: Entity<AppState>,
241 people: Vec<Pick>,
242 window: &mut Window,
243 cx: &mut App,
244) {
236 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
245 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
246 if !people.is_empty() {
247 let draft = form.read(cx).people.clone();
248 draft.update(cx, |draft, cx| draft.set_chips(people, cx));
249 }
237 let first_field = form.read(cx).title.clone();
250 let first_field = form.read(cx).title.clone();
238 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
251 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
239 let submit_form = form.clone();
252 let submit_form = form.clone();
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/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/shell.rs +40 −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
@@ -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
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 +193 −8
@@ -24,7 +24,11 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24 24 use super::widgets::{count_badge, icon, page_header, unread_marker};
25 25 use crate::agents::AgentsPanel;
26 26 use crate::app_state::{AppEvent, AppState, Selection};
27 use crate::channel_menu::{
28 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
29 };
27 30 use crate::chat_actions::TITLE_LIMIT;
31 use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
28 32 use crate::data::{Directory, is_pending_folder};
29 33 use crate::format;
30 34 use crate::local_previews::LocalPreview;
@@ -38,6 +42,9 @@ use crate::sidebar_model::{
38 42 };
39 43 use crate::theme;
40 44 use app_ui_kit::layout::SIDEBAR_WIDTH;
45 use gpui_kit::component::input::InputState;
46
47 pub(crate) mod chat_filter_bar;
41 48
42 49 pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
43 50 const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -223,7 +230,7 @@ fn chat_menu(
223 230 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
224 231 }),
225 232 );
226 popup = notifications_submenu(popup, window, cx, context, target)
233 popup = chat_notifications_submenu(popup, window, cx, context, target)
227 234 .separator()
228 235 .item(
229 236 PopupMenuItem::new("Hide")
@@ -232,6 +239,17 @@ fn chat_menu(
232 239 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
233 240 }),
234 241 );
242 if !target.is_group {
243 let remove_state = context.state.clone();
244 let remove_id = target.id.clone();
245 popup = popup.item(
246 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
247 .icon(menu_icon(IconName::Trash))
248 .on_click(move |_, window, cx| {
249 confirm_remove_history(&remove_state, &remove_id, window, cx);
250 }),
251 );
252 }
235 253 if target.is_group {
236 254 let leave_state = context.state.clone();
237 255 let leave_id = target.id.clone();
@@ -263,7 +281,7 @@ const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
263 281 ("Don't get desktop notifications", DesktopNotifications::Off),
264 282 ];
265 283
266 fn notifications_submenu(
284 fn chat_notifications_submenu(
267 285 popup: PopupMenu,
268 286 window: &mut Window,
269 287 cx: &mut Context<PopupMenu>,
@@ -513,6 +531,40 @@ fn leave_description(member_count: usize) -> String {
513 531 format!("{who} {verb} that you left. You can only come back if someone adds you.")
514 532 }
515 533
534 const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
535 const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
536 const REMOVE_HISTORY_TEXT: &str =
537 "This will remove the chat from your list and search. It affects you only.";
538
539 fn confirm_remove_history(
540 state: &Entity<AppState>,
541 chat_id: &str,
542 window: &mut Window,
543 cx: &mut App,
544 ) {
545 let state = state.clone();
546 let chat_id = chat_id.to_owned();
547 window.open_alert_dialog(cx, move |alert, _, _| {
548 let state = state.clone();
549 let chat_id = chat_id.clone();
550 let cancel = Button::new("remove-history-cancel")
551 .label("Cancel")
552 .on_click(|_, window, cx| window.close_dialog(cx));
553 let remove = Button::new("remove-history-confirm")
554 .label("Remove")
555 .primary()
556 .on_click(move |_, window, cx| {
557 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
558 window.close_dialog(cx);
559 });
560 alert
561 .title(REMOVE_HISTORY_TITLE)
562 .description(REMOVE_HISTORY_TEXT)
563 .footer(DialogFooter::new().child(cancel).child(remove))
564 .on_ok(|_, _, _| false)
565 });
566 }
567
516 568 pub(crate) fn confirm_leave(
517 569 state: &Entity<AppState>,
518 570 chat_id: &str,
@@ -546,6 +598,12 @@ pub(crate) fn confirm_leave(
546 598 });
547 599 }
548 600
601 pub enum SidebarEvent {
602 RestoreFocus,
603 }
604
605 impl EventEmitter<SidebarEvent> for SidebarView {}
606
549 607 pub struct SidebarView {
550 608 state: Entity<AppState>,
551 609 tab: SidebarTab,
@@ -560,6 +618,12 @@ pub struct SidebarView {
560 618 older_chats_seen: Cell<(bool, bool)>,
561 619 channels_scroll: ScrollHandle,
562 620 calls_scroll: ScrollHandle,
621 chat_filter: ChatFilter,
622 filter_box_open: bool,
623 more_filters_open: bool,
624 filter_input: Option<Entity<InputState>>,
625 filter_subscription: Option<Subscription>,
626 _activity_observation: Subscription,
563 627 _subscription: Subscription,
564 628 _state_observation: Subscription,
565 629 _agent_observation: Option<Subscription>,
@@ -650,6 +714,15 @@ impl SidebarView {
650 714 SidebarTab::Chats
651 715 };
652 716 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
717 let activity = activity_panel.read(cx).activity();
718 let activity_observation = cx.observe(&activity, |view, _, cx| {
719 if view
720 .chat_filter
721 .has(crate::chat_filter::ChatFilterPill::Mentions)
722 {
723 cx.notify();
724 }
725 });
653 726 cx.spawn(async move |this, cx| {
654 727 loop {
655 728 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -678,6 +751,12 @@ impl SidebarView {
678 751 older_chats_seen: Cell::new((false, false)),
679 752 channels_scroll: ScrollHandle::new(),
680 753 calls_scroll: ScrollHandle::new(),
754 chat_filter: ChatFilter::default(),
755 filter_box_open: false,
756 more_filters_open: false,
757 filter_input: None,
758 filter_subscription: None,
759 _activity_observation: activity_observation,
681 760 _subscription: subscription,
682 761 _state_observation: state_observation,
683 762 _agent_observation: agent_observation,
@@ -1164,7 +1243,18 @@ impl SidebarView {
1164 1243 now,
1165 1244 offset,
1166 1245 };
1167 let sections = build_sections(&input);
1246 let sections = if self.chat_filter.is_active() {
1247 let mentioned = self.mentioned_chats(cx);
1248 let selected_id = self.selected_chat_id(cx);
1249 filtered_sections(
1250 &input,
1251 &self.chat_filter,
1252 &mentioned,
1253 selected_id.as_deref(),
1254 )
1255 } else {
1256 build_sections(&input)
1257 };
1168 1258 let menu = MenuContext {
1169 1259 state: self.state.clone(),
1170 1260 folders: state.directory.move_targets(),
@@ -1289,6 +1379,10 @@ impl SidebarView {
1289 1379 .child(LOADING_OLDER_LABEL),
1290 1380 );
1291 1381 }
1382 let selected_chat_id = self.selected_chat_id(cx);
1383 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1384 list = list.child(self.filter_empty_state(cx));
1385 }
1292 1386 list = with_spacer(list, &mut skipped_height);
1293 1387 self.request_lazy_data(faces, presence_users, cx);
1294 1388 let scroll_area = div()
@@ -1445,6 +1539,8 @@ impl SidebarView {
1445 1539 let name_style = team_name_style(entry, expanded);
1446 1540 let badge = team_badge(entry, expanded);
1447 1541 let toggle_id = team_id.clone();
1542 let (team_menu_state, team_menu_id, team_hidden) =
1543 (self.state.clone(), team_id.clone(), entry.hidden);
1448 1544 list = list.child(
1449 1545 h_flex()
1450 1546 .id(SharedString::from(format!("team-{team_id}")))
@@ -1484,7 +1580,10 @@ impl SidebarView {
1484 1580 }
1485 1581 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1486 1582 cx.notify();
1487 })),
1583 }))
1584 .context_menu(move |popup, _, _| {
1585 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1586 }),
1488 1587 );
1489 1588 if !expanded {
1490 1589 return list;
@@ -1759,7 +1858,87 @@ fn channel_menu(
1759 1858 channel_id: &str,
1760 1859 notifications: ChannelNotifications,
1761 1860 ) -> PopupMenu {
1762 let channel_id = channel_id.to_owned();
1861 let menu_state = state.read(cx).channel_menu_state(channel_id);
1862 let mut popup = popup;
1863 for entry in channel_menu_entries(menu_state) {
1864 let item = match entry {
1865 MenuEntry::Separator => {
1866 popup = popup.separator();
1867 continue;
1868 }
1869 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1870 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1871 continue;
1872 }
1873 MenuEntry::Item(item) => item,
1874 };
1875 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1876 popup = popup.item(
1877 PopupMenuItem::new(item.label())
1878 .icon(menu_icon(channel_menu_icon(item)))
1879 .disabled(menu_state.disables(item))
1880 .on_click(move |_, _, cx| {
1881 action_state.update(cx, |state, cx| match item {
1882 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1883 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1884 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1885 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1886 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1887 ChannelMenuItem::Notifications => {}
1888 });
1889 }),
1890 );
1891 }
1892 popup
1893 }
1894
1895 fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1896 match item {
1897 ChannelMenuItem::Notifications => IconName::Bell,
1898 ChannelMenuItem::Pin => IconName::Pin,
1899 ChannelMenuItem::Unpin => IconName::PinOff,
1900 ChannelMenuItem::Show => IconName::Eye,
1901 ChannelMenuItem::Hide => IconName::EyeOff,
1902 ChannelMenuItem::CopyLink => IconName::Link,
1903 }
1904 }
1905
1906 fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1907 let mut popup = popup;
1908 for entry in team_menu_entries(hidden) {
1909 let MenuEntry::Item(item) = entry else {
1910 popup = popup.separator();
1911 continue;
1912 };
1913 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1914 popup = popup.item(
1915 PopupMenuItem::new(item.label())
1916 .icon(menu_icon(match item {
1917 TeamMenuItem::Show => IconName::Eye,
1918 TeamMenuItem::Hide => IconName::EyeOff,
1919 TeamMenuItem::CopyLink => IconName::Link,
1920 }))
1921 .on_click(move |_, _, cx| {
1922 action_state.update(cx, |state, cx| match item {
1923 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1924 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1925 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1926 });
1927 }),
1928 );
1929 }
1930 popup
1931 }
1932
1933 fn notifications_submenu(
1934 popup: PopupMenu,
1935 window: &mut Window,
1936 cx: &mut Context<PopupMenu>,
1937 state: &Entity<AppState>,
1938 channel_id: &str,
1939 notifications: ChannelNotifications,
1940 ) -> PopupMenu {
1941 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1763 1942 popup.submenu_with_icon(
1764 1943 Some(menu_icon(IconName::Bell)),
1765 1944 "Notifications",
@@ -1889,9 +2068,15 @@ impl Render for SidebarView {
1889 2068 };
1890 2069 let header = match self.tab {
1891 2070 SidebarTab::Chats => Some(
1892 page_header(self.tab.title())
1893 .child(self.chat_list_menu_button(cx))
1894 .child(self.new_chat_button(cx)),
2071 v_flex()
2072 .flex_none()
2073 .child(
2074 page_header(self.tab.title())
2075 .child(self.chat_list_menu_button(cx))
2076 .child(self.filter_toggle_button(cx))
2077 .child(self.new_chat_button(cx)),
2078 )
2079 .child(self.filter_bar(cx)),
1895 2080 ),
1896 2081 SidebarTab::Channels => {
1897 2082 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
@@ -24,7 +24,11 @@ use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
24use super::widgets::{count_badge, icon, page_header, unread_marker};
24use super::widgets::{count_badge, icon, page_header, unread_marker};
25use crate::agents::AgentsPanel;
25use crate::agents::AgentsPanel;
26use crate::app_state::{AppEvent, AppState, Selection};
26use crate::app_state::{AppEvent, AppState, Selection};
27use crate::channel_menu::{
28 ChannelMenuItem, MenuEntry, TeamMenuItem, channel_menu_entries, team_menu_entries,
29};
27use crate::chat_actions::TITLE_LIMIT;
30use crate::chat_actions::TITLE_LIMIT;
31use crate::chat_filter::{ChatFilter, filtered_sections, has_no_matches};
28use crate::data::{Directory, is_pending_folder};
32use crate::data::{Directory, is_pending_folder};
29use crate::format;
33use crate::format;
30use crate::local_previews::LocalPreview;
34use crate::local_previews::LocalPreview;
@@ -38,6 +42,9 @@ use crate::sidebar_model::{
38};
42};
39use crate::theme;
43use crate::theme;
40use app_ui_kit::layout::SIDEBAR_WIDTH;
44use app_ui_kit::layout::SIDEBAR_WIDTH;
45use gpui_kit::component::input::InputState;
46
47pub(crate) mod chat_filter_bar;
41
48
42pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
49pub const SIDEBAR_SCROLL_DIVIDER: &str = "shell/islands/sidebar/divider-scroll";
43const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
50const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
@@ -223,7 +230,7 @@ fn chat_menu(
223 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
230 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
224 }),
231 }),
225 );
232 );
226 popup = notifications_submenu(popup, window, cx, context, target)
233 popup = chat_notifications_submenu(popup, window, cx, context, target)
227 .separator()
234 .separator()
228 .item(
235 .item(
229 PopupMenuItem::new("Hide")
236 PopupMenuItem::new("Hide")
@@ -232,6 +239,17 @@ fn chat_menu(
232 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
239 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
233 }),
240 }),
234 );
241 );
242 if !target.is_group {
243 let remove_state = context.state.clone();
244 let remove_id = target.id.clone();
245 popup = popup.item(
246 PopupMenuItem::new(REMOVE_HISTORY_LABEL)
247 .icon(menu_icon(IconName::Trash))
248 .on_click(move |_, window, cx| {
249 confirm_remove_history(&remove_state, &remove_id, window, cx);
250 }),
251 );
252 }
235 if target.is_group {
253 if target.is_group {
236 let leave_state = context.state.clone();
254 let leave_state = context.state.clone();
237 let leave_id = target.id.clone();
255 let leave_id = target.id.clone();
@@ -263,7 +281,7 @@ const DESKTOP_NOTIFICATIONS: [(&str, DesktopNotifications); 2] = [
263 ("Don't get desktop notifications", DesktopNotifications::Off),
281 ("Don't get desktop notifications", DesktopNotifications::Off),
264];
282];
265
283
266fn notifications_submenu(
284fn chat_notifications_submenu(
267 popup: PopupMenu,
285 popup: PopupMenu,
268 window: &mut Window,
286 window: &mut Window,
269 cx: &mut Context<PopupMenu>,
287 cx: &mut Context<PopupMenu>,
@@ -513,6 +531,40 @@ fn leave_description(member_count: usize) -> String {
513 format!("{who} {verb} that you left. You can only come back if someone adds you.")
531 format!("{who} {verb} that you left. You can only come back if someone adds you.")
514}
532}
515
533
534const REMOVE_HISTORY_LABEL: &str = "Remove chat history";
535const REMOVE_HISTORY_TITLE: &str = "Remove chat history?";
536const REMOVE_HISTORY_TEXT: &str =
537 "This will remove the chat from your list and search. It affects you only.";
538
539fn confirm_remove_history(
540 state: &Entity<AppState>,
541 chat_id: &str,
542 window: &mut Window,
543 cx: &mut App,
544) {
545 let state = state.clone();
546 let chat_id = chat_id.to_owned();
547 window.open_alert_dialog(cx, move |alert, _, _| {
548 let state = state.clone();
549 let chat_id = chat_id.clone();
550 let cancel = Button::new("remove-history-cancel")
551 .label("Cancel")
552 .on_click(|_, window, cx| window.close_dialog(cx));
553 let remove = Button::new("remove-history-confirm")
554 .label("Remove")
555 .primary()
556 .on_click(move |_, window, cx| {
557 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
558 window.close_dialog(cx);
559 });
560 alert
561 .title(REMOVE_HISTORY_TITLE)
562 .description(REMOVE_HISTORY_TEXT)
563 .footer(DialogFooter::new().child(cancel).child(remove))
564 .on_ok(|_, _, _| false)
565 });
566}
567
516pub(crate) fn confirm_leave(
568pub(crate) fn confirm_leave(
517 state: &Entity<AppState>,
569 state: &Entity<AppState>,
518 chat_id: &str,
570 chat_id: &str,
@@ -546,6 +598,12 @@ pub(crate) fn confirm_leave(
546 });
598 });
547}
599}
548
600
601pub enum SidebarEvent {
602 RestoreFocus,
603}
604
605impl EventEmitter<SidebarEvent> for SidebarView {}
606
549pub struct SidebarView {
607pub struct SidebarView {
550 state: Entity<AppState>,
608 state: Entity<AppState>,
551 tab: SidebarTab,
609 tab: SidebarTab,
@@ -560,6 +618,12 @@ pub struct SidebarView {
560 older_chats_seen: Cell<(bool, bool)>,
618 older_chats_seen: Cell<(bool, bool)>,
561 channels_scroll: ScrollHandle,
619 channels_scroll: ScrollHandle,
562 calls_scroll: ScrollHandle,
620 calls_scroll: ScrollHandle,
621 chat_filter: ChatFilter,
622 filter_box_open: bool,
623 more_filters_open: bool,
624 filter_input: Option<Entity<InputState>>,
625 filter_subscription: Option<Subscription>,
626 _activity_observation: Subscription,
563 _subscription: Subscription,
627 _subscription: Subscription,
564 _state_observation: Subscription,
628 _state_observation: Subscription,
565 _agent_observation: Option<Subscription>,
629 _agent_observation: Option<Subscription>,
@@ -650,6 +714,15 @@ impl SidebarView {
650 SidebarTab::Chats
714 SidebarTab::Chats
651 };
715 };
652 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
716 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
717 let activity = activity_panel.read(cx).activity();
718 let activity_observation = cx.observe(&activity, |view, _, cx| {
719 if view
720 .chat_filter
721 .has(crate::chat_filter::ChatFilterPill::Mentions)
722 {
723 cx.notify();
724 }
725 });
653 cx.spawn(async move |this, cx| {
726 cx.spawn(async move |this, cx| {
654 loop {
727 loop {
655 cx.background_executor().timer(CALLS_REFRESH).await;
728 cx.background_executor().timer(CALLS_REFRESH).await;
@@ -678,6 +751,12 @@ impl SidebarView {
678 older_chats_seen: Cell::new((false, false)),
751 older_chats_seen: Cell::new((false, false)),
679 channels_scroll: ScrollHandle::new(),
752 channels_scroll: ScrollHandle::new(),
680 calls_scroll: ScrollHandle::new(),
753 calls_scroll: ScrollHandle::new(),
754 chat_filter: ChatFilter::default(),
755 filter_box_open: false,
756 more_filters_open: false,
757 filter_input: None,
758 filter_subscription: None,
759 _activity_observation: activity_observation,
681 _subscription: subscription,
760 _subscription: subscription,
682 _state_observation: state_observation,
761 _state_observation: state_observation,
683 _agent_observation: agent_observation,
762 _agent_observation: agent_observation,
@@ -1164,7 +1243,18 @@ impl SidebarView {
1164 now,
1243 now,
1165 offset,
1244 offset,
1166 };
1245 };
1167 let sections = build_sections(&input);
1246 let sections = if self.chat_filter.is_active() {
1247 let mentioned = self.mentioned_chats(cx);
1248 let selected_id = self.selected_chat_id(cx);
1249 filtered_sections(
1250 &input,
1251 &self.chat_filter,
1252 &mentioned,
1253 selected_id.as_deref(),
1254 )
1255 } else {
1256 build_sections(&input)
1257 };
1168 let menu = MenuContext {
1258 let menu = MenuContext {
1169 state: self.state.clone(),
1259 state: self.state.clone(),
1170 folders: state.directory.move_targets(),
1260 folders: state.directory.move_targets(),
@@ -1289,6 +1379,10 @@ impl SidebarView {
1289 .child(LOADING_OLDER_LABEL),
1379 .child(LOADING_OLDER_LABEL),
1290 );
1380 );
1291 }
1381 }
1382 let selected_chat_id = self.selected_chat_id(cx);
1383 if self.chat_filter.is_active() && has_no_matches(&sections, selected_chat_id.as_deref()) {
1384 list = list.child(self.filter_empty_state(cx));
1385 }
1292 list = with_spacer(list, &mut skipped_height);
1386 list = with_spacer(list, &mut skipped_height);
1293 self.request_lazy_data(faces, presence_users, cx);
1387 self.request_lazy_data(faces, presence_users, cx);
1294 let scroll_area = div()
1388 let scroll_area = div()
@@ -1445,6 +1539,8 @@ impl SidebarView {
1445 let name_style = team_name_style(entry, expanded);
1539 let name_style = team_name_style(entry, expanded);
1446 let badge = team_badge(entry, expanded);
1540 let badge = team_badge(entry, expanded);
1447 let toggle_id = team_id.clone();
1541 let toggle_id = team_id.clone();
1542 let (team_menu_state, team_menu_id, team_hidden) =
1543 (self.state.clone(), team_id.clone(), entry.hidden);
1448 list = list.child(
1544 list = list.child(
1449 h_flex()
1545 h_flex()
1450 .id(SharedString::from(format!("team-{team_id}")))
1546 .id(SharedString::from(format!("team-{team_id}")))
@@ -1484,7 +1580,10 @@ impl SidebarView {
1484 }
1580 }
1485 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1581 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1486 cx.notify();
1582 cx.notify();
1487 })),
1583 }))
1584 .context_menu(move |popup, _, _| {
1585 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1586 }),
1488 );
1587 );
1489 if !expanded {
1588 if !expanded {
1490 return list;
1589 return list;
@@ -1759,7 +1858,87 @@ fn channel_menu(
1759 channel_id: &str,
1858 channel_id: &str,
1760 notifications: ChannelNotifications,
1859 notifications: ChannelNotifications,
1761) -> PopupMenu {
1860) -> PopupMenu {
1762 let channel_id = channel_id.to_owned();
1861 let menu_state = state.read(cx).channel_menu_state(channel_id);
1862 let mut popup = popup;
1863 for entry in channel_menu_entries(menu_state) {
1864 let item = match entry {
1865 MenuEntry::Separator => {
1866 popup = popup.separator();
1867 continue;
1868 }
1869 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1870 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1871 continue;
1872 }
1873 MenuEntry::Item(item) => item,
1874 };
1875 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1876 popup = popup.item(
1877 PopupMenuItem::new(item.label())
1878 .icon(menu_icon(channel_menu_icon(item)))
1879 .disabled(menu_state.disables(item))
1880 .on_click(move |_, _, cx| {
1881 action_state.update(cx, |state, cx| match item {
1882 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1883 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1884 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1885 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1886 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1887 ChannelMenuItem::Notifications => {}
1888 });
1889 }),
1890 );
1891 }
1892 popup
1893}
1894
1895fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1896 match item {
1897 ChannelMenuItem::Notifications => IconName::Bell,
1898 ChannelMenuItem::Pin => IconName::Pin,
1899 ChannelMenuItem::Unpin => IconName::PinOff,
1900 ChannelMenuItem::Show => IconName::Eye,
1901 ChannelMenuItem::Hide => IconName::EyeOff,
1902 ChannelMenuItem::CopyLink => IconName::Link,
1903 }
1904}
1905
1906fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1907 let mut popup = popup;
1908 for entry in team_menu_entries(hidden) {
1909 let MenuEntry::Item(item) = entry else {
1910 popup = popup.separator();
1911 continue;
1912 };
1913 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1914 popup = popup.item(
1915 PopupMenuItem::new(item.label())
1916 .icon(menu_icon(match item {
1917 TeamMenuItem::Show => IconName::Eye,
1918 TeamMenuItem::Hide => IconName::EyeOff,
1919 TeamMenuItem::CopyLink => IconName::Link,
1920 }))
1921 .on_click(move |_, _, cx| {
1922 action_state.update(cx, |state, cx| match item {
1923 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1924 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1925 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1926 });
1927 }),
1928 );
1929 }
1930 popup
1931}
1932
1933fn notifications_submenu(
1934 popup: PopupMenu,
1935 window: &mut Window,
1936 cx: &mut Context<PopupMenu>,
1937 state: &Entity<AppState>,
1938 channel_id: &str,
1939 notifications: ChannelNotifications,
1940) -> PopupMenu {
1941 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1763 popup.submenu_with_icon(
1942 popup.submenu_with_icon(
1764 Some(menu_icon(IconName::Bell)),
1943 Some(menu_icon(IconName::Bell)),
1765 "Notifications",
1944 "Notifications",
@@ -1889,9 +2068,15 @@ impl Render for SidebarView {
1889 };
2068 };
1890 let header = match self.tab {
2069 let header = match self.tab {
1891 SidebarTab::Chats => Some(
2070 SidebarTab::Chats => Some(
1892 page_header(self.tab.title())
2071 v_flex()
1893 .child(self.chat_list_menu_button(cx))
2072 .flex_none()
1894 .child(self.new_chat_button(cx)),
2073 .child(
2074 page_header(self.tab.title())
2075 .child(self.chat_list_menu_button(cx))
2076 .child(self.filter_toggle_button(cx))
2077 .child(self.new_chat_button(cx)),
2078 )
2079 .child(self.filter_bar(cx)),
1895 ),
2080 ),
1896 SidebarTab::Channels => {
2081 SidebarTab::Channels => {
1897 Some(page_header(self.tab.title()).child(self.channel_list_menu_button(cx)))
2082 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/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/conversations.rs +85 −0
@@ -13,6 +13,7 @@ use crate::read_horizon::{self, ReadHorizon};
13 13 const PAGE_SIZE: usize = 200;
14 14 const MAX_PAGES: usize = 100;
15 15 const ALERTS_OFF: &str = "false";
16 const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
16 17
17 18 #[derive(Debug, Clone, PartialEq, Eq, Default)]
18 19 pub struct ConversationState {
@@ -20,6 +21,7 @@ pub struct ConversationState {
20 21 pub muted: bool,
21 22 pub hidden: Option<bool>,
22 23 pub read: ReadHorizon,
24 pub history_cleared_ms: Option<i64>,
23 25 pub notification_settings: Option<String>,
24 26 }
25 27
@@ -119,6 +121,19 @@ impl<T: MessageTransport> Conversations<T> {
119 121 Ok(write)
120 122 }
121 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
122 137 pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> {
123 138 let url = format!(
124 139 "{}/{}/properties?name={}",
@@ -153,6 +168,29 @@ impl<T: MessageTransport> Conversations<T> {
153 168 }
154 169 }
155 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
156 194 /// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread.
157 195 pub fn thread_url(region: &str, thread_id: &str) -> String {
158 196 format!(
@@ -206,6 +244,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
206 244 [chat_notifications::PROPERTY_NAME]
207 245 .as_str()
208 246 .map(str::to_owned),
247 history_cleared_ms: history_cleared_ms(conversation),
209 248 })
210 249 })
211 250 .collect())
@@ -421,6 +460,52 @@ mod tests {
421 460 assert!(states[0].read.is_unread("8:orgid:me"));
422 461 }
423 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
424 509 #[tokio::test]
425 510 async fn set_read_horizon_puts_the_consumption_horizon_property() {
426 511 let transport = canned(vec![(200, Value::Null)]);
@@ -13,6 +13,7 @@ use crate::read_horizon::{self, ReadHorizon};
13const PAGE_SIZE: usize = 200;
13const PAGE_SIZE: usize = 200;
14const MAX_PAGES: usize = 100;
14const MAX_PAGES: usize = 100;
15const ALERTS_OFF: &str = "false";
15const ALERTS_OFF: &str = "false";
16const CLEAR_HISTORY_PROPERTY: &str = "clearHistoryTime";
16
17
17#[derive(Debug, Clone, PartialEq, Eq, Default)]
18#[derive(Debug, Clone, PartialEq, Eq, Default)]
18pub struct ConversationState {
19pub struct ConversationState {
@@ -20,6 +21,7 @@ pub struct ConversationState {
20 pub muted: bool,
21 pub muted: bool,
21 pub hidden: Option<bool>,
22 pub hidden: Option<bool>,
22 pub read: ReadHorizon,
23 pub read: ReadHorizon,
24 pub history_cleared_ms: Option<i64>,
23 pub notification_settings: Option<String>,
25 pub notification_settings: Option<String>,
24}
26}
25
27
@@ -119,6 +121,19 @@ impl<T: MessageTransport> Conversations<T> {
119 Ok(write)
121 Ok(write)
120 }
122 }
121
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
122 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<()> {
123 let url = format!(
138 let url = format!(
124 "{}/{}/properties?name={}",
139 "{}/{}/properties?name={}",
@@ -153,6 +168,29 @@ impl<T: MessageTransport> Conversations<T> {
153 }
168 }
154}
169}
155
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
156/// 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.
157pub fn thread_url(region: &str, thread_id: &str) -> String {
195pub fn thread_url(region: &str, thread_id: &str) -> String {
158 format!(
196 format!(
@@ -206,6 +244,7 @@ fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> {
206 [chat_notifications::PROPERTY_NAME]
244 [chat_notifications::PROPERTY_NAME]
207 .as_str()
245 .as_str()
208 .map(str::to_owned),
246 .map(str::to_owned),
247 history_cleared_ms: history_cleared_ms(conversation),
209 })
248 })
210 })
249 })
211 .collect())
250 .collect())
@@ -421,6 +460,52 @@ mod tests {
421 assert!(states[0].read.is_unread("8:orgid:me"));
460 assert!(states[0].read.is_unread("8:orgid:me"));
422 }
461 }
423
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
424 #[tokio::test]
509 #[tokio::test]
425 async fn set_read_horizon_puts_the_consumption_horizon_property() {
510 async fn set_read_horizon_puts_the_consumption_horizon_property() {
426 let transport = canned(vec![(200, Value::Null)]);
511 let transport = canned(vec![(200, Value::Null)]);
crates/chatsvc/src/lib.rs +6 −1
@@ -6,6 +6,7 @@ pub mod cards;
6 6 pub mod channel_notifications;
7 7 pub mod chat_notifications;
8 8 pub mod chat_settings;
9 pub mod channel_visibility;
9 10 pub mod conversations;
10 11 pub mod drafts;
11 12 pub mod emotions;
@@ -53,6 +54,7 @@ pub use chat_settings::{
53 54 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
54 55 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
55 56 };
57 pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
56 58 pub use conversations::{ConversationState, Conversations};
57 59 pub use drafts::{ScheduledDraft, ScheduledDrafts};
58 60 pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -65,7 +67,10 @@ pub use language_settings::{
65 67 };
66 68 pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
67 69 pub use mask::mask_conversation_id;
68 pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
70 pub use members::{
71 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
72 TopicProblem, topic_problem,
73 };
69 74 pub use messages::{ConversationRef, Messages};
70 75 pub use pins::{
71 76 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
@@ -6,6 +6,7 @@ pub mod cards;
6pub mod channel_notifications;
6pub mod channel_notifications;
7pub mod chat_notifications;
7pub mod chat_notifications;
8pub mod chat_settings;
8pub mod chat_settings;
9pub mod channel_visibility;
9pub mod conversations;
10pub mod conversations;
10pub mod drafts;
11pub mod drafts;
11pub mod emotions;
12pub mod emotions;
@@ -53,6 +54,7 @@ pub use chat_settings::{
53 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
54 ChatSettingsDocument, EnterKeyBehavior, MeetingChatNotifications, MessageDensity,
54 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
55 NotificationAccountSettings, NotificationPreset, UpArrowBehavior,
55};
56};
57pub use channel_visibility::{ChannelKind, ChannelMembership, ChannelTarget, ChannelVisibility};
56pub use conversations::{ConversationState, Conversations};
58pub use conversations::{ConversationState, Conversations};
57pub use drafts::{ScheduledDraft, ScheduledDrafts};
59pub use drafts::{ScheduledDraft, ScheduledDrafts};
58pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
60pub use emotions::{EmotionReaction, MessageEmotions, parse_message_emotions, user_id_from_mri};
@@ -65,7 +67,10 @@ pub use language_settings::{
65};
67};
66pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
68pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
67pub use mask::mask_conversation_id;
69pub use mask::mask_conversation_id;
68pub use members::{HistoryShare, MAX_HISTORY_DAYS, ThreadMembers};
70pub use members::{
71 HistoryShare, INVALID_TOPIC_CHARACTER, MAX_HISTORY_DAYS, MAX_TOPIC_LENGTH, ThreadMembers,
72 TopicProblem, topic_problem,
73};
69pub use messages::{ConversationRef, Messages};
74pub use messages::{ConversationRef, Messages};
70pub use pins::{
75pub use pins::{
71 ChannelLayout, ChannelTab, Folder, FolderKind, Folders, PinnedChannels, PinnedChats,
76 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 +1 −0
@@ -63,6 +63,7 @@ mod tests {
63 63 ..ReadHorizon::default()
64 64 },
65 65 notification_settings: None,
66 history_cleared_ms: None,
66 67 }
67 68 }
68 69
@@ -63,6 +63,7 @@ mod tests {
63 ..ReadHorizon::default()
63 ..ReadHorizon::default()
64 },
64 },
65 notification_settings: None,
65 notification_settings: None,
66 history_cleared_ms: None,
66 }
67 }
67 }
68 }
68
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/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 +56 −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,
@@ -174,10 +193,47 @@ mod tests {
174 193 hidden,
175 194 read: chatsvc::ReadHorizon::default(),
176 195 notification_settings: None,
196 history_cleared_ms: None,
177 197 },
178 198 )])
179 199 }
180 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
181 237 fn hidden_after(text: &str) -> LocallyHidden {
182 238 let mut locally = LocallyHidden::default();
183 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,
@@ -174,10 +193,47 @@ mod tests {
174 hidden,
193 hidden,
175 read: chatsvc::ReadHorizon::default(),
194 read: chatsvc::ReadHorizon::default(),
176 notification_settings: None,
195 notification_settings: None,
196 history_cleared_ms: None,
177 },
197 },
178 )])
198 )])
179 }
199 }
180
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
181 fn hidden_after(text: &str) -> LocallyHidden {
237 fn hidden_after(text: &str) -> LocallyHidden {
182 let mut locally = LocallyHidden::default();
238 let mut locally = LocallyHidden::default();
183 locally.hide("19:a", at(text));
239 locally.hide("19:a", at(text));
crates/core/src/lib.rs +8 −1
@@ -14,7 +14,9 @@ mod card_width;
14 14 mod channel_mentions;
15 15 mod channel_sync;
16 16 mod chat_settings_sync;
17 mod channel_visibility;
17 18 mod chat_paging;
19 mod default_reactions;
18 20 mod download;
19 21 mod draft;
20 22 mod emoticon_tags;
@@ -114,6 +116,10 @@ pub use chatsvc::{
114 116 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
115 117 parse_language_settings, target_patch,
116 118 };
119 pub use default_reactions::{
120 DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
121 store_account_default_reactions,
122 };
117 123 pub use download::LibraryFile;
118 124 pub use draft::{
119 125 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -147,7 +153,8 @@ pub use meeting_join::{
147 153 };
148 154 pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
149 155 pub use message_link::{
150 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,
151 158 };
152 159 pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
153 160 pub use notes_chat::{is_notes_chat, notes_chat_title};
@@ -14,7 +14,9 @@ mod card_width;
14mod channel_mentions;
14mod channel_mentions;
15mod channel_sync;
15mod channel_sync;
16mod chat_settings_sync;
16mod chat_settings_sync;
17mod channel_visibility;
17mod chat_paging;
18mod chat_paging;
19mod default_reactions;
18mod download;
20mod download;
19mod draft;
21mod draft;
20mod emoticon_tags;
22mod emoticon_tags;
@@ -114,6 +116,10 @@ pub use chatsvc::{
114 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
116 TranslationStatus, TranslationTrigger, authoring_patch, behavior_patch, language_code,
115 parse_language_settings, target_patch,
117 parse_language_settings, target_patch,
116};
118};
119pub use default_reactions::{
120 DEFAULT_REACTION_SLOTS, TEAMS_DEFAULT_REACTIONS, default_reactions,
121 store_account_default_reactions,
122};
117pub use download::LibraryFile;
123pub use download::LibraryFile;
118pub use draft::{
124pub use draft::{
119 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
125 Draft, DraftLine, Edit, FormatState, LineKind, MAX_DEPTH, Mark, MarkKind, OBJECT_MARK,
@@ -147,7 +153,8 @@ pub use meeting_join::{
147};
153};
148pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
154pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
149pub use message_link::{
155pub use message_link::{
150 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,
151};
158};
152pub 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};
153pub 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 +1 −0
@@ -117,6 +117,7 @@ mod tests {
117 117 ..ReadHorizon::default()
118 118 },
119 119 notification_settings: None,
120 history_cleared_ms: None,
120 121 }
121 122 }
122 123
@@ -117,6 +117,7 @@ mod tests {
117 ..ReadHorizon::default()
117 ..ReadHorizon::default()
118 },
118 },
119 notification_settings: None,
119 notification_settings: None,
120 history_cleared_ms: None,
120 }
121 }
121 }
122 }
122
123
crates/core/src/remote.rs +18 −0
@@ -139,6 +139,12 @@ pub trait Remote {
139 139 share: HistoryShare,
140 140 ) -> Result<()>;
141 141 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
142 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
143 Err(Error::Unsupported("removing chat history"))
144 }
145 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
146 Err(Error::Unsupported("renaming a chat"))
147 }
142 148 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
143 149 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
144 150 async fn set_channel_notifications(
@@ -753,6 +759,18 @@ impl Remote for Graph {
753 759 .await?)
754 760 }
755 761
762 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
763 Ok(Conversations::new(self.session())
764 .clear_history(chat_id, cleared_until_ms)
765 .await?)
766 }
767
768 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
769 Ok(ThreadMembers::new(self.session())
770 .set_topic(chat_id, topic)
771 .await?)
772 }
773
756 774 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
757 775 Ok(Conversations::new(self.session())
758 776 .set_alerts(chat_id, !muted)
@@ -139,6 +139,12 @@ pub trait Remote {
139 share: HistoryShare,
139 share: HistoryShare,
140 ) -> Result<()>;
140 ) -> Result<()>;
141 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
141 async fn chat_states(&self) -> Result<Vec<ConversationState>>;
142 async fn clear_chat_history(&self, _chat_id: &str, _cleared_until_ms: i64) -> Result<()> {
143 Err(Error::Unsupported("removing chat history"))
144 }
145 async fn set_chat_topic(&self, _chat_id: &str, _topic: &str) -> Result<()> {
146 Err(Error::Unsupported("renaming a chat"))
147 }
142 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()>;
148 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<()>;
149 async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()>;
144 async fn set_channel_notifications(
150 async fn set_channel_notifications(
@@ -753,6 +759,18 @@ impl Remote for Graph {
753 .await?)
759 .await?)
754 }
760 }
755
761
762 async fn clear_chat_history(&self, chat_id: &str, cleared_until_ms: i64) -> Result<()> {
763 Ok(Conversations::new(self.session())
764 .clear_history(chat_id, cleared_until_ms)
765 .await?)
766 }
767
768 async fn set_chat_topic(&self, chat_id: &str, topic: &str) -> Result<()> {
769 Ok(ThreadMembers::new(self.session())
770 .set_topic(chat_id, topic)
771 .await?)
772 }
773
756 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
774 async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> {
757 Ok(Conversations::new(self.session())
775 Ok(Conversations::new(self.session())
758 .set_alerts(chat_id, !muted)
776 .set_alerts(chat_id, !muted)
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 +134 −0
@@ -585,6 +585,7 @@ impl Remote for Handle {
585 585 hidden: None,
586 586 read: chatsvc::ReadHorizon::default(),
587 587 notification_settings: None,
588 history_cleared_ms: None,
588 589 })
589 590 .collect();
590 591 states.extend(
@@ -596,6 +597,7 @@ impl Remote for Handle {
596 597 hidden: Some(hidden),
597 598 read: chatsvc::ReadHorizon::default(),
598 599 notification_settings: None,
600 history_cleared_ms: None,
599 601 }),
600 602 );
601 603 let read = self.read_states.lock().unwrap().clone();
@@ -607,6 +609,7 @@ impl Remote for Handle {
607 609 hidden: None,
608 610 read,
609 611 notification_settings: None,
612 history_cleared_ms: None,
610 613 }),
611 614 );
612 615 Ok(states)
@@ -3209,6 +3212,137 @@ impl FolderSource for FakeFolders {
3209 3212 Ok(state.clone())
3210 3213 })
3211 3214 }
3215
3216 fn set_channel_pinned<'a>(
3217 &'a self,
3218 channel_id: &'a str,
3219 pinned: bool,
3220 ) -> BoxFuture<'a, Result<Vec<String>>> {
3221 Box::pin(async move {
3222 self.calls
3223 .lock()
3224 .unwrap()
3225 .push(format!("pin channel {channel_id} {pinned}"));
3226 let mut channel_ids = self.channels.clone();
3227 channel_ids.retain(|id| id != channel_id);
3228 if pinned {
3229 channel_ids.push(channel_id.to_owned());
3230 }
3231 Ok(channel_ids)
3232 })
3233 }
3234
3235 fn set_channel_shown<'a>(
3236 &'a self,
3237 target: chatsvc::ChannelTarget<'a>,
3238 own_user_id: &'a str,
3239 shown: bool,
3240 _now_ms: i64,
3241 ) -> BoxFuture<'a, Result<()>> {
3242 Box::pin(async move {
3243 self.calls.lock().unwrap().push(format!(
3244 "show channel {} general={} {:?} {own_user_id} {shown}",
3245 target.channel_id, target.general, target.kind
3246 ));
3247 Ok(())
3248 })
3249 }
3250
3251 fn set_team_shown<'a>(
3252 &'a self,
3253 team_thread_id: &'a str,
3254 shown: bool,
3255 ) -> BoxFuture<'a, Result<()>> {
3256 Box::pin(async move {
3257 self.calls
3258 .lock()
3259 .unwrap()
3260 .push(format!("show team {team_thread_id} {shown}"));
3261 Ok(())
3262 })
3263 }
3264 }
3265
3266 fn store_alpha_team(engine: &SyncEngine<Handle>) {
3267 engine
3268 .store()
3269 .upsert_teams(&[TeamRecord {
3270 id: "alpha".into(),
3271 name: "Alpha".into(),
3272 }])
3273 .unwrap();
3274 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3275 id: id.into(),
3276 team_id: "alpha".into(),
3277 name: name.into(),
3278 membership_type: membership_type.map(str::to_owned),
3279 last_message_at: None,
3280 unread: false,
3281 };
3282 engine
3283 .store()
3284 .upsert_channels(&[
3285 channel("19:general@thread.tacv2", "General", Some("standard")),
3286 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3287 ])
3288 .unwrap();
3289 }
3290
3291 #[tokio::test]
3292 async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3293 let fake = Arc::new(Fake::default());
3294 let source = FakeFolders::new();
3295 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3296 store_alpha_team(&engine);
3297 let mut events = engine.subscribe();
3298
3299 engine.set_channel_pinned("ch3", true).await.unwrap();
3300 assert_eq!(
3301 engine.pinned_channels().unwrap(),
3302 ids(&["ch1", "ch2", "ch3"])
3303 );
3304 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3305 engine.set_channel_pinned("ch1", false).await.unwrap();
3306 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3307
3308 engine
3309 .set_channel_shown("19:secret@thread.tacv2", false)
3310 .await
3311 .unwrap();
3312 engine
3313 .set_channel_shown("19:general@thread.tacv2", false)
3314 .await
3315 .unwrap();
3316 engine.set_team_shown("alpha", false).await.unwrap();
3317 let team = engine.store().sidebar().unwrap().teams.remove(0);
3318 assert!(team.hidden);
3319 assert_eq!(team.hidden_channel_ids.len(), 2);
3320 let calls = source.calls.lock().unwrap().clone();
3321 assert_eq!(
3322 calls[2..],
3323 [
3324 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3325 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3326 "show team 19:general@thread.tacv2 false".to_owned(),
3327 ]
3328 );
3329 }
3330
3331 #[tokio::test]
3332 async fn channel_and_team_links_use_the_cached_tenant() {
3333 let fake = Arc::new(Fake::default());
3334 let engine = engine_with(&fake, SyncConfig::default());
3335 store_alpha_team(&engine);
3336 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3337
3338 assert_eq!(
3339 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3340 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3341 );
3342 assert_eq!(
3343 engine.team_link("alpha").await.unwrap(),
3344 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3345 );
3212 3346 }
3213 3347
3214 3348 #[tokio::test]
@@ -585,6 +585,7 @@ impl Remote for Handle {
585 hidden: None,
585 hidden: None,
586 read: chatsvc::ReadHorizon::default(),
586 read: chatsvc::ReadHorizon::default(),
587 notification_settings: None,
587 notification_settings: None,
588 history_cleared_ms: None,
588 })
589 })
589 .collect();
590 .collect();
590 states.extend(
591 states.extend(
@@ -596,6 +597,7 @@ impl Remote for Handle {
596 hidden: Some(hidden),
597 hidden: Some(hidden),
597 read: chatsvc::ReadHorizon::default(),
598 read: chatsvc::ReadHorizon::default(),
598 notification_settings: None,
599 notification_settings: None,
600 history_cleared_ms: None,
599 }),
601 }),
600 );
602 );
601 let read = self.read_states.lock().unwrap().clone();
603 let read = self.read_states.lock().unwrap().clone();
@@ -607,6 +609,7 @@ impl Remote for Handle {
607 hidden: None,
609 hidden: None,
608 read,
610 read,
609 notification_settings: None,
611 notification_settings: None,
612 history_cleared_ms: None,
610 }),
613 }),
611 );
614 );
612 Ok(states)
615 Ok(states)
@@ -3209,6 +3212,137 @@ impl FolderSource for FakeFolders {
3209 Ok(state.clone())
3212 Ok(state.clone())
3210 })
3213 })
3211 }
3214 }
3215
3216 fn set_channel_pinned<'a>(
3217 &'a self,
3218 channel_id: &'a str,
3219 pinned: bool,
3220 ) -> BoxFuture<'a, Result<Vec<String>>> {
3221 Box::pin(async move {
3222 self.calls
3223 .lock()
3224 .unwrap()
3225 .push(format!("pin channel {channel_id} {pinned}"));
3226 let mut channel_ids = self.channels.clone();
3227 channel_ids.retain(|id| id != channel_id);
3228 if pinned {
3229 channel_ids.push(channel_id.to_owned());
3230 }
3231 Ok(channel_ids)
3232 })
3233 }
3234
3235 fn set_channel_shown<'a>(
3236 &'a self,
3237 target: chatsvc::ChannelTarget<'a>,
3238 own_user_id: &'a str,
3239 shown: bool,
3240 _now_ms: i64,
3241 ) -> BoxFuture<'a, Result<()>> {
3242 Box::pin(async move {
3243 self.calls.lock().unwrap().push(format!(
3244 "show channel {} general={} {:?} {own_user_id} {shown}",
3245 target.channel_id, target.general, target.kind
3246 ));
3247 Ok(())
3248 })
3249 }
3250
3251 fn set_team_shown<'a>(
3252 &'a self,
3253 team_thread_id: &'a str,
3254 shown: bool,
3255 ) -> BoxFuture<'a, Result<()>> {
3256 Box::pin(async move {
3257 self.calls
3258 .lock()
3259 .unwrap()
3260 .push(format!("show team {team_thread_id} {shown}"));
3261 Ok(())
3262 })
3263 }
3264}
3265
3266fn store_alpha_team(engine: &SyncEngine<Handle>) {
3267 engine
3268 .store()
3269 .upsert_teams(&[TeamRecord {
3270 id: "alpha".into(),
3271 name: "Alpha".into(),
3272 }])
3273 .unwrap();
3274 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3275 id: id.into(),
3276 team_id: "alpha".into(),
3277 name: name.into(),
3278 membership_type: membership_type.map(str::to_owned),
3279 last_message_at: None,
3280 unread: false,
3281 };
3282 engine
3283 .store()
3284 .upsert_channels(&[
3285 channel("19:general@thread.tacv2", "General", Some("standard")),
3286 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3287 ])
3288 .unwrap();
3289}
3290
3291#[tokio::test]
3292async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3293 let fake = Arc::new(Fake::default());
3294 let source = FakeFolders::new();
3295 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3296 store_alpha_team(&engine);
3297 let mut events = engine.subscribe();
3298
3299 engine.set_channel_pinned("ch3", true).await.unwrap();
3300 assert_eq!(
3301 engine.pinned_channels().unwrap(),
3302 ids(&["ch1", "ch2", "ch3"])
3303 );
3304 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3305 engine.set_channel_pinned("ch1", false).await.unwrap();
3306 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3307
3308 engine
3309 .set_channel_shown("19:secret@thread.tacv2", false)
3310 .await
3311 .unwrap();
3312 engine
3313 .set_channel_shown("19:general@thread.tacv2", false)
3314 .await
3315 .unwrap();
3316 engine.set_team_shown("alpha", false).await.unwrap();
3317 let team = engine.store().sidebar().unwrap().teams.remove(0);
3318 assert!(team.hidden);
3319 assert_eq!(team.hidden_channel_ids.len(), 2);
3320 let calls = source.calls.lock().unwrap().clone();
3321 assert_eq!(
3322 calls[2..],
3323 [
3324 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3325 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3326 "show team 19:general@thread.tacv2 false".to_owned(),
3327 ]
3328 );
3329}
3330
3331#[tokio::test]
3332async fn channel_and_team_links_use_the_cached_tenant() {
3333 let fake = Arc::new(Fake::default());
3334 let engine = engine_with(&fake, SyncConfig::default());
3335 store_alpha_team(&engine);
3336 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3337
3338 assert_eq!(
3339 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3340 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3341 );
3342 assert_eq!(
3343 engine.team_link("alpha").await.unwrap(),
3344 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3345 );
3212}
3346}
3213
3347
3214#[tokio::test]
3348#[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
@@ -1630,3 +1630,44 @@ fn setting_read_horizons_replaces_the_conversation_only() {
1630 1630 assert_eq!(store.read_horizons("c").unwrap(), second);
1631 1631 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1632 1632 }
1633
1634 #[test]
1635 fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1636 let store = Store::open_in_memory().unwrap();
1637 store
1638 .upsert_teams(&[TeamRecord {
1639 id: "t1".to_owned(),
1640 name: "Alpha".to_owned(),
1641 }])
1642 .unwrap();
1643 let channel = |id: &str, name: &str| ChannelRecord {
1644 id: id.to_owned(),
1645 team_id: "t1".to_owned(),
1646 name: name.to_owned(),
1647 membership_type: None,
1648 last_message_at: None,
1649 unread: false,
1650 };
1651 store
1652 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1653 .unwrap();
1654 let team = || store.sidebar().unwrap().teams.remove(0);
1655
1656 store.set_channel_hidden("c2", true).unwrap();
1657 store.set_team_hidden("t1", true).unwrap();
1658 let hidden = team();
1659 assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1660 assert!(hidden.hidden);
1661 assert_eq!(hidden.channels[0].name, "General");
1662
1663 store.set_channel_hidden("c2", false).unwrap();
1664 store.set_team_hidden("t1", false).unwrap();
1665 let shown = team();
1666 assert!(shown.hidden_channel_ids.is_empty());
1667 assert!(!shown.hidden);
1668
1669 store
1670 .replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1671 .unwrap();
1672 assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1673 }
@@ -1630,3 +1630,44 @@ fn setting_read_horizons_replaces_the_conversation_only() {
1630 assert_eq!(store.read_horizons("c").unwrap(), second);
1630 assert_eq!(store.read_horizons("c").unwrap(), second);
1631 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1631 assert_eq!(store.read_horizons("other").unwrap().len(), 1);
1632}
1632}
1633
1634#[test]
1635fn local_show_hide_and_channel_pin_writes_reach_the_sidebar() {
1636 let store = Store::open_in_memory().unwrap();
1637 store
1638 .upsert_teams(&[TeamRecord {
1639 id: "t1".to_owned(),
1640 name: "Alpha".to_owned(),
1641 }])
1642 .unwrap();
1643 let channel = |id: &str, name: &str| ChannelRecord {
1644 id: id.to_owned(),
1645 team_id: "t1".to_owned(),
1646 name: name.to_owned(),
1647 membership_type: None,
1648 last_message_at: None,
1649 unread: false,
1650 };
1651 store
1652 .upsert_channels(&[channel("c1", "General"), channel("c2", "Random")])
1653 .unwrap();
1654 let team = || store.sidebar().unwrap().teams.remove(0);
1655
1656 store.set_channel_hidden("c2", true).unwrap();
1657 store.set_team_hidden("t1", true).unwrap();
1658 let hidden = team();
1659 assert_eq!(hidden.hidden_channel_ids, vec!["c2".to_owned()]);
1660 assert!(hidden.hidden);
1661 assert_eq!(hidden.channels[0].name, "General");
1662
1663 store.set_channel_hidden("c2", false).unwrap();
1664 store.set_team_hidden("t1", false).unwrap();
1665 let shown = team();
1666 assert!(shown.hidden_channel_ids.is_empty());
1667 assert!(!shown.hidden);
1668
1669 store
1670 .replace_pinned_channels(&["c2".to_owned(), "c1".to_owned()])
1671 .unwrap();
1672 assert_eq!(store.pinned_channel_ids().unwrap(), vec!["c2", "c1"]);
1673}