BlueGit

ict rusty-teams

Files

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

channel_menu.rs

channel_menu.rs 14.3 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 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}