BlueGit

ict rusty-teams

Files

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

channel_menu.rs

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