BlueGit

ict rusty-teams

Files

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

sidebar.rs

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