BlueGit

ict rusty-teams

Files

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

sidebar.rs

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