BlueGit

ict rusty-teams

Files

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

sidebar.rs

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