BlueGit

ict rusty-teams

Files

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

sidebar.rs

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