BlueGit

ict rusty-teams

Files

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

channel_menu.rs

channel_menu.rs 18.2 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(async move { engine.channel_link(&owned_id).await }, link_use, cx);
339 }
340
341 pub fn copy_team_link(&mut self, team_id: &str, cx: &mut Context<Self>) {
342 self.with_team_link(team_id, LinkUse::Copy, cx);
343 }
344
345 pub fn manage_team_in_browser(&mut self, team_id: &str, cx: &mut Context<Self>) {
346 self.with_team_link(team_id, LinkUse::OpenInBrowser, cx);
347 }
348
349 fn with_team_link(&mut self, team_id: &str, link_use: LinkUse, cx: &mut Context<Self>) {
350 let Some(engine) = self.engine.clone() else {
351 if self.mode.demo {
352 let team_thread_id = self.store.team_thread_id(team_id).ok().flatten();
353 let link = teams_core::team_link(
354 team_thread_id.as_deref().unwrap_or(team_id),
355 team_id,
356 crate::demo::DEMO_TENANT_ID,
357 );
358 self.use_link(link, link_use, cx);
359 }
360 return;
361 };
362 let owned_id = team_id.to_owned();
363 self.link_from(async move { engine.team_link(&owned_id).await }, link_use, cx);
364 }
365
366 pub fn channel_team_id(&self, channel_id: &str) -> Option<String> {
367 self.sidebar.teams.iter().find_map(|team| {
368 team.channels
369 .iter()
370 .any(|channel| channel.id == channel_id)
371 .then(|| team.team.id.clone())
372 })
373 }
374
375 pub fn channel_name(&self, channel_id: &str) -> Option<String> {
376 self.sidebar
377 .teams
378 .iter()
379 .flat_map(|team| &team.channels)
380 .find(|channel| channel.id == channel_id)
381 .map(|channel| channel.name.clone())
382 }
383
384 fn use_link(&mut self, link: String, link_use: LinkUse, cx: &mut Context<Self>) {
385 match link_use {
386 LinkUse::Copy => {
387 cx.write_to_clipboard(ClipboardItem::new_string(link));
388 self.raise_notice(COPIED_TO_CLIPBOARD.to_owned(), None, cx);
389 }
390 LinkUse::OpenInBrowser => cx.open_url(&link),
391 }
392 }
393
394 fn link_from(
395 &mut self,
396 call: impl Future<Output = teams_core::Result<String>> + Send + 'static,
397 link_use: LinkUse,
398 cx: &mut Context<Self>,
399 ) {
400 let receiver = crate::runtime::spawn(call);
401 cx.spawn(async move |this, cx| {
402 let outcome = match receiver.await {
403 Ok(Ok(link)) => Ok(link),
404 Ok(Err(error)) => Err(crate::notice::short_error(&error)),
405 Err(_) => Err("cancelled".to_owned()),
406 };
407 this.update(cx, |state, cx| match outcome {
408 Ok(link) => state.use_link(link, link_use, cx),
409 Err(reason) => state.raise_notice(link_use.failure(&reason), None, cx),
410 })
411 .ok();
412 })
413 .detach();
414 }
415
416 pub(crate) fn run_channel_action(
417 &mut self,
418 failure: &'static str,
419 call: impl Future<Output = teams_core::Result<()>> + Send + 'static,
420 revert: impl FnOnce(&mut Self, &mut Context<Self>) + 'static,
421 success: Option<&'static str>,
422 cx: &mut Context<Self>,
423 ) {
424 let receiver = crate::runtime::spawn(call);
425 cx.spawn(async move |this, cx| {
426 let failed = !matches!(receiver.await, Ok(Ok(())));
427 this.update(cx, |state, cx| {
428 if failed {
429 revert(state, cx);
430 state.raise_notice(failure.to_owned(), None, cx);
431 } else if let Some(text) = success {
432 state.raise_notice(text.to_owned(), None, cx);
433 }
434 })
435 .ok();
436 })
437 .detach();
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use crate::team_admin::ChannelAdmin;
444
445 use super::{
446 ChannelMenuItem, ChannelMenuState, MenuEntry, TeamMenuItem, TeamMenuState,
447 channel_menu_entries, channel_visibility_failure, pin_failure, post_pin_dialog,
448 post_pin_failure, post_pin_notice, team_menu_entries, team_visibility_failure,
449 };
450
451 fn labels<Item: Copy>(
452 entries: &[MenuEntry<Item>],
453 label: impl Fn(Item) -> &'static str,
454 ) -> Vec<&'static str> {
455 entries
456 .iter()
457 .map(|entry| match entry {
458 MenuEntry::Item(item) => label(*item),
459 MenuEntry::Separator => "-",
460 })
461 .collect()
462 }
463
464 #[test]
465 fn channel_menu_follows_teams_order() {
466 let shown = channel_menu_entries(ChannelMenuState {
467 pinned: false,
468 shown: true,
469 ..ChannelMenuState::default()
470 });
471 assert_eq!(
472 labels(&shown, ChannelMenuItem::label),
473 ["Channel notifications", "Pin", "Hide", "-", "Manage channel", "Copy link"]
474 );
475 let hidden_pinned = channel_menu_entries(ChannelMenuState {
476 pinned: true,
477 shown: false,
478 ..ChannelMenuState::default()
479 });
480 assert_eq!(
481 labels(&hidden_pinned, ChannelMenuItem::label),
482 ["Channel notifications", "Unpin", "Show", "-", "Manage channel", "Copy link"]
483 );
484 }
485
486 #[test]
487 fn pinned_channels_cannot_be_hidden() {
488 let pinned = ChannelMenuState {
489 pinned: true,
490 shown: true,
491 ..ChannelMenuState::default()
492 };
493 assert!(pinned.disables(ChannelMenuItem::Hide));
494 assert!(!pinned.disables(ChannelMenuItem::Unpin));
495 let unpinned = ChannelMenuState {
496 pinned: false,
497 shown: true,
498 ..ChannelMenuState::default()
499 };
500 assert!(!unpinned.disables(ChannelMenuItem::Hide));
501 }
502
503 #[test]
504 fn edit_and_delete_appear_only_with_the_rights() {
505 let admin = ChannelMenuState {
506 pinned: false,
507 shown: true,
508 admin: ChannelAdmin {
509 can_edit: true,
510 can_delete: true,
511 },
512 };
513 assert_eq!(
514 labels(&channel_menu_entries(admin), ChannelMenuItem::label),
515 [
516 "Channel notifications",
517 "Pin",
518 "Hide",
519 "-",
520 "Edit channel",
521 "Manage channel",
522 "Copy link",
523 "-",
524 "Delete channel"
525 ]
526 );
527 }
528
529 #[test]
530 fn team_menu_switches_between_show_and_hide() {
531 let shown = TeamMenuState::default();
532 assert_eq!(
533 labels(&team_menu_entries(shown), TeamMenuItem::label),
534 ["Hide", "-", "Manage team", "Copy link"]
535 );
536 let hidden = TeamMenuState {
537 hidden: true,
538 ..shown
539 };
540 assert_eq!(
541 labels(&team_menu_entries(hidden), TeamMenuItem::label),
542 ["Show", "-", "Manage team", "Copy link"]
543 );
544 }
545
546 #[test]
547 fn add_channel_leads_the_team_menu_when_the_team_allows_it() {
548 let state = TeamMenuState {
549 hidden: false,
550 can_add_channel: true,
551 };
552 assert_eq!(
553 labels(&team_menu_entries(state), TeamMenuItem::label),
554 ["Add channel", "Hide", "-", "Manage team", "Copy link"]
555 );
556 }
557
558 #[test]
559 fn post_pin_dialogs_and_notices_use_teams_strings() {
560 let unpin = post_pin_dialog(false);
561 assert_eq!(unpin.title, "Unpin this message?");
562 assert_eq!(
563 unpin.body,
564 "The message will be unpinned for everyone who views the channel."
565 );
566 assert_eq!(unpin.confirm, "Unpin");
567 let pin = post_pin_dialog(true);
568 assert_eq!(pin.title, "Pin in channel");
569 assert_eq!(pin.confirm, "Pin");
570 assert_eq!(post_pin_notice(true), "Post pinned");
571 assert_eq!(post_pin_notice(false), "Post unpinned");
572 assert_eq!(post_pin_failure(true), "We couldn't pin the post.");
573 assert_eq!(post_pin_failure(false), "We couldn't unpin the post.");
574 }
575
576 #[test]
577 fn failures_use_teams_strings() {
578 assert_eq!(pin_failure(true), "We couldn't pin the channel.");
579 assert_eq!(pin_failure(false), "We couldn't unpin the channel.");
580 assert_eq!(
581 channel_visibility_failure(false),
582 "We couldn't hide the channel."
583 );
584 assert_eq!(team_visibility_failure(true), "We couldn't show the team.");
585 }
586}