BlueGit

ict rusty-teams

Files

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

sidebar.rs

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