BlueGit

ict rusty-teams

feat(channels): channel and team menu with pin, show/hide and copy link

- channel menu: Notifications, Pin/Unpin, Show/Hide, Copy link; Hide disabled while pinned
- team row menu: Show/Hide, Copy link
- links in Teams' format on teams.cloud.microsoft, ngc for private and shared, toast "Copied to clipboard"
- pin via CSA pinnedChannels, show/hide via chatsvc favorite/isfollowed/membership writes
- optimistic store updates with revert and Teams' error strings, demo mode local only
- tests: link builders, menu model, store setters, engine wiring

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-17 · 6 weeks ago

Hash
9ee3d02fc6575e2080c10d142bb363c608fea1b9
Parent
9cc5dfa7
12 files changed +984 −7
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/demo.rs +1 −0
@@ -1414,6 +1414,7 @@ fn settings_card() -> serde_json::Value {
1414 1414 })
1415 1415 }
1416 1416
1417 pub const DEMO_TENANT_ID: &str = "demo-tenant";
1417 1418 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 1419
1419 1420 fn meeting_link_messages() -> Vec<MessageRecord> {
@@ -1414,6 +1414,7 @@ fn settings_card() -> serde_json::Value {
1414 })
1414 })
1415}
1415}
1416
1416
1417pub 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";
1418const 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
1419
1419fn meeting_link_messages() -> Vec<MessageRecord> {
1420fn meeting_link_messages() -> Vec<MessageRecord> {
crates/app-state/src/lib.rs +1 −0
@@ -9,6 +9,7 @@ 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;
13 14 pub mod chat_members;
14 15 pub mod connection_banner;
@@ -9,6 +9,7 @@ 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;
13pub mod chat_members;
14pub mod chat_members;
14pub mod connection_banner;
15pub mod connection_banner;
crates/app/src/views/sidebar.rs +90 −2
@@ -24,6 +24,9 @@ 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;
28 31 use crate::data::{Directory, is_pending_folder};
29 32 use crate::format;
@@ -1375,6 +1378,8 @@ impl SidebarView {
1375 1378 let name_style = team_name_style(entry, expanded);
1376 1379 let badge = team_badge(entry, expanded);
1377 1380 let toggle_id = team_id.clone();
1381 let (team_menu_state, team_menu_id, team_hidden) =
1382 (self.state.clone(), team_id.clone(), entry.hidden);
1378 1383 list = list.child(
1379 1384 h_flex()
1380 1385 .id(SharedString::from(format!("team-{team_id}")))
@@ -1414,7 +1419,10 @@ impl SidebarView {
1414 1419 }
1415 1420 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1416 1421 cx.notify();
1417 })),
1422 }))
1423 .context_menu(move |popup, _, _| {
1424 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1425 }),
1418 1426 );
1419 1427 if !expanded {
1420 1428 return list;
@@ -1689,7 +1697,87 @@ fn channel_menu(
1689 1697 channel_id: &str,
1690 1698 notifications: ChannelNotifications,
1691 1699 ) -> PopupMenu {
1692 let channel_id = channel_id.to_owned();
1700 let menu_state = state.read(cx).channel_menu_state(channel_id);
1701 let mut popup = popup;
1702 for entry in channel_menu_entries(menu_state) {
1703 let item = match entry {
1704 MenuEntry::Separator => {
1705 popup = popup.separator();
1706 continue;
1707 }
1708 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1709 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1710 continue;
1711 }
1712 MenuEntry::Item(item) => item,
1713 };
1714 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1715 popup = popup.item(
1716 PopupMenuItem::new(item.label())
1717 .icon(menu_icon(channel_menu_icon(item)))
1718 .disabled(menu_state.disables(item))
1719 .on_click(move |_, _, cx| {
1720 action_state.update(cx, |state, cx| match item {
1721 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1722 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1723 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1724 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1725 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1726 ChannelMenuItem::Notifications => {}
1727 });
1728 }),
1729 );
1730 }
1731 popup
1732 }
1733
1734 fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1735 match item {
1736 ChannelMenuItem::Notifications => IconName::Bell,
1737 ChannelMenuItem::Pin => IconName::Pin,
1738 ChannelMenuItem::Unpin => IconName::PinOff,
1739 ChannelMenuItem::Show => IconName::Eye,
1740 ChannelMenuItem::Hide => IconName::EyeOff,
1741 ChannelMenuItem::CopyLink => IconName::Link,
1742 }
1743 }
1744
1745 fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1746 let mut popup = popup;
1747 for entry in team_menu_entries(hidden) {
1748 let MenuEntry::Item(item) = entry else {
1749 popup = popup.separator();
1750 continue;
1751 };
1752 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1753 popup = popup.item(
1754 PopupMenuItem::new(item.label())
1755 .icon(menu_icon(match item {
1756 TeamMenuItem::Show => IconName::Eye,
1757 TeamMenuItem::Hide => IconName::EyeOff,
1758 TeamMenuItem::CopyLink => IconName::Link,
1759 }))
1760 .on_click(move |_, _, cx| {
1761 action_state.update(cx, |state, cx| match item {
1762 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1763 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1764 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1765 });
1766 }),
1767 );
1768 }
1769 popup
1770 }
1771
1772 fn notifications_submenu(
1773 popup: PopupMenu,
1774 window: &mut Window,
1775 cx: &mut Context<PopupMenu>,
1776 state: &Entity<AppState>,
1777 channel_id: &str,
1778 notifications: ChannelNotifications,
1779 ) -> PopupMenu {
1780 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1693 1781 popup.submenu_with_icon(
1694 1782 Some(menu_icon(IconName::Bell)),
1695 1783 "Notifications",
@@ -24,6 +24,9 @@ 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;
28use crate::data::{Directory, is_pending_folder};
31use crate::data::{Directory, is_pending_folder};
29use crate::format;
32use crate::format;
@@ -1375,6 +1378,8 @@ impl SidebarView {
1375 let name_style = team_name_style(entry, expanded);
1378 let name_style = team_name_style(entry, expanded);
1376 let badge = team_badge(entry, expanded);
1379 let badge = team_badge(entry, expanded);
1377 let toggle_id = team_id.clone();
1380 let toggle_id = team_id.clone();
1381 let (team_menu_state, team_menu_id, team_hidden) =
1382 (self.state.clone(), team_id.clone(), entry.hidden);
1378 list = list.child(
1383 list = list.child(
1379 h_flex()
1384 h_flex()
1380 .id(SharedString::from(format!("team-{team_id}")))
1385 .id(SharedString::from(format!("team-{team_id}")))
@@ -1414,7 +1419,10 @@ impl SidebarView {
1414 }
1419 }
1415 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1420 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1416 cx.notify();
1421 cx.notify();
1417 })),
1422 }))
1423 .context_menu(move |popup, _, _| {
1424 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_hidden)
1425 }),
1418 );
1426 );
1419 if !expanded {
1427 if !expanded {
1420 return list;
1428 return list;
@@ -1689,7 +1697,87 @@ fn channel_menu(
1689 channel_id: &str,
1697 channel_id: &str,
1690 notifications: ChannelNotifications,
1698 notifications: ChannelNotifications,
1691) -> PopupMenu {
1699) -> PopupMenu {
1692 let channel_id = channel_id.to_owned();
1700 let menu_state = state.read(cx).channel_menu_state(channel_id);
1701 let mut popup = popup;
1702 for entry in channel_menu_entries(menu_state) {
1703 let item = match entry {
1704 MenuEntry::Separator => {
1705 popup = popup.separator();
1706 continue;
1707 }
1708 MenuEntry::Item(ChannelMenuItem::Notifications) => {
1709 popup = notifications_submenu(popup, window, cx, &state, channel_id, notifications);
1710 continue;
1711 }
1712 MenuEntry::Item(item) => item,
1713 };
1714 let (action_state, action_id) = (state.clone(), channel_id.to_owned());
1715 popup = popup.item(
1716 PopupMenuItem::new(item.label())
1717 .icon(menu_icon(channel_menu_icon(item)))
1718 .disabled(menu_state.disables(item))
1719 .on_click(move |_, _, cx| {
1720 action_state.update(cx, |state, cx| match item {
1721 ChannelMenuItem::Pin => state.set_channel_pinned(&action_id, true, cx),
1722 ChannelMenuItem::Unpin => state.set_channel_pinned(&action_id, false, cx),
1723 ChannelMenuItem::Show => state.set_channel_shown(&action_id, true, cx),
1724 ChannelMenuItem::Hide => state.set_channel_shown(&action_id, false, cx),
1725 ChannelMenuItem::CopyLink => state.copy_channel_link(&action_id, cx),
1726 ChannelMenuItem::Notifications => {}
1727 });
1728 }),
1729 );
1730 }
1731 popup
1732}
1733
1734fn channel_menu_icon(item: ChannelMenuItem) -> IconName {
1735 match item {
1736 ChannelMenuItem::Notifications => IconName::Bell,
1737 ChannelMenuItem::Pin => IconName::Pin,
1738 ChannelMenuItem::Unpin => IconName::PinOff,
1739 ChannelMenuItem::Show => IconName::Eye,
1740 ChannelMenuItem::Hide => IconName::EyeOff,
1741 ChannelMenuItem::CopyLink => IconName::Link,
1742 }
1743}
1744
1745fn team_menu(popup: PopupMenu, state: Entity<AppState>, team_id: &str, hidden: bool) -> PopupMenu {
1746 let mut popup = popup;
1747 for entry in team_menu_entries(hidden) {
1748 let MenuEntry::Item(item) = entry else {
1749 popup = popup.separator();
1750 continue;
1751 };
1752 let (action_state, action_id) = (state.clone(), team_id.to_owned());
1753 popup = popup.item(
1754 PopupMenuItem::new(item.label())
1755 .icon(menu_icon(match item {
1756 TeamMenuItem::Show => IconName::Eye,
1757 TeamMenuItem::Hide => IconName::EyeOff,
1758 TeamMenuItem::CopyLink => IconName::Link,
1759 }))
1760 .on_click(move |_, _, cx| {
1761 action_state.update(cx, |state, cx| match item {
1762 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1763 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1764 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1765 });
1766 }),
1767 );
1768 }
1769 popup
1770}
1771
1772fn notifications_submenu(
1773 popup: PopupMenu,
1774 window: &mut Window,
1775 cx: &mut Context<PopupMenu>,
1776 state: &Entity<AppState>,
1777 channel_id: &str,
1778 notifications: ChannelNotifications,
1779) -> PopupMenu {
1780 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1693 popup.submenu_with_icon(
1781 popup.submenu_with_icon(
1694 Some(menu_icon(IconName::Bell)),
1782 Some(menu_icon(IconName::Bell)),
1695 "Notifications",
1783 "Notifications",
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/folders.rs +77 −4
@@ -5,8 +5,9 @@ use std::sync::{Arc, Mutex};
5 5
6 6 use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
7 7 use chatsvc::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
9 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
9 ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
10 pins::SessionTransport,
10 11 };
11 12 use chrono::Utc;
12 13 use serde_json::Value;
@@ -89,10 +90,34 @@ pub trait FolderSource: Send + Sync {
89 90 folder_id: &'a str,
90 91 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91 92 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
93 fn set_channel_pinned<'a>(
94 &'a self,
95 _channel_id: &'a str,
96 _pinned: bool,
97 ) -> BoxFuture<'a, Result<Vec<String>>> {
98 Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })
99 }
100 fn set_channel_shown<'a>(
101 &'a self,
102 _target: ChannelTarget<'a>,
103 _own_user_id: &'a str,
104 _shown: bool,
105 _now_ms: i64,
106 ) -> BoxFuture<'a, Result<()>> {
107 Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })
108 }
109 fn set_team_shown<'a>(
110 &'a self,
111 _team_thread_id: &'a str,
112 _shown: bool,
113 ) -> BoxFuture<'a, Result<()>> {
114 Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
115 }
92 116 }
93 117
94 118 pub struct ChatsvcFolderSource {
95 119 pins: Pins<SessionTransport>,
120 visibility: ChannelVisibility,
96 121 settings: UserSettings,
97 122 channel_settings: ChannelSettings,
98 123 properties: Mutex<Option<Value>>,
@@ -104,6 +129,7 @@ impl ChatsvcFolderSource {
104 129 pub fn new(session: &Session) -> Self {
105 130 ChatsvcFolderSource {
106 131 pins: Pins::new(session),
132 visibility: ChannelVisibility::new(session),
107 133 settings: UserSettings::new(session),
108 134 channel_settings: ChannelSettings::new(session),
109 135 properties: Mutex::new(None),
@@ -122,6 +148,49 @@ impl FolderSource for ChatsvcFolderSource {
122 148 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
123 149 }
124 150
151 fn set_channel_pinned<'a>(
152 &'a self,
153 channel_id: &'a str,
154 pinned: bool,
155 ) -> BoxFuture<'a, Result<Vec<String>>> {
156 Box::pin(async move {
157 let answer = if pinned {
158 self.pins.pin_channel(channel_id).await?
159 } else {
160 self.pins.unpin_channel(channel_id).await?
161 };
162 Ok(answer.channel_ids)
163 })
164 }
165
166 fn set_channel_shown<'a>(
167 &'a self,
168 target: ChannelTarget<'a>,
169 own_user_id: &'a str,
170 shown: bool,
171 now_ms: i64,
172 ) -> BoxFuture<'a, Result<()>> {
173 Box::pin(async move {
174 Ok(self
175 .visibility
176 .set_channel_shown(&target, own_user_id, shown, now_ms)
177 .await?)
178 })
179 }
180
181 fn set_team_shown<'a>(
182 &'a self,
183 team_thread_id: &'a str,
184 shown: bool,
185 ) -> BoxFuture<'a, Result<()>> {
186 Box::pin(async move {
187 Ok(self
188 .visibility
189 .set_team_shown(team_thread_id, shown)
190 .await?)
191 })
192 }
193
125 194 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
126 195 Box::pin(async {
127 196 let layout = self.pins.team_layout().await?;
@@ -567,13 +636,17 @@ impl<R: Remote> SyncEngine<R> {
567 636 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
568 637 }
569 638
570 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
639 pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
571 640 self.folder_source
572 641 .as_ref()
573 642 .ok_or(Error::Unsupported("chat folders without a folder source"))
574 643 }
575 644
576 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
645 pub(crate) fn store_folders(
646 &self,
647 folders: &[ChatFolder],
648 channel_ids: &[String],
649 ) -> Result<()> {
577 650 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
578 651 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
579 652 self.store.replace_folders(&records, channel_ids)?;
@@ -5,8 +5,9 @@ use std::sync::{Arc, Mutex};
5
5
6use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
6use chatsvc::settings::{parse_chat_sections, parse_skin_tone, parse_teams_order};
7use chatsvc::{
7use chatsvc::{
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChatSection,
8 ChannelNotificationLevel, ChannelNotifications, ChannelSettings, ChannelTarget,
9 ChatSectionSettings, Pins, UserSettings, pins::SessionTransport,
9 ChannelVisibility, ChatSection, ChatSectionSettings, Pins, UserSettings,
10 pins::SessionTransport,
10};
11};
11use chrono::Utc;
12use chrono::Utc;
12use serde_json::Value;
13use serde_json::Value;
@@ -89,10 +90,34 @@ pub trait FolderSource: Send + Sync {
89 folder_id: &'a str,
90 folder_id: &'a str,
90 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91 ) -> BoxFuture<'a, Result<Vec<ChatFolder>>>;
91 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
92 fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>>;
93 fn set_channel_pinned<'a>(
94 &'a self,
95 _channel_id: &'a str,
96 _pinned: bool,
97 ) -> BoxFuture<'a, Result<Vec<String>>> {
98 Box::pin(async { Err(Error::Unsupported("channel pins without chatsvc")) })
99 }
100 fn set_channel_shown<'a>(
101 &'a self,
102 _target: ChannelTarget<'a>,
103 _own_user_id: &'a str,
104 _shown: bool,
105 _now_ms: i64,
106 ) -> BoxFuture<'a, Result<()>> {
107 Box::pin(async { Err(Error::Unsupported("channel visibility without chatsvc")) })
108 }
109 fn set_team_shown<'a>(
110 &'a self,
111 _team_thread_id: &'a str,
112 _shown: bool,
113 ) -> BoxFuture<'a, Result<()>> {
114 Box::pin(async { Err(Error::Unsupported("team visibility without chatsvc")) })
115 }
92}
116}
93
117
94pub struct ChatsvcFolderSource {
118pub struct ChatsvcFolderSource {
95 pins: Pins<SessionTransport>,
119 pins: Pins<SessionTransport>,
120 visibility: ChannelVisibility,
96 settings: UserSettings,
121 settings: UserSettings,
97 channel_settings: ChannelSettings,
122 channel_settings: ChannelSettings,
98 properties: Mutex<Option<Value>>,
123 properties: Mutex<Option<Value>>,
@@ -104,6 +129,7 @@ impl ChatsvcFolderSource {
104 pub fn new(session: &Session) -> Self {
129 pub fn new(session: &Session) -> Self {
105 ChatsvcFolderSource {
130 ChatsvcFolderSource {
106 pins: Pins::new(session),
131 pins: Pins::new(session),
132 visibility: ChannelVisibility::new(session),
107 settings: UserSettings::new(session),
133 settings: UserSettings::new(session),
108 channel_settings: ChannelSettings::new(session),
134 channel_settings: ChannelSettings::new(session),
109 properties: Mutex::new(None),
135 properties: Mutex::new(None),
@@ -122,6 +148,49 @@ impl FolderSource for ChatsvcFolderSource {
122 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
148 Box::pin(async { Ok(self.pins.pinned_channels().await?.channel_ids) })
123 }
149 }
124
150
151 fn set_channel_pinned<'a>(
152 &'a self,
153 channel_id: &'a str,
154 pinned: bool,
155 ) -> BoxFuture<'a, Result<Vec<String>>> {
156 Box::pin(async move {
157 let answer = if pinned {
158 self.pins.pin_channel(channel_id).await?
159 } else {
160 self.pins.unpin_channel(channel_id).await?
161 };
162 Ok(answer.channel_ids)
163 })
164 }
165
166 fn set_channel_shown<'a>(
167 &'a self,
168 target: ChannelTarget<'a>,
169 own_user_id: &'a str,
170 shown: bool,
171 now_ms: i64,
172 ) -> BoxFuture<'a, Result<()>> {
173 Box::pin(async move {
174 Ok(self
175 .visibility
176 .set_channel_shown(&target, own_user_id, shown, now_ms)
177 .await?)
178 })
179 }
180
181 fn set_team_shown<'a>(
182 &'a self,
183 team_thread_id: &'a str,
184 shown: bool,
185 ) -> BoxFuture<'a, Result<()>> {
186 Box::pin(async move {
187 Ok(self
188 .visibility
189 .set_team_shown(team_thread_id, shown)
190 .await?)
191 })
192 }
193
125 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
194 fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
126 Box::pin(async {
195 Box::pin(async {
127 let layout = self.pins.team_layout().await?;
196 let layout = self.pins.team_layout().await?;
@@ -567,13 +636,17 @@ impl<R: Remote> SyncEngine<R> {
567 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
636 self.store_folders(&folders, &self.store.pinned_channel_ids()?)
568 }
637 }
569
638
570 fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
639 pub(crate) fn folder_source(&self) -> Result<&Arc<dyn FolderSource>> {
571 self.folder_source
640 self.folder_source
572 .as_ref()
641 .as_ref()
573 .ok_or(Error::Unsupported("chat folders without a folder source"))
642 .ok_or(Error::Unsupported("chat folders without a folder source"))
574 }
643 }
575
644
576 fn store_folders(&self, folders: &[ChatFolder], channel_ids: &[String]) -> Result<()> {
645 pub(crate) fn store_folders(
646 &self,
647 folders: &[ChatFolder],
648 channel_ids: &[String],
649 ) -> Result<()> {
577 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
650 let previous = (self.chat_folders()?, self.store.pinned_channel_ids()?);
578 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
651 let records: Vec<FolderRecord> = folders.iter().map(to_record).collect();
579 self.store.replace_folders(&records, channel_ids)?;
652 self.store.replace_folders(&records, channel_ids)?;
crates/core/src/lib.rs +3 −1
@@ -13,6 +13,7 @@ mod card_widgets;
13 13 mod card_width;
14 14 mod channel_mentions;
15 15 mod channel_sync;
16 mod channel_visibility;
16 17 mod chat_paging;
17 18 mod download;
18 19 mod draft;
@@ -140,7 +141,8 @@ pub use meeting_join::{
140 141 };
141 142 pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
142 143 pub use message_link::{
143 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
144 ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
145 chat_message_link, team_link,
144 146 };
145 147 pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
146 148 pub use notes_chat::{is_notes_chat, notes_chat_title};
@@ -13,6 +13,7 @@ mod card_widgets;
13mod card_width;
13mod card_width;
14mod channel_mentions;
14mod channel_mentions;
15mod channel_sync;
15mod channel_sync;
16mod channel_visibility;
16mod chat_paging;
17mod chat_paging;
17mod download;
18mod download;
18mod draft;
19mod draft;
@@ -140,7 +141,8 @@ pub use meeting_join::{
140};
141};
141pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
142pub use mentions::{MentionInput, apply_mentions, plain_mention_spans};
142pub use message_link::{
143pub use message_link::{
143 ChannelLinkInput, channel_message_link, channel_tab_link, chat_message_link,
144 ChannelAddress, ChannelLinkInput, channel_link, channel_message_link, channel_tab_link,
145 chat_message_link, team_link,
144};
146};
145pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
147pub use message_window::{JumpPlan, WINDOW_PAGE_SIZE, WindowPage, jump_plan, without_islands};
146pub use notes_chat::{is_notes_chat, notes_chat_title};
148pub use notes_chat::{is_notes_chat, notes_chat_title};
crates/core/tests/engine.rs +131 −0
@@ -3206,6 +3206,137 @@ impl FolderSource for FakeFolders {
3206 3206 Ok(state.clone())
3207 3207 })
3208 3208 }
3209
3210 fn set_channel_pinned<'a>(
3211 &'a self,
3212 channel_id: &'a str,
3213 pinned: bool,
3214 ) -> BoxFuture<'a, Result<Vec<String>>> {
3215 Box::pin(async move {
3216 self.calls
3217 .lock()
3218 .unwrap()
3219 .push(format!("pin channel {channel_id} {pinned}"));
3220 let mut channel_ids = self.channels.clone();
3221 channel_ids.retain(|id| id != channel_id);
3222 if pinned {
3223 channel_ids.push(channel_id.to_owned());
3224 }
3225 Ok(channel_ids)
3226 })
3227 }
3228
3229 fn set_channel_shown<'a>(
3230 &'a self,
3231 target: chatsvc::ChannelTarget<'a>,
3232 own_user_id: &'a str,
3233 shown: bool,
3234 _now_ms: i64,
3235 ) -> BoxFuture<'a, Result<()>> {
3236 Box::pin(async move {
3237 self.calls.lock().unwrap().push(format!(
3238 "show channel {} general={} {:?} {own_user_id} {shown}",
3239 target.channel_id, target.general, target.kind
3240 ));
3241 Ok(())
3242 })
3243 }
3244
3245 fn set_team_shown<'a>(
3246 &'a self,
3247 team_thread_id: &'a str,
3248 shown: bool,
3249 ) -> BoxFuture<'a, Result<()>> {
3250 Box::pin(async move {
3251 self.calls
3252 .lock()
3253 .unwrap()
3254 .push(format!("show team {team_thread_id} {shown}"));
3255 Ok(())
3256 })
3257 }
3258 }
3259
3260 fn store_alpha_team(engine: &SyncEngine<Handle>) {
3261 engine
3262 .store()
3263 .upsert_teams(&[TeamRecord {
3264 id: "alpha".into(),
3265 name: "Alpha".into(),
3266 }])
3267 .unwrap();
3268 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3269 id: id.into(),
3270 team_id: "alpha".into(),
3271 name: name.into(),
3272 membership_type: membership_type.map(str::to_owned),
3273 last_message_at: None,
3274 unread: false,
3275 };
3276 engine
3277 .store()
3278 .upsert_channels(&[
3279 channel("19:general@thread.tacv2", "General", Some("standard")),
3280 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3281 ])
3282 .unwrap();
3283 }
3284
3285 #[tokio::test]
3286 async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3287 let fake = Arc::new(Fake::default());
3288 let source = FakeFolders::new();
3289 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3290 store_alpha_team(&engine);
3291 let mut events = engine.subscribe();
3292
3293 engine.set_channel_pinned("ch3", true).await.unwrap();
3294 assert_eq!(
3295 engine.pinned_channels().unwrap(),
3296 ids(&["ch1", "ch2", "ch3"])
3297 );
3298 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3299 engine.set_channel_pinned("ch1", false).await.unwrap();
3300 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3301
3302 engine
3303 .set_channel_shown("19:secret@thread.tacv2", false)
3304 .await
3305 .unwrap();
3306 engine
3307 .set_channel_shown("19:general@thread.tacv2", false)
3308 .await
3309 .unwrap();
3310 engine.set_team_shown("alpha", false).await.unwrap();
3311 let team = engine.store().sidebar().unwrap().teams.remove(0);
3312 assert!(team.hidden);
3313 assert_eq!(team.hidden_channel_ids.len(), 2);
3314 let calls = source.calls.lock().unwrap().clone();
3315 assert_eq!(
3316 calls[2..],
3317 [
3318 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3319 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3320 "show team 19:general@thread.tacv2 false".to_owned(),
3321 ]
3322 );
3323 }
3324
3325 #[tokio::test]
3326 async fn channel_and_team_links_use_the_cached_tenant() {
3327 let fake = Arc::new(Fake::default());
3328 let engine = engine_with(&fake, SyncConfig::default());
3329 store_alpha_team(&engine);
3330 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3331
3332 assert_eq!(
3333 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3334 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3335 );
3336 assert_eq!(
3337 engine.team_link("alpha").await.unwrap(),
3338 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3339 );
3209 3340 }
3210 3341
3211 3342 #[tokio::test]
@@ -3206,6 +3206,137 @@ impl FolderSource for FakeFolders {
3206 Ok(state.clone())
3206 Ok(state.clone())
3207 })
3207 })
3208 }
3208 }
3209
3210 fn set_channel_pinned<'a>(
3211 &'a self,
3212 channel_id: &'a str,
3213 pinned: bool,
3214 ) -> BoxFuture<'a, Result<Vec<String>>> {
3215 Box::pin(async move {
3216 self.calls
3217 .lock()
3218 .unwrap()
3219 .push(format!("pin channel {channel_id} {pinned}"));
3220 let mut channel_ids = self.channels.clone();
3221 channel_ids.retain(|id| id != channel_id);
3222 if pinned {
3223 channel_ids.push(channel_id.to_owned());
3224 }
3225 Ok(channel_ids)
3226 })
3227 }
3228
3229 fn set_channel_shown<'a>(
3230 &'a self,
3231 target: chatsvc::ChannelTarget<'a>,
3232 own_user_id: &'a str,
3233 shown: bool,
3234 _now_ms: i64,
3235 ) -> BoxFuture<'a, Result<()>> {
3236 Box::pin(async move {
3237 self.calls.lock().unwrap().push(format!(
3238 "show channel {} general={} {:?} {own_user_id} {shown}",
3239 target.channel_id, target.general, target.kind
3240 ));
3241 Ok(())
3242 })
3243 }
3244
3245 fn set_team_shown<'a>(
3246 &'a self,
3247 team_thread_id: &'a str,
3248 shown: bool,
3249 ) -> BoxFuture<'a, Result<()>> {
3250 Box::pin(async move {
3251 self.calls
3252 .lock()
3253 .unwrap()
3254 .push(format!("show team {team_thread_id} {shown}"));
3255 Ok(())
3256 })
3257 }
3258}
3259
3260fn store_alpha_team(engine: &SyncEngine<Handle>) {
3261 engine
3262 .store()
3263 .upsert_teams(&[TeamRecord {
3264 id: "alpha".into(),
3265 name: "Alpha".into(),
3266 }])
3267 .unwrap();
3268 let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord {
3269 id: id.into(),
3270 team_id: "alpha".into(),
3271 name: name.into(),
3272 membership_type: membership_type.map(str::to_owned),
3273 last_message_at: None,
3274 unread: false,
3275 };
3276 engine
3277 .store()
3278 .upsert_channels(&[
3279 channel("19:general@thread.tacv2", "General", Some("standard")),
3280 channel("19:secret@thread.tacv2", "Secret", Some("private")),
3281 ])
3282 .unwrap();
3283}
3284
3285#[tokio::test]
3286async fn channel_pin_and_show_hide_go_through_the_source_and_cache() {
3287 let fake = Arc::new(Fake::default());
3288 let source = FakeFolders::new();
3289 let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
3290 store_alpha_team(&engine);
3291 let mut events = engine.subscribe();
3292
3293 engine.set_channel_pinned("ch3", true).await.unwrap();
3294 assert_eq!(
3295 engine.pinned_channels().unwrap(),
3296 ids(&["ch1", "ch2", "ch3"])
3297 );
3298 assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged);
3299 engine.set_channel_pinned("ch1", false).await.unwrap();
3300 assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"]));
3301
3302 engine
3303 .set_channel_shown("19:secret@thread.tacv2", false)
3304 .await
3305 .unwrap();
3306 engine
3307 .set_channel_shown("19:general@thread.tacv2", false)
3308 .await
3309 .unwrap();
3310 engine.set_team_shown("alpha", false).await.unwrap();
3311 let team = engine.store().sidebar().unwrap().teams.remove(0);
3312 assert!(team.hidden);
3313 assert_eq!(team.hidden_channel_ids.len(), 2);
3314 let calls = source.calls.lock().unwrap().clone();
3315 assert_eq!(
3316 calls[2..],
3317 [
3318 format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"),
3319 format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"),
3320 "show team 19:general@thread.tacv2 false".to_owned(),
3321 ]
3322 );
3323}
3324
3325#[tokio::test]
3326async fn channel_and_team_links_use_the_cached_tenant() {
3327 let fake = Arc::new(Fake::default());
3328 let engine = engine_with(&fake, SyncConfig::default());
3329 store_alpha_team(&engine);
3330 engine.store().set_meta("me_tenant_id", "tenant-1").unwrap();
3331
3332 assert_eq!(
3333 engine.channel_link("19:secret@thread.tacv2").await.unwrap(),
3334 "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true"
3335 );
3336 assert_eq!(
3337 engine.team_link("alpha").await.unwrap(),
3338 "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1"
3339 );
3209}
3340}
3210
3341
3211#[tokio::test]
3342#[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}