BlueGit

ict rusty-teams

Files

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

sidebar.rs

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