BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / channel_menu.rs

channel_menu.rs

channel_menu.rs 18.5 KiB Download Raw
1use std::future::Future;
2
3use gpui_kit::*;
4
5use crate::app_state::AppState;
6use crate::sidebar_model::channel_shown;
7use crate::team_admin::ChannelAdmin;
8
9pub const COPIED_TO_CLIPBOARD: &str = "Copied to clipboard";
10pub const PINNED_CHANNEL_CANNOT_HIDE: &str = "Pinned channels can't be hidden.";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum ChannelMenuItem {
14 Notifications,
15 Pin,
16 Unpin,
17 Show,
18 Hide,
19 EditChannel,
20 ManageChannel,
21 CopyLink,
22 DeleteChannel,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum TeamMenuItem {
27 AddChannel,
28 Show,
29 Hide,
30 ManageTeam,
31 CopyLink,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum MenuEntry<Item> {
36 Item(Item),
37 Separator,
38}
39
40impl ChannelMenuItem {
41 pub fn label(self) -> &'static str {
42 match self {
43 ChannelMenuItem::Notifications => "Channel notifications",
44 ChannelMenuItem::Pin => "Pin",
45 ChannelMenuItem::Unpin => "Unpin",
46 ChannelMenuItem::Show => "Show",
47 ChannelMenuItem::Hide => "Hide",
48 ChannelMenuItem::EditChannel => "Edit channel",
49 ChannelMenuItem::ManageChannel => "Manage channel",
50 ChannelMenuItem::CopyLink => "Copy link",
51 ChannelMenuItem::DeleteChannel => "Delete channel",
52 }
53 }
54}
55
56impl TeamMenuItem {
57 pub fn label(self) -> &'static str {
58 match self {
59 TeamMenuItem::AddChannel => "Add channel",
60 TeamMenuItem::Show => "Show",
61 TeamMenuItem::Hide => "Hide",
62 TeamMenuItem::ManageTeam => "Manage team",
63 TeamMenuItem::CopyLink => "Copy link",
64 }
65 }
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69enum LinkUse {
70 Copy,
71 OpenInBrowser,
72}
73
74impl LinkUse {
75 fn failure(self, reason: &str) -> String {
76 match self {
77 LinkUse::Copy => format!("Copy link failed: {reason}"),
78 LinkUse::OpenInBrowser => format!("Couldn't open Teams on the web: {reason}"),
79 }
80 }
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub struct ChannelMenuState {
85 pub pinned: bool,
86 pub shown: bool,
87 pub admin: ChannelAdmin,
88}
89
90impl ChannelMenuState {
91 pub fn disables(self, item: ChannelMenuItem) -> bool {
92 item == ChannelMenuItem::Hide && self.pinned
93 }
94}
95
96pub fn channel_menu_entries(state: ChannelMenuState) -> Vec<MenuEntry<ChannelMenuItem>> {
97 let mut entries = vec![
98 MenuEntry::Item(ChannelMenuItem::Notifications),
99 MenuEntry::Item(if state.pinned {
100 ChannelMenuItem::Unpin
101 } else {
102 ChannelMenuItem::Pin
103 }),
104 MenuEntry::Item(if state.shown {
105 ChannelMenuItem::Hide
106 } else {
107 ChannelMenuItem::Show
108 }),
109 MenuEntry::Separator,
110 ];
111 if state.admin.can_edit {
112 entries.push(MenuEntry::Item(ChannelMenuItem::EditChannel));
113 }
114 entries.extend([
115 MenuEntry::Item(ChannelMenuItem::ManageChannel),
116 MenuEntry::Item(ChannelMenuItem::CopyLink),
117 ]);
118 if state.admin.can_delete {
119 entries.extend([
120 MenuEntry::Separator,
121 MenuEntry::Item(ChannelMenuItem::DeleteChannel),
122 ]);
123 }
124 entries
125}
126
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
128pub struct TeamMenuState {
129 pub hidden: bool,
130 pub can_add_channel: bool,
131}
132
133pub fn team_menu_entries(state: TeamMenuState) -> Vec<MenuEntry<TeamMenuItem>> {
134 let mut entries = Vec::new();
135 if state.can_add_channel {
136 entries.push(MenuEntry::Item(TeamMenuItem::AddChannel));
137 }
138 entries.extend([
139 MenuEntry::Item(if state.hidden {
140 TeamMenuItem::Show
141 } else {
142 TeamMenuItem::Hide
143 }),
144 MenuEntry::Separator,
145 MenuEntry::Item(TeamMenuItem::ManageTeam),
146 MenuEntry::Item(TeamMenuItem::CopyLink),
147 ]);
148 entries
149}
150
151pub fn pin_failure(pinned: bool) -> &'static str {
152 if pinned {
153 "We couldn't pin the channel."
154 } else {
155 "We couldn't unpin the channel."
156 }
157}
158
159pub fn channel_visibility_failure(shown: bool) -> &'static str {
160 if shown {
161 "We couldn't show the channel."
162 } else {
163 "We couldn't hide the channel."
164 }
165}
166
167pub fn team_visibility_failure(shown: bool) -> &'static str {
168 if shown {
169 "We couldn't show the team."
170 } else {
171 "We couldn't hide the team."
172 }
173}
174
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub struct PostPinDialog {
177 pub title: &'static str,
178 pub body: &'static str,
179 pub confirm: &'static str,
180}
181
182pub fn post_pin_dialog(pin: bool) -> PostPinDialog {
183 if pin {
184 PostPinDialog {
185 title: "Pin in channel",
186 body: "The message will be pinned for everyone who views the channel.",
187 confirm: "Pin",
188 }
189 } else {
190 PostPinDialog {
191 title: "Unpin this message?",
192 body: "The message will be unpinned for everyone who views the channel.",
193 confirm: "Unpin",
194 }
195 }
196}
197
198pub fn post_pin_notice(pin: bool) -> &'static str {
199 if pin { "Post pinned" } else { "Post unpinned" }
200}
201
202pub fn post_pin_failure(pin: bool) -> &'static str {
203 if pin {
204 "We couldn't pin the post."
205 } else {
206 "We couldn't unpin the post."
207 }
208}
209
210impl AppState {
211 pub fn channel_menu_state(&self, channel_id: &str) -> ChannelMenuState {
212 ChannelMenuState {
213 pinned: self.channel_pinned(channel_id),
214 shown: self
215 .sidebar
216 .teams
217 .iter()
218 .find(|team| team.channels.iter().any(|channel| channel.id == channel_id))
219 .is_none_or(|team| channel_shown(team, channel_id)),
220 admin: self.channel_admin(channel_id),
221 }
222 }
223
224 pub fn channel_pinned(&self, channel_id: &str) -> bool {
225 self.directory
226 .pinned_channels
227 .iter()
228 .any(|id| id == channel_id)
229 }
230
231 pub fn set_channel_pinned(&mut self, channel_id: &str, pinned: bool, cx: &mut Context<Self>) {
232 if self.channel_pinned(channel_id) == pinned {
233 return;
234 }
235 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
236 return;
237 };
238 let previous = self.directory.pinned_channels.clone();
239 let mut changed = previous.clone();
240 changed.retain(|id| id != channel_id);
241 if pinned {
242 changed.push(channel_id.to_owned());
243 }
244 self.apply_pinned_channels(changed, cx);
245 let Some(engine) = engine_or_demo else {
246 return;
247 };
248 let owned_id = channel_id.to_owned();
249 self.run_channel_action(
250 pin_failure(pinned),
251 async move { engine.set_channel_pinned(&owned_id, pinned).await },
252 move |state, cx| state.apply_pinned_channels(previous, cx),
253 None,
254 cx,
255 );
256 }
257
258 fn apply_pinned_channels(&mut self, channel_ids: Vec<String>, cx: &mut Context<Self>) {
259 let _ = self.store.replace_pinned_channels(&channel_ids);
260 self.directory.pinned_channels = channel_ids;
261 cx.emit(crate::app_state::AppEvent::Sidebar);
262 cx.notify();
263 }
264
265 pub fn set_channel_shown(&mut self, channel_id: &str, shown: bool, cx: &mut Context<Self>) {
266 if !shown && self.channel_pinned(channel_id) {
267 self.raise_notice(PINNED_CHANNEL_CANNOT_HIDE.to_owned(), None, cx);
268 return;
269 }
270 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
271 return;
272 };
273 let _ = self.store.set_channel_hidden(channel_id, !shown);
274 self.reload_sidebar(cx);
275 let Some(engine) = engine_or_demo else {
276 return;
277 };
278 let owned_id = channel_id.to_owned();
279 let revert_id = owned_id.clone();
280 self.run_channel_action(
281 channel_visibility_failure(shown),
282 async move { engine.set_channel_shown(&owned_id, shown).await },
283 move |state, cx| {
284 let _ = state.store.set_channel_hidden(&revert_id, shown);
285 state.reload_sidebar(cx);
286 },
287 None,
288 cx,
289 );
290 }
291
292 pub fn set_team_shown(&mut self, team_id: &str, shown: bool, cx: &mut Context<Self>) {
293 let Some(engine_or_demo) = self.chat_action_engine(cx) else {
294 return;
295 };
296 let _ = self.store.set_team_hidden(team_id, !shown);
297 self.reload_sidebar(cx);
298 let Some(engine) = engine_or_demo else {
299 return;
300 };
301 let owned_id = team_id.to_owned();
302 let revert_id = owned_id.clone();
303 self.run_channel_action(
304 team_visibility_failure(shown),
305 async move { engine.set_team_shown(&owned_id, shown).await },
306 move |state, cx| {
307 let _ = state.store.set_team_hidden(&revert_id, shown);
308 state.reload_sidebar(cx);
309 },
310 None,
311 cx,
312 );
313 }
314
315 pub fn copy_channel_link(&mut self, channel_id: &str, cx: &mut Context<Self>) {
316 self.with_channel_link(channel_id, LinkUse::Copy, cx);
317 }
318
319 pub fn manage_channel_in_browser(&mut self, channel_id: &str, cx: &mut Context<Self>) {
320 self.with_channel_link(channel_id, LinkUse::OpenInBrowser, cx);
321 }
322
323 fn with_channel_link(&mut self, channel_id: &str, link_use: LinkUse, cx: &mut Context<Self>) {
324 let Some(engine) = self.engine.clone() else {
325 if self.mode.demo {
326 let link = teams_core::channel_link(&teams_core::ChannelAddress {
327 tenant_id: crate::demo::DEMO_TENANT_ID.to_owned(),
328 group_id: self.channel_team_id(channel_id).unwrap_or_default(),
329 channel_id: channel_id.to_owned(),
330 channel_name: self.channel_name(channel_id).unwrap_or_default(),
331 membership_type: None,
332 });
333 self.use_link(link, link_use, cx);
334 }
335 return;
336 };
337 let owned_id = channel_id.to_owned();
338 self.link_from(
339 async move { engine.channel_link(&owned_id).await },
340 link_use,
341 cx,
342 );
343 }
344
345 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
346 self.with_team_link(team_id, LinkUse::Copy, cx);
347 }
348
349 pub fn manage_team_in_browser(&mut self, team_id: &str, cx: &mut Context<Self>) {
350 self.with_team_link(team_id, LinkUse::OpenInBrowser, cx);
351 }
352
353 fn with_team_link(&mut self, team_id: &str, link_use: LinkUse, cx: &mut Context<Self>) {
354 let Some(engine) = self.engine.clone() else {
355 if self.mode.demo {
356 let team_thread_id = self.store.team_thread_id(team_id).ok().flatten();
357 let link = teams_core::team_link(
358 team_thread_id.as_deref().unwrap_or(team_id),
359 team_id,
360 crate::demo::DEMO_TENANT_ID,
361 );
362 self.use_link(link, link_use, cx);
363 }
364 return;
365 };
366 let owned_id = team_id.to_owned();
367 self.link_from(
368 async move { engine.team_link(&owned_id).await },
369 link_use,
370 cx,
371 );
372 }
373
374 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
375 self.sidebar.teams.iter().find_map(|team| {
376 team.channels
377 .iter()
378 .any(|channel| channel.id == channel_id)
379 .then(|| team.team.id.clone())
380 })
381 }
382
383 pub fn channel_name(&self, channel_id: &str) -> Option<String> {
384 self.sidebar
385 .teams
386 .iter()
387 .flat_map(|team| &team.channels)
388 .find(|channel| channel.id == channel_id)
389 .map(|channel| channel.name.clone())
390 }
391
392 fn use_link(&mut self, link: String, link_use: LinkUse, cx: &mut Context<Self>) {
393 match link_use {
394 LinkUse::Copy => {
395 cx.write_to_clipboard(ClipboardItem::new_string(link));
396 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
397 }
398 LinkUse::OpenInBrowser => app_base::open_link::open_url(cx, &link),
399 }
400 }
401
402 fn link_from(
403 &mut self,
404 call: impl Future<Output = teams_core::Result<String>> + Send + 'static,
405 link_use: LinkUse,
406 cx: &mut Context<Self>,
407 ) {
408 let receiver = crate::runtime::spawn(call);
409 cx.spawn(async move |this, cx| {
410 let outcome = match receiver.await {
411 Ok(Ok(link)) => Ok(link),
412 Ok(Err(error)) => Err(crate::notice::short_error(&error)),
413 Err(_) => Err("cancelled".to_owned()),
414 };
415 this.update(cx, |state, cx| match outcome {
416 Ok(link) => state.use_link(link, link_use, cx),
417 Err(reason) => state.raise_notice(link_use.failure(&reason), None, cx),
418 })
419 .ok();
420 })
421 .detach();
422 }
423
424 pub(crate) fn run_channel_action(
425 &mut self,
426 failure: &'static str,
427 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
428 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
429 success: Option<&'static str>,
430 cx: &mut Context<Self>,
431 ) {
432 let receiver = crate::runtime::spawn(call);
433 cx.spawn(async move |this, cx| {
434 let failed = !matches!(receiver.await, Ok(Ok(())));
435 this.update(cx, |state, cx| {
436 if failed {
437 revert(state, cx);
438 state.raise_notice(failure.to_owned(), None, cx);
439 } else if let Some(text) = success {
440 state.raise_notice(text.to_owned(), None, cx);
441 }
442 })
443 .ok();
444 })
445 .detach();
446 }
447}
448
449#[cfg(test)]
450mod tests {
451 use crate::team_admin::ChannelAdmin;
452
453 use super::{
454 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, TeamMenuState,
455 channel_menu_entries, channel_visibility_failure, pin_failure, post_pin_dialog,
456 post_pin_failure, post_pin_notice, team_menu_entries, team_visibility_failure,
457 };
458
459 fn labels<Item: Copy>(
460 entries: &[MenuEntry<Item>],
461 label: impl Fn(Item) -> &'static str,
462 ) -> Vec<&'static str> {
463 entries
464 .iter()
465 .map(|entry| match entry {
466 MenuEntry::Item(item) => label(*item),
467 MenuEntry::Separator => "-",
468 })
469 .collect()
470 }
471
472 #[test]
473 fn channel_menu_follows_teams_order() {
474 let shown = channel_menu_entries(ChannelMenuState {
475 pinned: false,
476 shown: true,
477 ..ChannelMenuState::default()
478 });
479 assert_eq!(
480 labels(&shown, ChannelMenuItem::label),
481 [
482 "Channel notifications",
483 "Pin",
484 "Hide",
485 "-",
486 "Manage channel",
487 "Copy link"
488 ]
489 );
490 let hidden_pinned = channel_menu_entries(ChannelMenuState {
491 pinned: true,
492 shown: false,
493 ..ChannelMenuState::default()
494 });
495 assert_eq!(
496 labels(&hidden_pinned, ChannelMenuItem::label),
497 [
498 "Channel notifications",
499 "Unpin",
500 "Show",
501 "-",
502 "Manage channel",
503 "Copy link"
504 ]
505 );
506 }
507
508 #[test]
509 fn pinned_channels_cannot_be_hidden() {
510 let pinned = ChannelMenuState {
511 pinned: true,
512 shown: true,
513 ..ChannelMenuState::default()
514 };
515 assert!(pinned.disables(ChannelMenuItem::Hide));
516 assert!(!pinned.disables(ChannelMenuItem::Unpin));
517 let unpinned = ChannelMenuState {
518 pinned: false,
519 shown: true,
520 ..ChannelMenuState::default()
521 };
522 assert!(!unpinned.disables(ChannelMenuItem::Hide));
523 }
524
525 #[test]
526 fn edit_and_delete_appear_only_with_the_rights() {
527 let admin = ChannelMenuState {
528 pinned: false,
529 shown: true,
530 admin: ChannelAdmin {
531 can_edit: true,
532 can_delete: true,
533 },
534 };
535 assert_eq!(
536 labels(&channel_menu_entries(admin), ChannelMenuItem::label),
537 [
538 "Channel notifications",
539 "Pin",
540 "Hide",
541 "-",
542 "Edit channel",
543 "Manage channel",
544 "Copy link",
545 "-",
546 "Delete channel"
547 ]
548 );
549 }
550
551 #[test]
552 fn team_menu_switches_between_show_and_hide() {
553 let shown = TeamMenuState::default();
554 assert_eq!(
555 labels(&team_menu_entries(shown), TeamMenuItem::label),
556 ["Hide", "-", "Manage team", "Copy link"]
557 );
558 let hidden = TeamMenuState {
559 hidden: true,
560 ..shown
561 };
562 assert_eq!(
563 labels(&team_menu_entries(hidden), TeamMenuItem::label),
564 ["Show", "-", "Manage team", "Copy link"]
565 );
566 }
567
568 #[test]
569 fn add_channel_leads_the_team_menu_when_the_team_allows_it() {
570 let state = TeamMenuState {
571 hidden: false,
572 can_add_channel: true,
573 };
574 assert_eq!(
575 labels(&team_menu_entries(state), TeamMenuItem::label),
576 ["Add channel", "Hide", "-", "Manage team", "Copy link"]
577 );
578 }
579
580 #[test]
581 fn post_pin_dialogs_and_notices_use_teams_strings() {
582 let unpin = post_pin_dialog(false);
583 assert_eq!(unpin.title, "Unpin this message?");
584 assert_eq!(
585 unpin.body,
586 "The message will be unpinned for everyone who views the channel."
587 );
588 assert_eq!(unpin.confirm, "Unpin");
589 let pin = post_pin_dialog(true);
590 assert_eq!(pin.title, "Pin in channel");
591 assert_eq!(pin.confirm, "Pin");
592 assert_eq!(post_pin_notice(true), "Post pinned");
593 assert_eq!(post_pin_notice(false), "Post unpinned");
594 assert_eq!(post_pin_failure(true), "We couldn't pin the post.");
595 assert_eq!(post_pin_failure(false), "We couldn't unpin the post.");
596 }
597
598 #[test]
599 fn failures_use_teams_strings() {
600 assert_eq!(pin_failure(true), "We couldn't pin the channel.");
601 assert_eq!(pin_failure(false), "We couldn't unpin the channel.");
602 assert_eq!(
603 channel_visibility_failure(false),
604 "We couldn't hide the channel."
605 );
606 assert_eq!(team_visibility_failure(true), "We couldn't show the team.");
607 }
608}