BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / sidebar.rs

sidebar.rs

sidebar.rs 52.2 KiB Download Raw
1use std::collections::HashSet;
2use std::time::Duration;
3
4use chrono::{Local, Offset, Utc};
5use gpui_kit::assets::IconName;
6use gpui_kit::component::button::{Button, ButtonVariants as _};
7use gpui_kit::component::dialog::DialogFooter;
8use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenu, PopupMenuItem};
9use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use store::{
13 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
14};
15
16use super::avatar::{spec_avatar, square_avatar, with_presence};
17use super::activity_panel::ActivityPanel;
18use super::calls_tab::calls_body;
19use super::saved_panel::SavedPanel;
20use super::widgets::{count_badge, dot, icon, page_header, unread_marker};
21use crate::app_state::{AppEvent, AppState, Selection};
22use crate::chat_actions::TITLE_LIMIT;
23use crate::data::{Directory, FolderKind};
24use crate::format;
25use crate::local_previews::LocalPreview;
26use crate::notice::truncated;
27use crate::sidebar_model::{
28 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
29 SectionInput, SectionKind, Step, build_sections, step_id,
30 visible_channel_ids,
31};
32use crate::theme;
33
34const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
35pub const SIDEBAR_WIDTH: f32 = 300.;
36const ROW_HEIGHT: f32 = 54.;
37const PINNED_CHANNEL_HEIGHT: f32 = 48.;
38const SECTION_HEIGHT: f32 = 30.;
39const SECTION_GAP: f32 = 4.;
40const HINT_HEIGHT: f32 = 26.;
41const SEE_MORE_HEIGHT: f32 = 28.;
42const FALLBACK_VIEWPORT: f32 = 900.;
43const CALLS_REFRESH: Duration = Duration::from_secs(30);
44const VIEWPORT_MARGIN: f32 = 300.;
45const AVATAR_SIZE: f32 = 36.;
46const PINNED_LABEL: &str = "Pinned";
47const TEAMS_LABEL: &str = "Teams";
48const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
49const TEAM_ROW_HEIGHT: f32 = 40.;
50const REVEAL_ROW_HEIGHT: f32 = 32.;
51const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
52const MENU_ICON_SIZE: f32 = 15.;
53const MUTED_ICON_SIZE: f32 = 13.;
54const NOTIFICATION_ICON_SIZE: f32 = 13.;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum SidebarTab {
58 Activity,
59 Chats,
60 Channels,
61 Calls,
62 Saved,
63}
64
65impl SidebarTab {
66 fn title(self) -> &'static str {
67 match self {
68 SidebarTab::Activity => "Activity",
69 SidebarTab::Chats => "Chats",
70 SidebarTab::Channels => "Channels",
71 SidebarTab::Calls => "Calls",
72 SidebarTab::Saved => "Saved",
73 }
74 }
75}
76
77#[derive(Clone)]
78struct DraggedChat {
79 id: String,
80 title: String,
81}
82
83struct DragGhost {
84 title: String,
85}
86
87impl Render for DragGhost {
88 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
89 div()
90 .px(px(12.))
91 .py(px(6.))
92 .rounded(px(8.))
93 .bg(theme::surface_raised())
94 .border_1()
95 .border_color(theme::accent())
96 .text_size(px(13.))
97 .text_color(theme::text())
98 .child(self.title.clone())
99 }
100}
101
102struct ChatMenuTarget {
103 id: String,
104 title: String,
105 pinned: bool,
106 unread: bool,
107 muted: bool,
108 is_group: bool,
109 member_count: usize,
110}
111
112#[derive(Clone)]
113struct MenuContext {
114 state: Entity<AppState>,
115 folders: Vec<(String, String)>,
116 favorites_id: Option<String>,
117}
118
119fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
120 icon(name, MENU_ICON_SIZE, theme::text_muted())
121}
122
123fn chat_menu(
124 popup: PopupMenu,
125 window: &mut Window,
126 cx: &mut Context<PopupMenu>,
127 context: &MenuContext,
128 target: &ChatMenuTarget,
129) -> PopupMenu {
130 let pinned = target.pinned;
131 let pin_state = context.state.clone();
132 let pin_id = target.id.clone();
133 let mut popup = popup.item(
134 PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" })
135 .icon(menu_icon(if pinned {
136 IconName::PinOff
137 } else {
138 IconName::Pin
139 }))
140 .on_click(move |_, _, cx| {
141 pin_state.update(cx, |state, cx| {
142 if pinned {
143 state.move_chat(&pin_id, None, cx);
144 } else {
145 state.pin_chat(&pin_id, cx);
146 }
147 });
148 }),
149 );
150 if !context.folders.is_empty() {
151 let folders = context.folders.clone();
152 let move_state = context.state.clone();
153 let move_id = target.id.clone();
154 popup = popup.submenu_with_icon(
155 Some(menu_icon(IconName::Folder)),
156 "Move to folder",
157 window,
158 cx,
159 move |submenu, _, _| {
160 folders.iter().fold(submenu, |submenu, (folder_id, name)| {
161 let (state, chat_id, folder_id) =
162 (move_state.clone(), move_id.clone(), folder_id.clone());
163 submenu.item(PopupMenuItem::new(name.clone()).on_click(move |_, _, cx| {
164 state.update(cx, |state, cx| {
165 state.move_chat(&chat_id, Some(&folder_id), cx)
166 });
167 }))
168 })
169 },
170 );
171 }
172 let read_state = context.state.clone();
173 let read_id = target.id.clone();
174 let unread = target.unread;
175 let mute_state = context.state.clone();
176 let mute_id = target.id.clone();
177 let muted = target.muted;
178 let hide_state = context.state.clone();
179 let hide_id = target.id.clone();
180 popup = popup
181 .separator()
182 .item(
183 PopupMenuItem::new(if unread {
184 "Mark as read"
185 } else {
186 "Mark as unread"
187 })
188 .icon(menu_icon(if unread {
189 IconName::MailOpen
190 } else {
191 IconName::Mail
192 }))
193 .on_click(move |_, _, cx| {
194 read_state.update(cx, |state, cx| {
195 if unread {
196 state.mark_chat_read(&read_id, cx);
197 } else {
198 state.mark_chat_unread(&read_id, cx);
199 }
200 });
201 }),
202 )
203 .item(
204 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
205 .icon(menu_icon(if muted {
206 IconName::Bell
207 } else {
208 IconName::BellOff
209 }))
210 .on_click(move |_, _, cx| {
211 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
212 }),
213 )
214 .separator()
215 .item(
216 PopupMenuItem::new("Hide")
217 .icon(menu_icon(IconName::EyeOff))
218 .on_click(move |_, _, cx| {
219 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
220 }),
221 );
222 if target.is_group {
223 let leave_state = context.state.clone();
224 let leave_id = target.id.clone();
225 let title = target.title.clone();
226 let member_count = target.member_count;
227 popup = popup.item(
228 PopupMenuItem::element(|_, _| {
229 div().text_color(theme::red_soft()).child("Leave chat...")
230 })
231 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
232 .on_click(move |_, window, cx| {
233 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
234 }),
235 );
236 }
237 popup
238}
239
240fn leave_description(member_count: usize) -> String {
241 let who = match member_count {
242 0 | 1 => "The other members".to_owned(),
243 2 => "The other member".to_owned(),
244 count => format!("The {} other members", count - 1),
245 };
246 let verb = if member_count == 2 { "sees" } else { "see" };
247 format!("{who} {verb} that you left. You can only come back if someone adds you.")
248}
249
250fn confirm_leave(
251 state: &Entity<AppState>,
252 chat_id: &str,
253 title: &str,
254 member_count: usize,
255 window: &mut Window,
256 cx: &mut App,
257) {
258 let state = state.clone();
259 let chat_id = chat_id.to_owned();
260 let heading = format!("Leave \"{}\"?", truncated(title, TITLE_LIMIT));
261 let description = leave_description(member_count);
262 window.open_alert_dialog(cx, move |alert, _, _| {
263 let state = state.clone();
264 let chat_id = chat_id.clone();
265 let cancel = Button::new("leave-cancel")
266 .label("Cancel")
267 .on_click(|_, window, cx| window.close_dialog(cx));
268 let leave = Button::new("leave-confirm")
269 .label("Leave")
270 .danger()
271 .on_click(move |_, window, cx| {
272 state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
273 window.close_dialog(cx);
274 });
275 alert
276 .title(heading.clone())
277 .description(description.clone())
278 .footer(DialogFooter::new().child(cancel).child(leave))
279 .on_ok(|_, _, _| false)
280 });
281}
282
283pub struct SidebarView {
284 state: Entity<AppState>,
285 tab: SidebarTab,
286 activity_panel: Entity<ActivityPanel>,
287 saved_panel: Entity<SavedPanel>,
288 collapsed_teams: HashSet<String>,
289 revealed_channel_teams: HashSet<String>,
290 hidden_teams_open: bool,
291 chats_scroll: ScrollHandle,
292 channels_scroll: ScrollHandle,
293 calls_scroll: ScrollHandle,
294 _subscription: Subscription,
295 _state_observation: Subscription,
296}
297
298fn preview_text(preview: &Preview) -> Option<(String, bool)> {
299 match preview {
300 Preview::Empty => None,
301 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
302 Preview::Typing(text) => Some((text.clone(), true)),
303 Preview::Text {
304 prefix: Some(prefix),
305 text,
306 } => Some((format!("{prefix}: {text}"), false)),
307 Preview::Text { prefix: None, text } => Some((text.clone(), false)),
308 }
309}
310
311fn preview_icon(text: &str) -> Option<IconName> {
312 match text.rsplit(": ").next()? {
313 "Image" => Some(IconName::Image),
314 "File" => Some(IconName::File),
315 _ => None,
316 }
317}
318
319fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
320 let row = h_flex()
321 .flex_1()
322 .min_w_0()
323 .overflow_hidden()
324 .gap(px(4.))
325 .items_center()
326 .text_size(px(12.5))
327 .text_color(color);
328 match preview {
329 LocalPreview::Draft(text) => row
330 .child(
331 div()
332 .flex_none()
333 .text_color(theme::accent_text())
334 .child("Draft:"),
335 )
336 .child(div().truncate().child(text.clone())),
337 LocalPreview::NotSent => row.child(
338 div()
339 .flex_none()
340 .text_color(theme::red_soft())
341 .child("Not sent"),
342 ),
343 }
344}
345
346impl SidebarView {
347 pub fn new(
348 state: Entity<AppState>,
349 activity_panel: Entity<ActivityPanel>,
350 saved_panel: Entity<SavedPanel>,
351 cx: &mut Context<Self>,
352 ) -> Self {
353 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
354 if matches!(event, AppEvent::Selection) {
355 if state.read(cx).new_chat {
356 this.tab = SidebarTab::Chats;
357 }
358 this.expand_team_of_selection(cx);
359 }
360 if matches!(
361 event,
362 AppEvent::Sidebar
363 | AppEvent::CallHistory
364 | AppEvent::Selection
365 | AppEvent::Directory
366 | AppEvent::Typing
367 | AppEvent::LocalPreviews
368 ) {
369 cx.notify();
370 }
371 });
372 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
373 let tab = if state.read(cx).start_on_channels {
374 SidebarTab::Channels
375 } else {
376 SidebarTab::Chats
377 };
378 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
379 cx.spawn(async move |this, cx| {
380 loop {
381 cx.background_executor().timer(CALLS_REFRESH).await;
382 let alive = this.update(cx, |view, cx| {
383 if view.tab == SidebarTab::Calls {
384 cx.notify();
385 }
386 });
387 if alive.is_err() {
388 break;
389 }
390 }
391 })
392 .detach();
393 SidebarView {
394 state,
395 tab,
396 activity_panel,
397 saved_panel,
398 collapsed_teams,
399 revealed_channel_teams: HashSet::new(),
400 hidden_teams_open: false,
401 chats_scroll: ScrollHandle::new(),
402 channels_scroll: ScrollHandle::new(),
403 calls_scroll: ScrollHandle::new(),
404 _subscription: subscription,
405 _state_observation: state_observation,
406 }
407 }
408
409 pub fn tab(&self) -> SidebarTab {
410 self.tab
411 }
412
413 pub fn show_activity(&mut self, cx: &mut Context<Self>) {
414 self.open_tab(SidebarTab::Activity, cx);
415 }
416
417 pub fn show_chats(&mut self, cx: &mut Context<Self>) {
418 self.open_tab(SidebarTab::Chats, cx);
419 }
420
421 pub fn show_channels(&mut self, cx: &mut Context<Self>) {
422 self.open_tab(SidebarTab::Channels, cx);
423 }
424
425 pub fn show_calls(&mut self, cx: &mut Context<Self>) {
426 self.open_tab(SidebarTab::Calls, cx);
427 }
428
429 pub fn show_saved(&mut self, cx: &mut Context<Self>) {
430 self.open_tab(SidebarTab::Saved, cx);
431 }
432
433 pub fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
434 self.tab = tab;
435 match tab {
436 SidebarTab::Calls => self.state.update(cx, |state, cx| {
437 state.refresh_call_history(cx);
438 state.refresh_calendar(cx);
439 }),
440 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
441 _ => {}
442 }
443 cx.notify();
444 }
445
446 pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {
447 let selection = match self.tab {
448 SidebarTab::Chats => self
449 .state
450 .read(cx)
451 .adjacent_chat_id(step)
452 .map(Selection::Chat),
453 SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),
454 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,
455 };
456 if let Some(selection) = selection {
457 self.state.update(cx, |state, cx| state.select(selection, cx));
458 }
459 }
460
461 fn adjacent_channel_id(&self, step: Step, cx: &mut Context<Self>) -> Option<String> {
462 let state = self.state.read(cx);
463 let selected_channel = match &state.selection {
464 Some(Selection::Channel(channel_id)) => Some(channel_id.as_str()),
465 _ => None,
466 };
467 let input = ChannelOrderInput {
468 teams: &state.sidebar.teams,
469 pinned_ids: &state.directory.pinned_channels,
470 collapsed_teams: &self.collapsed_teams,
471 revealed_channel_teams: &self.revealed_channel_teams,
472 hidden_teams_open: self.hidden_teams_open,
473 selected_channel,
474 };
475 step_id(&visible_channel_ids(&input), selected_channel, step)
476 }
477
478 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
479 let state = self.state.read(cx);
480 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
481 return;
482 };
483 let team_id = state
484 .sidebar
485 .teams
486 .iter()
487 .find(|entry| {
488 entry
489 .channels
490 .iter()
491 .any(|channel| channel.id == channel_id)
492 })
493 .map(|entry| entry.team.id.clone());
494 if let Some(team_id) = team_id
495 && self.collapsed_teams.remove(&team_id)
496 {
497 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
498 }
499 }
500
501 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
502 let active = self.state.read(cx).new_chat;
503 div()
504 .id("new-chat")
505 .size(px(NEW_CHAT_BUTTON_SIZE))
506 .flex_none()
507 .flex()
508 .items_center()
509 .justify_center()
510 .rounded(px(8.))
511 .bg(theme::surface_raised())
512 .cursor_pointer()
513 .when(active, |button| button.bg(theme::popup_hover()))
514 .hover(|button| button.bg(theme::popup_hover()))
515 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
516 .child(icon(IconName::Pencil, 16., theme::text_soft()))
517 .on_click(cx.listener(|this, _, _, cx| {
518 this.state.update(cx, |state, cx| state.start_new_chat(cx));
519 }))
520 }
521
522 fn draft_row(&self) -> impl IntoElement {
523 h_flex()
524 .id("new-chat-draft")
525 .mx(px(6.))
526 .h(px(ROW_HEIGHT))
527 .px(px(10.))
528 .gap(px(12.))
529 .items_center()
530 .rounded(px(8.))
531 .bg(theme::surface_raised())
532 .child(
533 div()
534 .size(px(AVATAR_SIZE))
535 .flex_none()
536 .flex()
537 .items_center()
538 .justify_center()
539 .rounded_full()
540 .bg(theme::border_strong())
541 .child(icon(IconName::Pencil, 16., theme::text())),
542 )
543 .child(
544 v_flex()
545 .flex_1()
546 .min_w_0()
547 .gap(px(2.))
548 .child(
549 div()
550 .truncate()
551 .text_size(px(14.))
552 .text_color(theme::text())
553 .child("New chat"),
554 )
555 .child(
556 div()
557 .truncate()
558 .text_size(px(12.5))
559 .text_color(theme::text_muted())
560 .child("Draft"),
561 ),
562 )
563 }
564
565 fn section_header(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
566 let drop_target = matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)
567 .then(|| section.id.clone());
568 let toggle_id = section.id.clone();
569 h_flex()
570 .id(SharedString::from(format!("section-{}", section.id)))
571 .h(px(SECTION_HEIGHT))
572 .mt(px(SECTION_GAP))
573 .mx(px(6.))
574 .px(px(10.))
575 .gap(px(6.))
576 .items_center()
577 .rounded(px(6.))
578 .cursor_pointer()
579 .hover(|header| header.bg(theme::row_hover()))
580 .drag_over::<DraggedChat>(|style, _, _, _| {
581 style
582 .bg(theme::drop_background())
583 .border_1()
584 .border_dashed()
585 .border_color(theme::accent())
586 })
587 .on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
588 let target = drop_target.clone();
589 this.state.update(cx, |state, cx| {
590 state.move_chat(&dragged.id, target.as_deref(), cx)
591 });
592 }))
593 .child(icon(
594 if section.collapsed {
595 IconName::ChevronRight
596 } else {
597 IconName::ChevronDown
598 },
599 12.,
600 theme::text_muted(),
601 ))
602 .child(
603 div()
604 .flex_1()
605 .min_w_0()
606 .truncate()
607 .text_size(px(12.))
608 .font_weight(FontWeight::SEMIBOLD)
609 .text_color(theme::text_soft())
610 .child(section.name.clone()),
611 )
612 .when(section.collapsed && section.unread_chats > 0, |header| {
613 header.child(count_badge(section.unread_chats, false))
614 })
615 .child(
616 div()
617 .text_size(px(11.))
618 .text_color(theme::text_faint())
619 .child(section.count.to_string()),
620 )
621 .on_click(cx.listener(move |this, _, _, cx| {
622 let id = toggle_id.clone();
623 this.state
624 .update(cx, |state, cx| state.toggle_collapsed(&id, cx));
625 }))
626 }
627
628 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
629 let toggle_id = section.id.clone();
630 let label = if section.hidden_count > 0 {
631 format!("See more ({})", section.hidden_count)
632 } else {
633 "See less".to_owned()
634 };
635 div()
636 .id(SharedString::from(format!("see-more-{}", section.id)))
637 .mx(px(6.))
638 .pl(px(10. + AVATAR_SIZE + 12.))
639 .h(px(SEE_MORE_HEIGHT))
640 .flex()
641 .items_center()
642 .rounded(px(6.))
643 .cursor_pointer()
644 .text_size(px(12.5))
645 .text_color(theme::accent_text())
646 .hover(|row| row.bg(theme::row_hover()))
647 .child(label)
648 .on_click(cx.listener(move |this, _, _, cx| {
649 let id = toggle_id.clone();
650 this.state
651 .update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
652 }))
653 }
654
655 fn chat_row(
656 &self,
657 item: &ChatItem,
658 selected: bool,
659 local_preview: Option<&LocalPreview>,
660 directory: &Directory,
661 menu: &MenuContext,
662 ) -> AnyElement {
663 let ring = if selected {
664 theme::surface_raised()
665 } else {
666 theme::surface()
667 };
668 let unread = item.unread.is_unread();
669 let presence = item
670 .presence_user
671 .as_deref()
672 .map(|user_id| directory.presence_of(user_id));
673 let avatar = spec_avatar(directory, &item.avatar, AVATAR_SIZE, ring);
674 let avatar = match presence {
675 Some(kind) => with_presence(avatar, kind, AVATAR_SIZE, ring).into_any_element(),
676 None => avatar,
677 };
678 let name = div()
679 .flex_1()
680 .min_w_0()
681 .truncate()
682 .text_size(px(14.))
683 .font_weight(if unread {
684 FontWeight::BOLD
685 } else {
686 FontWeight::NORMAL
687 })
688 .text_color(theme::text())
689 .child(item.title.clone());
690 let time = h_flex()
691 .flex_none()
692 .gap(px(4.))
693 .items_center()
694 .text_size(px(11.))
695 .text_color(if unread {
696 theme::accent_text()
697 } else {
698 theme::text_muted()
699 })
700 .when(item.muted, |time| {
701 time.child(icon(
702 IconName::BellOff,
703 MUTED_ICON_SIZE,
704 theme::text_faint(),
705 ))
706 })
707 .child(item.time_label.clone());
708 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
709 theme::accent_text()
710 } else if item.muted {
711 theme::text_faint()
712 } else if unread {
713 theme::text_strong()
714 } else {
715 theme::text_muted()
716 };
717 let preview = match local_preview {
718 Some(local) => Some(local_preview_row(local, preview_color)),
719 None => preview_text(&item.preview).map(|(text, italic)| {
720 let glyph = preview_icon(&text);
721 h_flex()
722 .flex_1()
723 .min_w_0()
724 .overflow_hidden()
725 .gap(px(4.))
726 .items_center()
727 .text_size(px(12.5))
728 .when(italic, |preview| preview.italic())
729 .text_color(preview_color)
730 .children(glyph.map(|name| icon(name, 12., preview_color)))
731 .child(div().truncate().child(text))
732 }),
733 };
734 let lines = v_flex()
735 .flex_1()
736 .min_w_0()
737 .gap(px(2.))
738 .child(
739 h_flex()
740 .gap(px(8.))
741 .items_baseline()
742 .child(name)
743 .child(time),
744 )
745 .child(
746 h_flex()
747 .h(px(18.))
748 .gap(px(8.))
749 .items_center()
750 .child(preview.unwrap_or_else(|| div().flex_1()))
751 .children(unread_marker(item.unread, item.muted)),
752 );
753 let state = self.state.clone();
754 let chat_id = item.id.clone();
755 let dragged = DraggedChat {
756 id: item.id.clone(),
757 title: item.title.clone(),
758 };
759 let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;
760 let menu_context = menu.clone();
761 let target = ChatMenuTarget {
762 id: item.id.clone(),
763 title: item.title.clone(),
764 pinned,
765 unread,
766 muted: item.muted,
767 is_group: item.is_group,
768 member_count: item.member_count,
769 };
770 h_flex()
771 .id(SharedString::from(format!("chat-{}", item.id)))
772 .mx(px(6.))
773 .h(px(ROW_HEIGHT))
774 .px(px(10.))
775 .gap(px(12.))
776 .items_center()
777 .rounded(px(8.))
778 .cursor_pointer()
779 .when(selected, |row| row.bg(theme::surface_raised()))
780 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
781 .on_drag(dragged, |dragged, _, _, cx| {
782 let title = dragged.title.clone();
783 cx.new(|_| DragGhost { title })
784 })
785 .child(avatar)
786 .child(lines)
787 .on_click(move |_, _, cx| {
788 let selection = Selection::Chat(chat_id.clone());
789 state.update(cx, |state, cx| state.select(selection, cx));
790 })
791 .context_menu(move |popup, window, cx| {
792 chat_menu(popup, window, cx, &menu_context, &target)
793 })
794 .into_any_element()
795 }
796
797 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
798 let (sections, menu, local_previews) = {
799 let state = self.state.read(cx);
800 let now = Utc::now();
801 let offset = Local::now().offset().fix();
802 let input = SectionInput {
803 chats: &state.sidebar.chats,
804 directory: &state.directory,
805 collapsed: &state.collapsed,
806 expanded_lists: &state.expanded_lists,
807 typing: &state.typing,
808 now,
809 offset,
810 };
811 let sections = build_sections(&input);
812 let menu = MenuContext {
813 state: self.state.clone(),
814 folders: state
815 .directory
816 .folders
817 .iter()
818 .filter(|folder| folder.kind == FolderKind::UserCreated)
819 .map(|folder| (folder.id.clone(), folder.name.clone()))
820 .collect(),
821 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
822 };
823 (sections, menu, state.local_previews.clone())
824 };
825
826 let top = -f32::from(self.chats_scroll.offset().y);
827 let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
828 let height = if measured > 1. {
829 measured
830 } else {
831 window_height.max(FALLBACK_VIEWPORT)
832 };
833 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
834
835 let (selected, drafting) = {
836 let state = self.state.read(cx);
837 (
838 state.selection.clone().filter(|_| !state.new_chat),
839 state.new_chat,
840 )
841 };
842 let mut faces: Vec<String> = Vec::new();
843 let mut presence_users: Vec<String> = Vec::new();
844 let mut y = 0.;
845 let mut list = v_flex().w_full().pb(px(12.));
846 let mut skipped_height = 0.;
847 let directory_state = self.state.clone();
848 if drafting {
849 list = list.child(self.draft_row());
850 y += ROW_HEIGHT;
851 }
852 for section in &sections {
853 list = with_spacer(list, &mut skipped_height);
854 list = list.child(self.section_header(section, cx));
855 y += SECTION_GAP + SECTION_HEIGHT;
856 if section.collapsed {
857 continue;
858 }
859 for item in &section.items {
860 let on_screen = y + ROW_HEIGHT >= visible_from && y <= visible_to;
861 if on_screen {
862 collect_faces(&item.avatar, &mut faces);
863 presence_users.extend(item.presence_user.clone());
864 }
865 if on_screen {
866 list = with_spacer(list, &mut skipped_height);
867 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
868 let directory = &directory_state.read(cx).directory;
869 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
870 list = list.child(self.chat_row(
871 item,
872 is_selected,
873 local_preview,
874 directory,
875 &menu,
876 ));
877 } else {
878 skipped_height += ROW_HEIGHT;
879 }
880 y += ROW_HEIGHT;
881 }
882 if section.hidden_count > 0 || section.list_expanded {
883 list = with_spacer(list, &mut skipped_height);
884 list = list.child(self.see_more_row(section, cx));
885 y += SEE_MORE_HEIGHT;
886 }
887 if section.show_empty_hint {
888 list = with_spacer(list, &mut skipped_height);
889 list = list.child(
890 div()
891 .ml(px(16.))
892 .mr(px(16.))
893 .h(px(HINT_HEIGHT))
894 .flex()
895 .items_center()
896 .text_size(px(12.))
897 .italic()
898 .text_color(theme::text_faint())
899 .child(EMPTY_FOLDER_HINT),
900 );
901 y += HINT_HEIGHT;
902 }
903 }
904 list = with_spacer(list, &mut skipped_height);
905 self.request_lazy_data(faces, presence_users, cx);
906 div()
907 .id("chats-scroll")
908 .flex_1()
909 .min_h_0()
910 .overflow_y_scroll()
911 .track_scroll(&self.chats_scroll)
912 .child(list)
913 .into_any_element()
914 }
915
916 fn request_lazy_data(
917 &self,
918 faces: Vec<String>,
919 presence_users: Vec<String>,
920 cx: &mut Context<Self>,
921 ) {
922 if faces.is_empty() && presence_users.is_empty() {
923 return;
924 }
925 let state = self.state.clone();
926 cx.defer(move |cx| {
927 state.update(cx, |state, cx| {
928 state.request_avatars(faces, cx);
929 state.request_presence(presence_users, cx);
930 });
931 });
932 }
933
934 fn channel_row(
935 &self,
936 channel_id: &str,
937 team: &TeamRecord,
938 channel: &ChannelRecord,
939 selected: bool,
940 notifications: ChannelNotifications,
941 ) -> AnyElement {
942 let unread = channel.unread;
943 let state = self.state.clone();
944 let menu_state = self.state.clone();
945 let menu_channel_id = channel_id.to_owned();
946 let selection = Selection::Channel(channel_id.to_owned());
947 let now = Utc::now();
948 let offset = Local::now().offset().fix();
949 let time = channel
950 .last_message_at
951 .map(|time| {
952 format::list_time_label(time, now.with_timezone(&offset).date_naive(), offset)
953 })
954 .unwrap_or_default();
955 h_flex()
956 .id(SharedString::from(format!("pinned-{channel_id}")))
957 .mx(px(6.))
958 .h(px(PINNED_CHANNEL_HEIGHT))
959 .px(px(10.))
960 .gap(px(12.))
961 .items_center()
962 .rounded(px(8.))
963 .cursor_pointer()
964 .when(selected, |row| row.bg(theme::surface_raised()))
965 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
966 .child(square_avatar(&team.name, &team.id, 28., 7.))
967 .child(
968 v_flex()
969 .flex_1()
970 .min_w_0()
971 .gap(px(1.))
972 .child(
973 h_flex()
974 .gap(px(8.))
975 .items_baseline()
976 .child(
977 div()
978 .flex_1()
979 .min_w_0()
980 .truncate()
981 .text_size(px(13.5))
982 .font_weight(if unread {
983 FontWeight::BOLD
984 } else {
985 FontWeight::NORMAL
986 })
987 .text_color(theme::text())
988 .child(format!("{} / {}", team.name, channel.name)),
989 )
990 .children(notification_badge(notifications.level))
991 .child(
992 div()
993 .flex_none()
994 .text_size(px(11.))
995 .text_color(if unread {
996 theme::accent_text()
997 } else {
998 theme::text_muted()
999 })
1000 .child(time),
1001 ),
1002 )
1003 .child(
1004 h_flex()
1005 .gap(px(8.))
1006 .items_center()
1007 .child(
1008 div()
1009 .flex_1()
1010 .min_w_0()
1011 .truncate()
1012 .text_size(px(12.))
1013 .text_color(theme::text_muted())
1014 .child(team.name.clone()),
1015 )
1016 .when(unread, |line| line.child(dot(7.))),
1017 ),
1018 )
1019 .on_click(move |_, _, cx| {
1020 let selection = selection.clone();
1021 state.update(cx, |state, cx| state.select(selection, cx));
1022 })
1023 .context_menu(move |popup, window, cx| {
1024 channel_menu(
1025 popup,
1026 window,
1027 cx,
1028 menu_state.clone(),
1029 &menu_channel_id,
1030 notifications,
1031 )
1032 })
1033 .into_any_element()
1034 }
1035
1036 fn plain_header(&self, label: &str) -> impl IntoElement {
1037 div()
1038 .h(px(SECTION_HEIGHT))
1039 .mt(px(SECTION_GAP))
1040 .px(px(16.))
1041 .flex()
1042 .items_center()
1043 .text_size(px(12.))
1044 .font_weight(FontWeight::SEMIBOLD)
1045 .text_color(theme::text_soft())
1046 .child(label.to_owned())
1047 }
1048
1049 fn team_block(
1050 &self,
1051 mut list: Div,
1052 entry: &SidebarTeam,
1053 selected: Option<&Selection>,
1054 cx: &mut Context<Self>,
1055 ) -> Div {
1056 let team_id = entry.team.id.clone();
1057 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1058 let unread = entry.channels.iter().any(|channel| channel.unread);
1059 let toggle_id = team_id.clone();
1060 list = list.child(
1061 h_flex()
1062 .id(SharedString::from(format!("team-{team_id}")))
1063 .mx(px(6.))
1064 .h(px(TEAM_ROW_HEIGHT))
1065 .px(px(10.))
1066 .gap(px(8.))
1067 .items_center()
1068 .rounded(px(8.))
1069 .cursor_pointer()
1070 .hover(|row| row.bg(theme::row_hover()))
1071 .child(icon(
1072 if expanded {
1073 IconName::ChevronDown
1074 } else {
1075 IconName::ChevronRight
1076 },
1077 14.,
1078 theme::text_muted(),
1079 ))
1080 .child(square_avatar(&entry.team.name, &entry.team.id, 28., 7.))
1081 .child(
1082 div()
1083 .flex_1()
1084 .min_w_0()
1085 .truncate()
1086 .text_size(px(13.5))
1087 .font_weight(if unread || expanded {
1088 FontWeight::SEMIBOLD
1089 } else {
1090 FontWeight::NORMAL
1091 })
1092 .text_color(theme::text())
1093 .child(entry.team.name.clone()),
1094 )
1095 .when(unread && !expanded, |row| row.child(dot(7.)))
1096 .on_click(cx.listener(move |this, _, _, cx| {
1097 if !this.collapsed_teams.remove(&toggle_id) {
1098 this.collapsed_teams.insert(toggle_id.clone());
1099 }
1100 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1101 cx.notify();
1102 })),
1103 );
1104 if !expanded {
1105 return list;
1106 }
1107 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1108 let is_selected =
1109 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1110 for channel in entry
1111 .channels
1112 .iter()
1113 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1114 {
1115 list = list.child(self.team_channel_row(
1116 channel,
1117 is_selected(channel),
1118 entry.channel_notifications(&channel.id),
1119 ));
1120 }
1121 let hidden: Vec<&ChannelRecord> = entry
1122 .channels
1123 .iter()
1124 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1125 .collect();
1126 if hidden.is_empty() {
1127 return list;
1128 }
1129 let revealed = self.revealed_channel_teams.contains(&team_id);
1130 let toggle_id = team_id.clone();
1131 list = list.child(self.reveal_row(
1132 SharedString::from(format!("hidden-channels-{team_id}")),
1133 hidden_channels_label(hidden.len()),
1134 revealed,
1135 40.,
1136 cx.listener(move |this, _, _, cx| {
1137 if !this.revealed_channel_teams.remove(&toggle_id) {
1138 this.revealed_channel_teams.insert(toggle_id.clone());
1139 }
1140 cx.notify();
1141 }),
1142 ));
1143 if revealed {
1144 for channel in hidden {
1145 list = list.child(self.team_channel_row(
1146 channel,
1147 false,
1148 entry.channel_notifications(&channel.id),
1149 ));
1150 }
1151 }
1152 list
1153 }
1154
1155 fn reveal_row(
1156 &self,
1157 id: SharedString,
1158 label: String,
1159 open: bool,
1160 indent: f32,
1161 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1162 ) -> impl IntoElement {
1163 h_flex()
1164 .id(id)
1165 .mx(px(6.))
1166 .h(px(REVEAL_ROW_HEIGHT))
1167 .pl(px(indent))
1168 .pr(px(10.))
1169 .gap(px(8.))
1170 .items_center()
1171 .rounded(px(8.))
1172 .cursor_pointer()
1173 .hover(|row| row.bg(theme::row_hover()))
1174 .child(icon(
1175 if open {
1176 IconName::ChevronDown
1177 } else {
1178 IconName::ChevronRight
1179 },
1180 12.,
1181 theme::text_faint(),
1182 ))
1183 .child(
1184 div()
1185 .text_size(px(12.5))
1186 .text_color(theme::text_muted())
1187 .child(label),
1188 )
1189 .on_click(on_click)
1190 }
1191
1192 fn team_channel_row(
1193 &self,
1194 channel: &ChannelRecord,
1195 is_selected: bool,
1196 notifications: ChannelNotifications,
1197 ) -> impl IntoElement {
1198 let state = self.state.clone();
1199 let menu_state = self.state.clone();
1200 let menu_channel_id = channel.id.clone();
1201 let selection = Selection::Channel(channel.id.clone());
1202 h_flex()
1203 .id(SharedString::from(format!("channel-{}", channel.id)))
1204 .mx(px(6.))
1205 .h(px(TEAM_ROW_HEIGHT))
1206 .pl(px(40.))
1207 .pr(px(10.))
1208 .gap(px(8.))
1209 .items_center()
1210 .rounded(px(8.))
1211 .cursor_pointer()
1212 .when(is_selected, |row| row.bg(theme::surface_raised()))
1213 .when(!is_selected, |row| {
1214 row.hover(|row| row.bg(theme::row_hover()))
1215 })
1216 .child(
1217 div()
1218 .w(px(14.))
1219 .flex()
1220 .justify_center()
1221 .text_size(px(15.))
1222 .text_color(theme::text_faint())
1223 .child("#"),
1224 )
1225 .child(
1226 div()
1227 .flex_1()
1228 .min_w_0()
1229 .truncate()
1230 .text_size(px(13.5))
1231 .font_weight(if channel.unread {
1232 FontWeight::BOLD
1233 } else {
1234 FontWeight::NORMAL
1235 })
1236 .text_color(theme::text())
1237 .child(channel.name.clone()),
1238 )
1239 .children(notification_badge(notifications.level))
1240 .when(channel.unread, |row| row.child(dot(7.)))
1241 .on_click(move |_, _, cx| {
1242 let selection = selection.clone();
1243 state.update(cx, |state, cx| state.select(selection, cx));
1244 })
1245 .context_menu(move |popup, window, cx| {
1246 channel_menu(
1247 popup,
1248 window,
1249 cx,
1250 menu_state.clone(),
1251 &menu_channel_id,
1252 notifications,
1253 )
1254 })
1255 }
1256
1257 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1258 let (sidebar, pinned_ids, selected) = {
1259 let state = self.state.read(cx);
1260 (
1261 state.sidebar.clone(),
1262 state.directory.pinned_channels.clone(),
1263 state.selection.clone().filter(|_| !state.new_chat),
1264 )
1265 };
1266 let mut list = v_flex().w_full().pb(px(12.));
1267 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1268 .iter()
1269 .filter_map(|id| {
1270 sidebar.teams.iter().find_map(|entry| {
1271 entry
1272 .channels
1273 .iter()
1274 .find(|channel| &channel.id == id)
1275 .map(|channel| (entry, channel))
1276 })
1277 })
1278 .collect();
1279 if !pinned.is_empty() {
1280 list = list.child(self.plain_header(PINNED_LABEL));
1281 for (entry, channel) in pinned {
1282 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1283 list = list.child(self.channel_row(
1284 &channel.id,
1285 &entry.team,
1286 channel,
1287 is_selected,
1288 entry.channel_notifications(&channel.id),
1289 ));
1290 }
1291 }
1292 list = list.child(self.plain_header(TEAMS_LABEL));
1293 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1294 sidebar.teams.iter().partition(|entry| !entry.hidden);
1295 for entry in shown_teams {
1296 list = self.team_block(list, entry, selected.as_ref(), cx);
1297 }
1298 if !hidden_teams.is_empty() {
1299 let holds_selection = hidden_teams
1300 .iter()
1301 .any(|entry| team_holds(entry, selected.as_ref()));
1302 let open = self.hidden_teams_open || holds_selection;
1303 list = list.child(self.reveal_row(
1304 "hidden-teams".into(),
1305 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1306 open,
1307 10.,
1308 cx.listener(|this, _, _, cx| {
1309 this.hidden_teams_open = !this.hidden_teams_open;
1310 cx.notify();
1311 }),
1312 ));
1313 if open {
1314 for entry in hidden_teams {
1315 list = self.team_block(list, entry, selected.as_ref(), cx);
1316 }
1317 }
1318 }
1319 div()
1320 .id("channels-scroll")
1321 .flex_1()
1322 .min_h_0()
1323 .overflow_y_scroll()
1324 .track_scroll(&self.channels_scroll)
1325 .child(list)
1326 .into_any_element()
1327 }
1328}
1329
1330fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1331 let name = match level {
1332 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1333 ChannelNotificationLevel::Off => IconName::BellOff,
1334 ChannelNotificationLevel::Feed => return None,
1335 };
1336 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1337}
1338
1339fn channel_menu(
1340 popup: PopupMenu,
1341 window: &mut Window,
1342 cx: &mut Context<PopupMenu>,
1343 state: Entity<AppState>,
1344 channel_id: &str,
1345 notifications: ChannelNotifications,
1346) -> PopupMenu {
1347 let channel_id = channel_id.to_owned();
1348 popup.submenu_with_icon(
1349 Some(menu_icon(IconName::Bell)),
1350 "Notifications",
1351 window,
1352 cx,
1353 move |submenu, _, _| {
1354 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1355 let (state, channel_id) = (state.clone(), channel_id.clone());
1356 PopupMenuItem::new(label)
1357 .checked(notifications.level == level)
1358 .on_click(move |_, _, cx| {
1359 let changed = ChannelNotifications {
1360 level,
1361 include_replies: notifications.include_replies
1362 && level != ChannelNotificationLevel::Off,
1363 };
1364 state.update(cx, |state, cx| {
1365 state.set_channel_notifications(&channel_id, changed, cx)
1366 });
1367 })
1368 };
1369 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1370 submenu
1371 .item(level_item(
1372 "Banner and activity",
1373 ChannelNotificationLevel::BannerAndFeed,
1374 ))
1375 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1376 .item(level_item("Off", ChannelNotificationLevel::Off))
1377 .separator()
1378 .item(
1379 PopupMenuItem::new("Include thread replies")
1380 .checked(notifications.include_replies)
1381 .disabled(notifications.level == ChannelNotificationLevel::Off)
1382 .on_click(move |_, _, cx| {
1383 let changed = ChannelNotifications {
1384 level: notifications.level,
1385 include_replies: !notifications.include_replies,
1386 };
1387 replies_state.update(cx, |state, cx| {
1388 state.set_channel_notifications(&replies_id, changed, cx)
1389 });
1390 }),
1391 )
1392 },
1393 )
1394}
1395
1396fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1397 !collapsed_teams.contains(team_id)
1398}
1399
1400fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1401 store
1402 .meta(COLLAPSED_TEAMS_META_KEY)
1403 .ok()
1404 .flatten()
1405 .map(|value| parse_collapsed_teams(&value))
1406 .unwrap_or_default()
1407}
1408
1409fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1410 let _ = store.set_meta(
1411 COLLAPSED_TEAMS_META_KEY,
1412 &serialize_collapsed_teams(collapsed_teams),
1413 );
1414}
1415
1416fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1417 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1418 team_ids.sort_unstable();
1419 serde_json::to_string(&team_ids).unwrap_or_default()
1420}
1421
1422fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1423 serde_json::from_str(value).unwrap_or_default()
1424}
1425
1426fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1427 entry
1428 .channels
1429 .iter()
1430 .any(|channel| selected == Some(&Selection::Channel(channel.id.clone())))
1431}
1432
1433fn hidden_channels_label(count: usize) -> String {
1434 if count == 1 {
1435 "1 hidden channel".to_owned()
1436 } else {
1437 format!("{count} hidden channels")
1438 }
1439}
1440
1441fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1442 match spec {
1443 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1444 AvatarSpec::Pair(first, second) => {
1445 faces.extend(first.user_id.clone());
1446 faces.extend(second.user_id.clone());
1447 }
1448 }
1449}
1450
1451fn with_spacer(list: Div, skipped_height: &mut f32) -> Div {
1452 let height = std::mem::take(skipped_height);
1453 if height > 0. {
1454 list.child(div().h(px(height)).flex_none())
1455 } else {
1456 list
1457 }
1458}
1459
1460impl Render for SidebarView {
1461 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1462 let window_height = f32::from(window.viewport_size().height);
1463 let body = match self.tab {
1464 SidebarTab::Activity => self.activity_panel.clone().into_any_element(),
1465 SidebarTab::Chats => self.chats_body(window_height, cx),
1466 SidebarTab::Channels => self.channels_body(cx),
1467 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1468 SidebarTab::Saved => self.saved_panel.clone().into_any_element(),
1469 };
1470 let header = match self.tab {
1471 SidebarTab::Chats => Some(page_header(self.tab.title()).child(self.new_chat_button(cx))),
1472 SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),
1473 SidebarTab::Activity | SidebarTab::Saved => None,
1474 };
1475 v_flex()
1476 .w(px(SIDEBAR_WIDTH))
1477 .h_full()
1478 .flex_none()
1479 .bg(theme::surface())
1480 .rounded(px(10.))
1481 .overflow_hidden()
1482 .children(header)
1483 .child(body)
1484 }
1485}
1486
1487#[cfg(test)]
1488mod tests {
1489 use std::collections::HashSet;
1490
1491 use super::{
1492 leave_description, parse_collapsed_teams, serialize_collapsed_teams, team_expanded,
1493 };
1494
1495 #[test]
1496 fn teams_start_expanded() {
1497 assert!(team_expanded("t1", &HashSet::new()));
1498 }
1499
1500 #[test]
1501 fn collapsed_team_stays_closed() {
1502 let collapsed = HashSet::from(["t1".to_owned()]);
1503 assert!(!team_expanded("t1", &collapsed));
1504 assert!(team_expanded("t2", &collapsed));
1505 }
1506
1507 #[test]
1508 fn collapsed_teams_round_trip_as_json() {
1509 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1510 let json = serialize_collapsed_teams(&collapsed);
1511 assert_eq!(json, r#"["a","b"]"#);
1512 assert_eq!(parse_collapsed_teams(&json), collapsed);
1513 assert!(parse_collapsed_teams("garbage").is_empty());
1514 }
1515
1516 #[test]
1517 fn leave_text_counts_the_other_members() {
1518 assert_eq!(
1519 leave_description(4),
1520 "The 3 other members see that you left. You can only come back if someone adds you."
1521 );
1522 assert!(leave_description(2).starts_with("The other member sees"));
1523 assert!(leave_description(0).starts_with("The other members see"));
1524 }
1525}