BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 62.6 KiB Download Raw
1use std::cell::Cell;
2use std::collections::HashSet;
3use std::time::Duration;
4
5use chrono::{Local, Offset, Utc};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::dialog::DialogFooter;
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
15};
16
17use super::activity_panel::ActivityPanel;
18use super::avatar::{spec_avatar, square_avatar, with_presence};
19use super::calls_tab::calls_body;
20use super::saved_panel::SavedPanel;
21use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
22use super::widgets::{count_badge, dot, icon, page_header, unread_marker};
23use crate::app_state::{AppEvent, AppState, Selection};
24use crate::chat_actions::TITLE_LIMIT;
25use crate::data::{Directory, is_pending_folder};
26use crate::format;
27use crate::local_previews::LocalPreview;
28use crate::notice::truncated;
29use crate::sidebar_model::{
30 AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
31 SectionInput, SectionKind, Step, build_sections, older_chats_trigger_resets, step_id,
32 visible_channel_ids, wants_older_chats,
33};
34use crate::theme;
35
36const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
37pub const SIDEBAR_WIDTH: f32 = 300.;
38const ROW_HEIGHT: f32 = 54.;
39const PROPOSAL_DOT_SIZE: f32 = 8.;
40const PINNED_CHANNEL_HEIGHT: f32 = 48.;
41const SECTION_HEIGHT: f32 = 30.;
42const SECTION_GAP: f32 = 4.;
43const HINT_HEIGHT: f32 = 26.;
44const SEE_MORE_HEIGHT: f32 = 28.;
45const LOADING_OLDER_LABEL: &str = "Loading older chats";
46const FALLBACK_VIEWPORT: f32 = 900.;
47const CALLS_REFRESH: Duration = Duration::from_secs(30);
48const VIEWPORT_MARGIN: f32 = 300.;
49const AVATAR_SIZE: f32 = 36.;
50const PINNED_LABEL: &str = "Pinned";
51const TEAMS_LABEL: &str = "Teams";
52const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
53const TEAM_ROW_HEIGHT: f32 = 40.;
54const REVEAL_ROW_HEIGHT: f32 = 32.;
55const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
56const MENU_ICON_SIZE: f32 = 15.;
57const MUTED_ICON_SIZE: f32 = 13.;
58const NOTIFICATION_ICON_SIZE: f32 = 13.;
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum SidebarTab {
62 Activity,
63 Chats,
64 Channels,
65 Calls,
66 Saved,
67}
68
69impl SidebarTab {
70 fn title(self) -> &'static str {
71 match self {
72 SidebarTab::Activity => "Activity",
73 SidebarTab::Chats => "Chats",
74 SidebarTab::Channels => "Channels",
75 SidebarTab::Calls => "Calls",
76 SidebarTab::Saved => "Saved",
77 }
78 }
79}
80
81#[derive(Clone)]
82struct DraggedChat {
83 id: String,
84 title: String,
85}
86
87struct DragGhost {
88 title: String,
89}
90
91impl Render for DragGhost {
92 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
93 div()
94 .px(px(12.))
95 .py(px(6.))
96 .rounded(px(8.))
97 .bg(theme::surface_raised())
98 .border_1()
99 .border_color(theme::accent())
100 .text_size(px(13.))
101 .text_color(theme::text())
102 .child(self.title.clone())
103 }
104}
105
106struct ChatMenuTarget {
107 id: String,
108 title: String,
109 folder_id: Option<String>,
110 unread: bool,
111 muted: bool,
112 is_group: bool,
113 member_count: usize,
114}
115
116#[derive(Clone)]
117struct MenuContext {
118 state: Entity<AppState>,
119 folders: Vec<(String, String)>,
120}
121
122fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
123 icon(name, MENU_ICON_SIZE, theme::text_muted())
124}
125
126fn chat_menu(
127 popup: PopupMenu,
128 window: &mut Window,
129 cx: &mut Context<PopupMenu>,
130 context: &MenuContext,
131 target: &ChatMenuTarget,
132) -> PopupMenu {
133 let mut popup = popup;
134 let current = target.folder_id.clone();
135 let folders: Vec<(String, String)> = context
136 .folders
137 .iter()
138 .filter(|(folder_id, _)| current.as_ref() != Some(folder_id))
139 .cloned()
140 .collect();
141 if !folders.is_empty() {
142 let move_state = context.state.clone();
143 let move_id = target.id.clone();
144 popup = popup.submenu_with_icon(
145 Some(menu_icon(IconName::Folder)),
146 "Move to section",
147 window,
148 cx,
149 move |submenu, _, _| {
150 folders.iter().fold(submenu, |submenu, (folder_id, name)| {
151 let (state, chat_id, folder_id) =
152 (move_state.clone(), move_id.clone(), folder_id.clone());
153 submenu.item(PopupMenuItem::new(name.clone()).on_click(move |_, _, cx| {
154 state.update(cx, |state, cx| {
155 state.move_chat(&chat_id, Some(&folder_id), cx)
156 });
157 }))
158 })
159 },
160 );
161 }
162 if current.is_some() {
163 let remove_state = context.state.clone();
164 let remove_id = target.id.clone();
165 popup = popup.item(
166 PopupMenuItem::new("Remove from section")
167 .icon(menu_icon(IconName::FolderMinus))
168 .on_click(move |_, _, cx| {
169 remove_state.update(cx, |state, cx| state.move_chat(&remove_id, None, cx));
170 }),
171 );
172 }
173 let read_state = context.state.clone();
174 let read_id = target.id.clone();
175 let unread = target.unread;
176 let mute_state = context.state.clone();
177 let mute_id = target.id.clone();
178 let muted = target.muted;
179 let hide_state = context.state.clone();
180 let hide_id = target.id.clone();
181 popup = popup
182 .separator()
183 .item(
184 PopupMenuItem::new(if unread {
185 "Mark as read"
186 } else {
187 "Mark as unread"
188 })
189 .icon(menu_icon(if unread {
190 IconName::MailOpen
191 } else {
192 IconName::Mail
193 }))
194 .on_click(move |_, _, cx| {
195 read_state.update(cx, |state, cx| {
196 if unread {
197 state.mark_chat_read(&read_id, cx);
198 } else {
199 state.mark_chat_unread(&read_id, cx);
200 }
201 });
202 }),
203 )
204 .item(
205 PopupMenuItem::new(if muted { "Unmute" } else { "Mute" })
206 .icon(menu_icon(if muted {
207 IconName::Bell
208 } else {
209 IconName::BellOff
210 }))
211 .on_click(move |_, _, cx| {
212 mute_state.update(cx, |state, cx| state.set_chat_muted(&mute_id, !muted, cx));
213 }),
214 )
215 .separator()
216 .item(
217 PopupMenuItem::new("Hide")
218 .icon(menu_icon(IconName::EyeOff))
219 .on_click(move |_, _, cx| {
220 hide_state.update(cx, |state, cx| state.hide_chat(&hide_id, cx));
221 }),
222 );
223 if target.is_group {
224 let leave_state = context.state.clone();
225 let leave_id = target.id.clone();
226 let title = target.title.clone();
227 let member_count = target.member_count;
228 popup = popup.item(
229 PopupMenuItem::element(|_, _| {
230 div().text_color(theme::red_soft()).child("Leave chat...")
231 })
232 .icon(icon(IconName::LogOut, MENU_ICON_SIZE, theme::red_soft()))
233 .on_click(move |_, window, cx| {
234 confirm_leave(&leave_state, &leave_id, &title, member_count, window, cx);
235 }),
236 );
237 }
238 popup
239}
240
241#[derive(Clone)]
242struct SectionMenuTarget {
243 id: String,
244 name: String,
245 user_created: bool,
246 previous_id: Option<String>,
247 next_id: Option<String>,
248 movable: bool,
249 read_only: bool,
250}
251
252fn section_menu_targets(
253 sections: &[Section],
254 directory: &Directory,
255 read_only: bool,
256) -> Vec<SectionMenuTarget> {
257 let movable_ids: HashSet<&str> = directory
258 .folders
259 .iter()
260 .map(|folder| folder.id.as_str())
261 .filter(|folder_id| !is_pending_folder(folder_id))
262 .collect();
263 let movable = |section: &Section| movable_ids.contains(section.id.as_str());
264 sections
265 .iter()
266 .enumerate()
267 .map(|(index, section)| SectionMenuTarget {
268 id: section.id.clone(),
269 name: section.name.clone(),
270 user_created: section.kind == SectionKind::Folder && movable(section),
271 previous_id: sections[..index]
272 .iter()
273 .rev()
274 .find(|other| movable(other))
275 .map(|other| other.id.clone()),
276 next_id: sections[index + 1..]
277 .iter()
278 .find(|other| movable(other))
279 .map(|other| other.id.clone()),
280 movable: movable(section),
281 read_only,
282 })
283 .collect()
284}
285
286fn drop_target(section: &Section) -> Option<Option<String>> {
287 if is_pending_folder(&section.id) {
288 return None;
289 }
290 Some(
291 matches!(section.kind, SectionKind::Favorites | SectionKind::Folder)
292 .then(|| section.id.clone()),
293 )
294}
295
296fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {
297 let state = state.clone();
298 PopupMenuItem::new("New section")
299 .icon(menu_icon(IconName::Plus))
300 .disabled(read_only)
301 .on_click(move |_, window, cx| {
302 open_section_name_dialog(state.clone(), SectionNameTarget::New, window, cx);
303 })
304}
305
306fn move_section_item(
307 state: &Entity<AppState>,
308 label: &'static str,
309 glyph: IconName,
310 folder_id: &str,
311 target_id: Option<&String>,
312 read_only: bool,
313) -> PopupMenuItem {
314 let state = state.clone();
315 let folder_id = folder_id.to_owned();
316 let target_id = target_id.cloned();
317 PopupMenuItem::new(label)
318 .icon(menu_icon(glyph))
319 .disabled(read_only || target_id.is_none())
320 .on_click(move |_, _, cx| {
321 if let Some(target_id) = &target_id {
322 state.update(cx, |state, cx| {
323 state.move_section(&folder_id, target_id, cx)
324 });
325 }
326 })
327}
328
329fn section_menu(
330 popup: PopupMenu,
331 state: &Entity<AppState>,
332 target: &SectionMenuTarget,
333) -> PopupMenu {
334 let mut popup = popup;
335 if target.user_created {
336 let rename_state = state.clone();
337 let rename_target = SectionNameTarget::Rename {
338 folder_id: target.id.clone(),
339 name: target.name.clone(),
340 };
341 popup = popup.item(
342 PopupMenuItem::new("Rename section")
343 .icon(menu_icon(IconName::Pencil))
344 .disabled(target.read_only)
345 .on_click(move |_, window, cx| {
346 open_section_name_dialog(
347 rename_state.clone(),
348 rename_target.clone(),
349 window,
350 cx,
351 );
352 }),
353 );
354 }
355 if target.movable {
356 popup = popup
357 .item(move_section_item(
358 state,
359 "Move up",
360 IconName::ArrowUp,
361 &target.id,
362 target.previous_id.as_ref(),
363 target.read_only,
364 ))
365 .item(move_section_item(
366 state,
367 "Move down",
368 IconName::ArrowDown,
369 &target.id,
370 target.next_id.as_ref(),
371 target.read_only,
372 ))
373 .separator();
374 }
375 popup = popup.item(new_section_item(state, target.read_only));
376 if target.user_created {
377 let delete_state = state.clone();
378 let (folder_id, name) = (target.id.clone(), target.name.clone());
379 popup = popup.separator().item(
380 PopupMenuItem::element(|_, _| {
381 div().text_color(theme::red_soft()).child("Delete section")
382 })
383 .icon(icon(IconName::Trash, MENU_ICON_SIZE, theme::red_soft()))
384 .disabled(target.read_only)
385 .on_click(move |_, window, cx| {
386 confirm_delete_section(&delete_state, &folder_id, &name, window, cx);
387 }),
388 );
389 }
390 popup
391}
392
393fn confirm_delete_section(
394 state: &Entity<AppState>,
395 folder_id: &str,
396 name: &str,
397 window: &mut Window,
398 cx: &mut App,
399) {
400 let state = state.clone();
401 let folder_id = folder_id.to_owned();
402 let heading = format!("Delete section \"{}\"?", truncated(name, TITLE_LIMIT));
403 window.open_alert_dialog(cx, move |alert, _, _| {
404 let state = state.clone();
405 let folder_id = folder_id.clone();
406 let cancel = Button::new("delete-section-cancel")
407 .label("Cancel")
408 .on_click(|_, window, cx| window.close_dialog(cx));
409 let delete = Button::new("delete-section-confirm")
410 .label("Delete")
411 .danger()
412 .on_click(move |_, window, cx| {
413 state.update(cx, |state, cx| state.delete_section(&folder_id, cx));
414 window.close_dialog(cx);
415 });
416 alert
417 .title(heading.clone())
418 .description("Chats in it move back to Chats.")
419 .footer(DialogFooter::new().child(cancel).child(delete))
420 .on_ok(|_, _, _| false)
421 });
422}
423
424fn leave_description(member_count: usize) -> String {
425 let who = match member_count {
426 0 | 1 => "The other members".to_owned(),
427 2 => "The other member".to_owned(),
428 count => format!("The {} other members", count - 1),
429 };
430 let verb = if member_count == 2 { "sees" } else { "see" };
431 format!("{who} {verb} that you left. You can only come back if someone adds you.")
432}
433
434fn confirm_leave(
435 state: &Entity<AppState>,
436 chat_id: &str,
437 title: &str,
438 member_count: usize,
439 window: &mut Window,
440 cx: &mut App,
441) {
442 let state = state.clone();
443 let chat_id = chat_id.to_owned();
444 let heading = format!("Leave \"{}\"?", truncated(title, TITLE_LIMIT));
445 let description = leave_description(member_count);
446 window.open_alert_dialog(cx, move |alert, _, _| {
447 let state = state.clone();
448 let chat_id = chat_id.clone();
449 let cancel = Button::new("leave-cancel")
450 .label("Cancel")
451 .on_click(|_, window, cx| window.close_dialog(cx));
452 let leave = Button::new("leave-confirm")
453 .label("Leave")
454 .danger()
455 .on_click(move |_, window, cx| {
456 state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
457 window.close_dialog(cx);
458 });
459 alert
460 .title(heading.clone())
461 .description(description.clone())
462 .footer(DialogFooter::new().child(cancel).child(leave))
463 .on_ok(|_, _, _| false)
464 });
465}
466
467pub struct SidebarView {
468 state: Entity<AppState>,
469 tab: SidebarTab,
470 activity_panel: Entity<ActivityPanel>,
471 saved_panel: Entity<SavedPanel>,
472 collapsed_teams: HashSet<String>,
473 revealed_channel_teams: HashSet<String>,
474 hidden_teams_open: bool,
475 chats_scroll: ScrollHandle,
476 older_chats_trigger_top: Cell<Option<f32>>,
477 older_chats_seen: Cell<(bool, bool)>,
478 channels_scroll: ScrollHandle,
479 calls_scroll: ScrollHandle,
480 _subscription: Subscription,
481 _state_observation: Subscription,
482 _agent_observation: Option<Subscription>,
483}
484
485fn preview_text(preview: &Preview) -> Option<(String, bool)> {
486 match preview {
487 Preview::Empty => None,
488 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
489 Preview::Typing(text) => Some((text.clone(), true)),
490 Preview::Text {
491 prefix: Some(prefix),
492 text,
493 } => Some((format!("{prefix}: {text}"), false)),
494 Preview::Text { prefix: None, text } => Some((text.clone(), false)),
495 }
496}
497
498fn preview_icon(text: &str) -> Option<IconName> {
499 match text.rsplit(": ").next()? {
500 "Image" => Some(IconName::Image),
501 "File" => Some(IconName::File),
502 _ => None,
503 }
504}
505
506fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
507 let row = h_flex()
508 .flex_1()
509 .min_w_0()
510 .overflow_hidden()
511 .gap(px(4.))
512 .items_center()
513 .text_size(px(12.5))
514 .text_color(color);
515 match preview {
516 LocalPreview::Draft(text) => row
517 .child(
518 div()
519 .flex_none()
520 .text_color(theme::accent_text())
521 .child("Draft:"),
522 )
523 .child(div().truncate().child(text.clone())),
524 LocalPreview::NotSent => row.child(
525 div()
526 .flex_none()
527 .text_color(theme::red_soft())
528 .child("Not sent"),
529 ),
530 }
531}
532
533impl SidebarView {
534 pub fn new(
535 state: Entity<AppState>,
536 activity_panel: Entity<ActivityPanel>,
537 saved_panel: Entity<SavedPanel>,
538 cx: &mut Context<Self>,
539 ) -> Self {
540 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
541 if matches!(event, AppEvent::Selection) {
542 if state.read(cx).new_chat {
543 this.tab = SidebarTab::Chats;
544 }
545 this.expand_team_of_selection(cx);
546 }
547 if matches!(
548 event,
549 AppEvent::Sidebar
550 | AppEvent::CallHistory
551 | AppEvent::Selection
552 | AppEvent::Directory
553 | AppEvent::Typing
554 | AppEvent::LocalPreviews
555 ) {
556 cx.notify();
557 }
558 });
559 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
560 let agent_observation =
561 crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
562 let tab = if state.read(cx).start_on_channels {
563 SidebarTab::Channels
564 } else {
565 SidebarTab::Chats
566 };
567 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
568 cx.spawn(async move |this, cx| {
569 loop {
570 cx.background_executor().timer(CALLS_REFRESH).await;
571 let alive = this.update(cx, |view, cx| {
572 if view.tab == SidebarTab::Calls {
573 cx.notify();
574 }
575 });
576 if alive.is_err() {
577 break;
578 }
579 }
580 })
581 .detach();
582 SidebarView {
583 state,
584 tab,
585 activity_panel,
586 saved_panel,
587 collapsed_teams,
588 revealed_channel_teams: HashSet::new(),
589 hidden_teams_open: false,
590 chats_scroll: ScrollHandle::new(),
591 older_chats_trigger_top: Cell::new(None),
592 older_chats_seen: Cell::new((false, false)),
593 channels_scroll: ScrollHandle::new(),
594 calls_scroll: ScrollHandle::new(),
595 _subscription: subscription,
596 _state_observation: state_observation,
597 _agent_observation: agent_observation,
598 }
599 }
600
601 pub fn tab(&self) -> SidebarTab {
602 self.tab
603 }
604
605 pub fn show_activity(&mut self, cx: &mut Context<Self>) {
606 self.open_tab(SidebarTab::Activity, cx);
607 }
608
609 pub fn show_chats(&mut self, cx: &mut Context<Self>) {
610 self.open_tab(SidebarTab::Chats, cx);
611 }
612
613 pub fn show_channels(&mut self, cx: &mut Context<Self>) {
614 self.open_tab(SidebarTab::Channels, cx);
615 }
616
617 pub fn show_calls(&mut self, cx: &mut Context<Self>) {
618 self.open_tab(SidebarTab::Calls, cx);
619 }
620
621 pub fn show_saved(&mut self, cx: &mut Context<Self>) {
622 self.open_tab(SidebarTab::Saved, cx);
623 }
624
625 pub fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
626 self.tab = tab;
627 match tab {
628 SidebarTab::Calls => self.state.update(cx, |state, cx| {
629 state.refresh_call_history(cx);
630 state.refresh_calendar(cx);
631 }),
632 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
633 _ => {}
634 }
635 cx.notify();
636 }
637
638 pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {
639 let selection = match self.tab {
640 SidebarTab::Chats => self
641 .state
642 .read(cx)
643 .adjacent_chat_id(step)
644 .map(Selection::Chat),
645 SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),
646 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,
647 };
648 if let Some(selection) = selection {
649 self.state
650 .update(cx, |state, cx| state.select(selection, cx));
651 }
652 }
653
654 fn adjacent_channel_id(&self, step: Step, cx: &mut Context<Self>) -> Option<String> {
655 let state = self.state.read(cx);
656 let selected_channel = match &state.selection {
657 Some(Selection::Channel(channel_id)) => Some(channel_id.as_str()),
658 _ => None,
659 };
660 let input = ChannelOrderInput {
661 teams: &state.sidebar.teams,
662 pinned_ids: &state.directory.pinned_channels,
663 collapsed_teams: &self.collapsed_teams,
664 revealed_channel_teams: &self.revealed_channel_teams,
665 hidden_teams_open: self.hidden_teams_open,
666 selected_channel,
667 };
668 step_id(&visible_channel_ids(&input), selected_channel, step)
669 }
670
671 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
672 let state = self.state.read(cx);
673 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
674 return;
675 };
676 let team_id = state
677 .sidebar
678 .teams
679 .iter()
680 .find(|entry| {
681 entry
682 .channels
683 .iter()
684 .any(|channel| channel.id == channel_id)
685 })
686 .map(|entry| entry.team.id.clone());
687 if let Some(team_id) = team_id
688 && self.collapsed_teams.remove(&team_id)
689 {
690 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
691 }
692 }
693
694 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
695 let active = self.state.read(cx).new_chat;
696 div()
697 .id("new-chat")
698 .size(px(NEW_CHAT_BUTTON_SIZE))
699 .flex_none()
700 .flex()
701 .items_center()
702 .justify_center()
703 .rounded(px(8.))
704 .bg(theme::surface_raised())
705 .cursor_pointer()
706 .when(active, |button| button.bg(theme::popup_hover()))
707 .hover(|button| button.bg(theme::popup_hover()))
708 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
709 .child(icon(IconName::Pencil, 16., theme::text_soft()))
710 .on_click(cx.listener(|this, _, _, cx| {
711 this.state.update(cx, |state, cx| state.start_new_chat(cx));
712 }))
713 }
714
715 fn chat_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
716 let state = self.state.clone();
717 let read_only = self.state.read(cx).mode.read_only;
718 Button::new("chat-list-more")
719 .icon(IconName::Ellipsis)
720 .ghost()
721 .size(px(NEW_CHAT_BUTTON_SIZE))
722 .rounded(px(8.))
723 .tooltip("More options")
724 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
725 }
726
727 fn draft_row(&self) -> impl IntoElement {
728 h_flex()
729 .id("new-chat-draft")
730 .mx(px(6.))
731 .h(px(ROW_HEIGHT))
732 .px(px(10.))
733 .gap(px(12.))
734 .items_center()
735 .rounded(px(8.))
736 .bg(theme::surface_raised())
737 .child(
738 div()
739 .size(px(AVATAR_SIZE))
740 .flex_none()
741 .flex()
742 .items_center()
743 .justify_center()
744 .rounded_full()
745 .bg(theme::border_strong())
746 .child(icon(IconName::Pencil, 16., theme::text())),
747 )
748 .child(
749 v_flex()
750 .flex_1()
751 .min_w_0()
752 .gap(px(2.))
753 .child(
754 div()
755 .truncate()
756 .text_size(px(14.))
757 .text_color(theme::text())
758 .child("New chat"),
759 )
760 .child(
761 div()
762 .truncate()
763 .text_size(px(12.5))
764 .text_color(theme::text_muted())
765 .child("Draft"),
766 ),
767 )
768 }
769
770 fn section_header(
771 &self,
772 section: &Section,
773 menu: SectionMenuTarget,
774 cx: &mut Context<Self>,
775 ) -> impl IntoElement {
776 let drop_target = drop_target(section);
777 let toggle_id = section.id.clone();
778 let menu_state = self.state.clone();
779 h_flex()
780 .id(SharedString::from(format!("section-{}", section.id)))
781 .h(px(SECTION_HEIGHT))
782 .mt(px(SECTION_GAP))
783 .mx(px(6.))
784 .px(px(10.))
785 .gap(px(6.))
786 .items_center()
787 .rounded(px(6.))
788 .cursor_pointer()
789 .hover(|header| header.bg(theme::row_hover()))
790 .when_some(drop_target, |header, drop_target| {
791 header
792 .drag_over::<DraggedChat>(|style, _, _, _| {
793 style
794 .bg(theme::drop_background())
795 .border_1()
796 .border_color(theme::accent())
797 })
798 .on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
799 let target = drop_target.clone();
800 this.state.update(cx, |state, cx| {
801 state.move_chat(&dragged.id, target.as_deref(), cx)
802 });
803 }))
804 })
805 .child(icon(
806 if section.collapsed {
807 IconName::ChevronRight
808 } else {
809 IconName::ChevronDown
810 },
811 12.,
812 theme::text_muted(),
813 ))
814 .child(
815 div()
816 .flex_1()
817 .min_w_0()
818 .truncate()
819 .text_size(px(12.))
820 .font_weight(FontWeight::SEMIBOLD)
821 .text_color(theme::text_soft())
822 .child(section.name.clone()),
823 )
824 .when(section.collapsed && section.unread_chats > 0, |header| {
825 header.child(count_badge(section.unread_chats, false))
826 })
827 .child(
828 div()
829 .text_size(px(11.))
830 .text_color(theme::text_faint())
831 .child(section.count.to_string()),
832 )
833 .on_click(cx.listener(move |this, _, _, cx| {
834 let id = toggle_id.clone();
835 this.state
836 .update(cx, |state, cx| state.toggle_collapsed(&id, cx));
837 }))
838 .context_menu(move |popup, _, _| section_menu(popup, &menu_state, &menu))
839 }
840
841 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
842 let toggle_id = section.id.clone();
843 let label = if section.hidden_count > 0 {
844 format!("See more ({})", section.hidden_count)
845 } else {
846 "See less".to_owned()
847 };
848 div()
849 .id(SharedString::from(format!("see-more-{}", section.id)))
850 .mx(px(6.))
851 .pl(px(10. + AVATAR_SIZE + 12.))
852 .h(px(SEE_MORE_HEIGHT))
853 .flex()
854 .items_center()
855 .rounded(px(6.))
856 .cursor_pointer()
857 .text_size(px(12.5))
858 .text_color(theme::accent_text())
859 .hover(|row| row.bg(theme::row_hover()))
860 .child(label)
861 .on_click(cx.listener(move |this, _, _, cx| {
862 let id = toggle_id.clone();
863 this.state
864 .update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
865 }))
866 }
867
868 fn chat_row(
869 &self,
870 item: &ChatItem,
871 selected: bool,
872 local_preview: Option<&LocalPreview>,
873 proposal_agent: Option<&'static str>,
874 directory: &Directory,
875 menu: &MenuContext,
876 ) -> AnyElement {
877 let ring = if selected {
878 theme::surface_raised()
879 } else {
880 theme::surface()
881 };
882 let unread = item.unread.is_unread();
883 let presence = item
884 .presence_user
885 .as_deref()
886 .map(|user_id| directory.presence_of(user_id));
887 let avatar = spec_avatar(directory, &item.avatar, AVATAR_SIZE, ring);
888 let avatar = match presence {
889 Some(kind) => with_presence(avatar, kind, AVATAR_SIZE, ring).into_any_element(),
890 None => avatar,
891 };
892 let name = div()
893 .flex_1()
894 .min_w_0()
895 .truncate()
896 .text_size(px(14.))
897 .font_weight(if unread {
898 FontWeight::BOLD
899 } else {
900 FontWeight::NORMAL
901 })
902 .text_color(theme::text())
903 .child(item.title.clone());
904 let time = h_flex()
905 .flex_none()
906 .gap(px(4.))
907 .items_center()
908 .text_size(px(11.))
909 .text_color(if unread {
910 theme::accent_text()
911 } else {
912 theme::text_muted()
913 })
914 .when(item.muted, |time| {
915 time.child(icon(
916 IconName::BellOff,
917 MUTED_ICON_SIZE,
918 theme::text_faint(),
919 ))
920 })
921 .child(item.time_label.clone());
922 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
923 theme::accent_text()
924 } else if item.muted {
925 theme::text_faint()
926 } else if unread {
927 theme::text_strong()
928 } else {
929 theme::text_muted()
930 };
931 let preview = match (proposal_agent, local_preview) {
932 (Some(agent), _) => Some(
933 h_flex()
934 .flex_1()
935 .min_w_0()
936 .overflow_hidden()
937 .text_size(px(12.5))
938 .text_color(theme::accent_text())
939 .child(div().truncate().child(format!("Proposal from {agent}"))),
940 ),
941 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
942 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
943 let glyph = preview_icon(&text);
944 h_flex()
945 .flex_1()
946 .min_w_0()
947 .overflow_hidden()
948 .gap(px(4.))
949 .items_center()
950 .text_size(px(12.5))
951 .when(italic, |preview| preview.italic())
952 .text_color(preview_color)
953 .children(glyph.map(|name| icon(name, 12., preview_color)))
954 .child(div().truncate().child(text))
955 }),
956 };
957 let lines = v_flex()
958 .flex_1()
959 .min_w_0()
960 .gap(px(2.))
961 .child(
962 h_flex()
963 .gap(px(8.))
964 .items_baseline()
965 .child(name)
966 .child(time),
967 )
968 .child(
969 h_flex()
970 .h(px(18.))
971 .gap(px(8.))
972 .items_center()
973 .child(preview.unwrap_or_else(|| div().flex_1()))
974 .children(match proposal_agent {
975 Some(_) => Some(
976 div()
977 .size(px(PROPOSAL_DOT_SIZE))
978 .flex_none()
979 .rounded_full()
980 .bg(theme::accent())
981 .into_any_element(),
982 ),
983 None => unread_marker(item.unread, item.muted)
984 .map(IntoElement::into_any_element),
985 }),
986 );
987 let state = self.state.clone();
988 let chat_id = item.id.clone();
989 let dragged = DraggedChat {
990 id: item.id.clone(),
991 title: item.title.clone(),
992 };
993 let menu_context = menu.clone();
994 let target = ChatMenuTarget {
995 id: item.id.clone(),
996 title: item.title.clone(),
997 folder_id: item.folder_id.clone(),
998 unread,
999 muted: item.muted,
1000 is_group: item.is_group,
1001 member_count: item.member_count,
1002 };
1003 h_flex()
1004 .id(SharedString::from(format!("chat-{}", item.id)))
1005 .mx(px(6.))
1006 .h(px(ROW_HEIGHT))
1007 .px(px(10.))
1008 .gap(px(12.))
1009 .items_center()
1010 .rounded(px(8.))
1011 .cursor_pointer()
1012 .when(selected, |row| row.bg(theme::surface_raised()))
1013 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1014 .on_drag(dragged, |dragged, _, _, cx| {
1015 let title = dragged.title.clone();
1016 cx.new(|_| DragGhost { title })
1017 })
1018 .child(avatar)
1019 .child(lines)
1020 .on_click(move |_, _, cx| {
1021 let selection = Selection::Chat(chat_id.clone());
1022 state.update(cx, |state, cx| state.select(selection, cx));
1023 })
1024 .context_menu(move |popup, window, cx| {
1025 chat_menu(popup, window, cx, &menu_context, &target)
1026 })
1027 .into_any_element()
1028 }
1029
1030 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
1031 let proposal_agents = crate::agent_api::pending_agents(cx);
1032 let (sections, section_menus, menu, local_previews) = {
1033 let state = self.state.read(cx);
1034 let now = Utc::now();
1035 let offset = Local::now().offset().fix();
1036 let input = SectionInput {
1037 chats: &state.sidebar.chats,
1038 directory: &state.directory,
1039 collapsed: &state.collapsed,
1040 expanded_lists: &state.expanded_lists,
1041 typing: &state.typing,
1042 now,
1043 offset,
1044 };
1045 let sections = build_sections(&input);
1046 let menu = MenuContext {
1047 state: self.state.clone(),
1048 folders: state.directory.move_targets(),
1049 };
1050 let section_menus =
1051 section_menu_targets(&sections, &state.directory, state.mode.read_only);
1052 (sections, section_menus, menu, state.local_previews.clone())
1053 };
1054
1055 let top = -f32::from(self.chats_scroll.offset().y);
1056 let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
1057 let height = if measured > 1. {
1058 measured
1059 } else {
1060 window_height.max(FALLBACK_VIEWPORT)
1061 };
1062 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
1063
1064 let (selected, drafting) = {
1065 let state = self.state.read(cx);
1066 (
1067 state.selection.clone().filter(|_| !state.new_chat),
1068 state.new_chat,
1069 )
1070 };
1071 let mut faces: Vec<String> = Vec::new();
1072 let mut presence_users: Vec<String> = Vec::new();
1073 let mut y = 0.;
1074 let mut list = v_flex().w_full().pb(px(12.));
1075 let mut skipped_height = 0.;
1076 let mut others_end = None;
1077 let directory_state = self.state.clone();
1078 if drafting {
1079 list = list.child(self.draft_row());
1080 y += ROW_HEIGHT;
1081 }
1082 for (section, section_menu) in sections.iter().zip(section_menus) {
1083 list = with_spacer(list, &mut skipped_height);
1084 list = list.child(self.section_header(section, section_menu, cx));
1085 y += SECTION_GAP + SECTION_HEIGHT;
1086 if section.collapsed {
1087 continue;
1088 }
1089 for item in &section.items {
1090 let on_screen = y + ROW_HEIGHT >= visible_from && y <= visible_to;
1091 if on_screen {
1092 collect_faces(&item.avatar, &mut faces);
1093 presence_users.extend(item.presence_user.clone());
1094 }
1095 if on_screen {
1096 list = with_spacer(list, &mut skipped_height);
1097 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
1098 let directory = &directory_state.read(cx).directory;
1099 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
1100 list = list.child(self.chat_row(
1101 item,
1102 is_selected,
1103 local_preview,
1104 proposal_agents.get(&item.id).copied(),
1105 directory,
1106 &menu,
1107 ));
1108 } else {
1109 skipped_height += ROW_HEIGHT;
1110 }
1111 y += ROW_HEIGHT;
1112 }
1113 if section.kind == SectionKind::Others {
1114 others_end = Some(y);
1115 }
1116 if section.hidden_count > 0 || section.list_expanded {
1117 list = with_spacer(list, &mut skipped_height);
1118 list = list.child(self.see_more_row(section, cx));
1119 y += SEE_MORE_HEIGHT;
1120 }
1121 if section.show_empty_hint {
1122 list = with_spacer(list, &mut skipped_height);
1123 list = list.child(
1124 div()
1125 .ml(px(16.))
1126 .mr(px(16.))
1127 .h(px(HINT_HEIGHT))
1128 .flex()
1129 .items_center()
1130 .text_size(px(12.))
1131 .italic()
1132 .text_color(theme::text_faint())
1133 .child(EMPTY_FOLDER_HINT),
1134 );
1135 y += HINT_HEIGHT;
1136 }
1137 }
1138 let (has_older, loading_older) = self.state.read(cx).older_chats();
1139 let previous = self.older_chats_seen.replace((has_older, loading_older));
1140 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
1141 self.older_chats_trigger_top.set(None);
1142 }
1143 if has_older
1144 && wants_older_chats(
1145 others_end,
1146 top + height,
1147 top,
1148 self.older_chats_trigger_top.get(),
1149 loading_older,
1150 )
1151 {
1152 self.older_chats_trigger_top.set(Some(top));
1153 let state = self.state.clone();
1154 cx.defer(move |cx| state.read(cx).request_older_chats());
1155 }
1156 if loading_older {
1157 list = with_spacer(list, &mut skipped_height);
1158 list = list.child(
1159 div()
1160 .pl(px(16. + AVATAR_SIZE + 12.))
1161 .h(px(SEE_MORE_HEIGHT))
1162 .flex()
1163 .items_center()
1164 .text_size(px(12.5))
1165 .italic()
1166 .text_color(theme::text_faint())
1167 .child(LOADING_OLDER_LABEL),
1168 );
1169 }
1170 list = with_spacer(list, &mut skipped_height);
1171 self.request_lazy_data(faces, presence_users, cx);
1172 div()
1173 .id("chats-scroll")
1174 .flex_1()
1175 .min_h_0()
1176 .overflow_y_scroll()
1177 .track_scroll(&self.chats_scroll)
1178 .child(list)
1179 .into_any_element()
1180 }
1181
1182 fn request_lazy_data(
1183 &self,
1184 faces: Vec<String>,
1185 presence_users: Vec<String>,
1186 cx: &mut Context<Self>,
1187 ) {
1188 if faces.is_empty() && presence_users.is_empty() {
1189 return;
1190 }
1191 let state = self.state.clone();
1192 cx.defer(move |cx| {
1193 state.update(cx, |state, cx| {
1194 state.request_avatars(faces, cx);
1195 state.request_presence(presence_users, cx);
1196 });
1197 });
1198 }
1199
1200 fn channel_row(
1201 &self,
1202 channel_id: &str,
1203 team: &TeamRecord,
1204 channel: &ChannelRecord,
1205 selected: bool,
1206 notifications: ChannelNotifications,
1207 ) -> AnyElement {
1208 let unread = channel.unread;
1209 let state = self.state.clone();
1210 let menu_state = self.state.clone();
1211 let menu_channel_id = channel_id.to_owned();
1212 let selection = Selection::Channel(channel_id.to_owned());
1213 let now = Utc::now();
1214 let offset = Local::now().offset().fix();
1215 let time = channel
1216 .last_message_at
1217 .map(|time| {
1218 format::list_time_label(time, now.with_timezone(&offset).date_naive(), offset)
1219 })
1220 .unwrap_or_default();
1221 h_flex()
1222 .id(SharedString::from(format!("pinned-{channel_id}")))
1223 .mx(px(6.))
1224 .h(px(PINNED_CHANNEL_HEIGHT))
1225 .px(px(10.))
1226 .gap(px(12.))
1227 .items_center()
1228 .rounded(px(8.))
1229 .cursor_pointer()
1230 .when(selected, |row| row.bg(theme::surface_raised()))
1231 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1232 .child(square_avatar(&team.name, &team.id, 28., 7.))
1233 .child(
1234 v_flex()
1235 .flex_1()
1236 .min_w_0()
1237 .gap(px(1.))
1238 .child(
1239 h_flex()
1240 .gap(px(8.))
1241 .items_baseline()
1242 .child(
1243 div()
1244 .flex_1()
1245 .min_w_0()
1246 .truncate()
1247 .text_size(px(13.5))
1248 .font_weight(if unread {
1249 FontWeight::BOLD
1250 } else {
1251 FontWeight::NORMAL
1252 })
1253 .text_color(theme::text())
1254 .child(format!("{} / {}", team.name, channel.name)),
1255 )
1256 .children(notification_badge(notifications.level))
1257 .child(
1258 div()
1259 .flex_none()
1260 .text_size(px(11.))
1261 .text_color(if unread {
1262 theme::accent_text()
1263 } else {
1264 theme::text_muted()
1265 })
1266 .child(time),
1267 ),
1268 )
1269 .child(
1270 h_flex()
1271 .gap(px(8.))
1272 .items_center()
1273 .child(
1274 div()
1275 .flex_1()
1276 .min_w_0()
1277 .truncate()
1278 .text_size(px(12.))
1279 .text_color(theme::text_muted())
1280 .child(team.name.clone()),
1281 )
1282 .when(unread, |line| line.child(dot(7.))),
1283 ),
1284 )
1285 .on_click(move |_, _, cx| {
1286 let selection = selection.clone();
1287 state.update(cx, |state, cx| state.select(selection, cx));
1288 })
1289 .context_menu(move |popup, window, cx| {
1290 channel_menu(
1291 popup,
1292 window,
1293 cx,
1294 menu_state.clone(),
1295 &menu_channel_id,
1296 notifications,
1297 )
1298 })
1299 .into_any_element()
1300 }
1301
1302 fn plain_header(&self, label: &str) -> impl IntoElement {
1303 div()
1304 .h(px(SECTION_HEIGHT))
1305 .mt(px(SECTION_GAP))
1306 .px(px(16.))
1307 .flex()
1308 .items_center()
1309 .text_size(px(12.))
1310 .font_weight(FontWeight::SEMIBOLD)
1311 .text_color(theme::text_soft())
1312 .child(label.to_owned())
1313 }
1314
1315 fn team_block(
1316 &self,
1317 mut list: Div,
1318 entry: &SidebarTeam,
1319 selected: Option<&Selection>,
1320 cx: &mut Context<Self>,
1321 ) -> Div {
1322 let team_id = entry.team.id.clone();
1323 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1324 let unread = entry.channels.iter().any(|channel| channel.unread);
1325 let toggle_id = team_id.clone();
1326 list = list.child(
1327 h_flex()
1328 .id(SharedString::from(format!("team-{team_id}")))
1329 .mx(px(6.))
1330 .h(px(TEAM_ROW_HEIGHT))
1331 .px(px(10.))
1332 .gap(px(8.))
1333 .items_center()
1334 .rounded(px(8.))
1335 .cursor_pointer()
1336 .hover(|row| row.bg(theme::row_hover()))
1337 .child(icon(
1338 if expanded {
1339 IconName::ChevronDown
1340 } else {
1341 IconName::ChevronRight
1342 },
1343 14.,
1344 theme::text_muted(),
1345 ))
1346 .child(square_avatar(&entry.team.name, &entry.team.id, 28., 7.))
1347 .child(
1348 div()
1349 .flex_1()
1350 .min_w_0()
1351 .truncate()
1352 .text_size(px(13.5))
1353 .font_weight(if unread || expanded {
1354 FontWeight::SEMIBOLD
1355 } else {
1356 FontWeight::NORMAL
1357 })
1358 .text_color(theme::text())
1359 .child(entry.team.name.clone()),
1360 )
1361 .when(unread && !expanded, |row| row.child(dot(7.)))
1362 .on_click(cx.listener(move |this, _, _, cx| {
1363 if !this.collapsed_teams.remove(&toggle_id) {
1364 this.collapsed_teams.insert(toggle_id.clone());
1365 }
1366 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1367 cx.notify();
1368 })),
1369 );
1370 if !expanded {
1371 return list;
1372 }
1373 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1374 let is_selected =
1375 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1376 for channel in entry
1377 .channels
1378 .iter()
1379 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1380 {
1381 list = list.child(self.team_channel_row(
1382 channel,
1383 is_selected(channel),
1384 entry.channel_notifications(&channel.id),
1385 ));
1386 }
1387 let hidden: Vec<&ChannelRecord> = entry
1388 .channels
1389 .iter()
1390 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1391 .collect();
1392 if hidden.is_empty() {
1393 return list;
1394 }
1395 let revealed = self.revealed_channel_teams.contains(&team_id);
1396 let toggle_id = team_id.clone();
1397 list = list.child(self.reveal_row(
1398 SharedString::from(format!("hidden-channels-{team_id}")),
1399 hidden_channels_label(hidden.len()),
1400 revealed,
1401 40.,
1402 cx.listener(move |this, _, _, cx| {
1403 if !this.revealed_channel_teams.remove(&toggle_id) {
1404 this.revealed_channel_teams.insert(toggle_id.clone());
1405 }
1406 cx.notify();
1407 }),
1408 ));
1409 if revealed {
1410 for channel in hidden {
1411 list = list.child(self.team_channel_row(
1412 channel,
1413 false,
1414 entry.channel_notifications(&channel.id),
1415 ));
1416 }
1417 }
1418 list
1419 }
1420
1421 fn reveal_row(
1422 &self,
1423 id: SharedString,
1424 label: String,
1425 open: bool,
1426 indent: f32,
1427 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1428 ) -> impl IntoElement {
1429 h_flex()
1430 .id(id)
1431 .mx(px(6.))
1432 .h(px(REVEAL_ROW_HEIGHT))
1433 .pl(px(indent))
1434 .pr(px(10.))
1435 .gap(px(8.))
1436 .items_center()
1437 .rounded(px(8.))
1438 .cursor_pointer()
1439 .hover(|row| row.bg(theme::row_hover()))
1440 .child(icon(
1441 if open {
1442 IconName::ChevronDown
1443 } else {
1444 IconName::ChevronRight
1445 },
1446 12.,
1447 theme::text_faint(),
1448 ))
1449 .child(
1450 div()
1451 .text_size(px(12.5))
1452 .text_color(theme::text_muted())
1453 .child(label),
1454 )
1455 .on_click(on_click)
1456 }
1457
1458 fn team_channel_row(
1459 &self,
1460 channel: &ChannelRecord,
1461 is_selected: bool,
1462 notifications: ChannelNotifications,
1463 ) -> impl IntoElement {
1464 let state = self.state.clone();
1465 let menu_state = self.state.clone();
1466 let menu_channel_id = channel.id.clone();
1467 let selection = Selection::Channel(channel.id.clone());
1468 h_flex()
1469 .id(SharedString::from(format!("channel-{}", channel.id)))
1470 .mx(px(6.))
1471 .h(px(TEAM_ROW_HEIGHT))
1472 .pl(px(40.))
1473 .pr(px(10.))
1474 .gap(px(8.))
1475 .items_center()
1476 .rounded(px(8.))
1477 .cursor_pointer()
1478 .when(is_selected, |row| row.bg(theme::surface_raised()))
1479 .when(!is_selected, |row| {
1480 row.hover(|row| row.bg(theme::row_hover()))
1481 })
1482 .child(
1483 div()
1484 .w(px(14.))
1485 .flex()
1486 .justify_center()
1487 .text_size(px(15.))
1488 .text_color(theme::text_faint())
1489 .child("#"),
1490 )
1491 .child(
1492 div()
1493 .flex_1()
1494 .min_w_0()
1495 .truncate()
1496 .text_size(px(13.5))
1497 .font_weight(if channel.unread {
1498 FontWeight::BOLD
1499 } else {
1500 FontWeight::NORMAL
1501 })
1502 .text_color(theme::text())
1503 .child(channel.name.clone()),
1504 )
1505 .children(notification_badge(notifications.level))
1506 .when(channel.unread, |row| row.child(dot(7.)))
1507 .on_click(move |_, _, cx| {
1508 let selection = selection.clone();
1509 state.update(cx, |state, cx| state.select(selection, cx));
1510 })
1511 .context_menu(move |popup, window, cx| {
1512 channel_menu(
1513 popup,
1514 window,
1515 cx,
1516 menu_state.clone(),
1517 &menu_channel_id,
1518 notifications,
1519 )
1520 })
1521 }
1522
1523 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1524 let (sidebar, pinned_ids, selected) = {
1525 let state = self.state.read(cx);
1526 (
1527 state.sidebar.clone(),
1528 state.directory.pinned_channels.clone(),
1529 state.selection.clone().filter(|_| !state.new_chat),
1530 )
1531 };
1532 let mut list = v_flex().w_full().pb(px(12.));
1533 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1534 .iter()
1535 .filter_map(|id| {
1536 sidebar.teams.iter().find_map(|entry| {
1537 entry
1538 .channels
1539 .iter()
1540 .find(|channel| &channel.id == id)
1541 .map(|channel| (entry, channel))
1542 })
1543 })
1544 .collect();
1545 if !pinned.is_empty() {
1546 list = list.child(self.plain_header(PINNED_LABEL));
1547 for (entry, channel) in pinned {
1548 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1549 list = list.child(self.channel_row(
1550 &channel.id,
1551 &entry.team,
1552 channel,
1553 is_selected,
1554 entry.channel_notifications(&channel.id),
1555 ));
1556 }
1557 }
1558 list = list.child(self.plain_header(TEAMS_LABEL));
1559 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1560 sidebar.teams.iter().partition(|entry| !entry.hidden);
1561 for entry in shown_teams {
1562 list = self.team_block(list, entry, selected.as_ref(), cx);
1563 }
1564 if !hidden_teams.is_empty() {
1565 let holds_selection = hidden_teams
1566 .iter()
1567 .any(|entry| team_holds(entry, selected.as_ref()));
1568 let open = self.hidden_teams_open || holds_selection;
1569 list = list.child(self.reveal_row(
1570 "hidden-teams".into(),
1571 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1572 open,
1573 10.,
1574 cx.listener(|this, _, _, cx| {
1575 this.hidden_teams_open = !this.hidden_teams_open;
1576 cx.notify();
1577 }),
1578 ));
1579 if open {
1580 for entry in hidden_teams {
1581 list = self.team_block(list, entry, selected.as_ref(), cx);
1582 }
1583 }
1584 }
1585 div()
1586 .id("channels-scroll")
1587 .flex_1()
1588 .min_h_0()
1589 .overflow_y_scroll()
1590 .track_scroll(&self.channels_scroll)
1591 .child(list)
1592 .into_any_element()
1593 }
1594}
1595
1596fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1597 let name = match level {
1598 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1599 ChannelNotificationLevel::Off => IconName::BellOff,
1600 ChannelNotificationLevel::Feed => return None,
1601 };
1602 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1603}
1604
1605fn channel_menu(
1606 popup: PopupMenu,
1607 window: &mut Window,
1608 cx: &mut Context<PopupMenu>,
1609 state: Entity<AppState>,
1610 channel_id: &str,
1611 notifications: ChannelNotifications,
1612) -> PopupMenu {
1613 let channel_id = channel_id.to_owned();
1614 popup.submenu_with_icon(
1615 Some(menu_icon(IconName::Bell)),
1616 "Notifications",
1617 window,
1618 cx,
1619 move |submenu, _, _| {
1620 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1621 let (state, channel_id) = (state.clone(), channel_id.clone());
1622 PopupMenuItem::new(label)
1623 .checked(notifications.level == level)
1624 .on_click(move |_, _, cx| {
1625 let changed = ChannelNotifications {
1626 level,
1627 include_replies: notifications.include_replies
1628 && level != ChannelNotificationLevel::Off,
1629 };
1630 state.update(cx, |state, cx| {
1631 state.set_channel_notifications(&channel_id, changed, cx)
1632 });
1633 })
1634 };
1635 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1636 submenu
1637 .item(level_item(
1638 "Banner and activity",
1639 ChannelNotificationLevel::BannerAndFeed,
1640 ))
1641 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1642 .item(level_item("Off", ChannelNotificationLevel::Off))
1643 .separator()
1644 .item(
1645 PopupMenuItem::new("Include thread replies")
1646 .checked(notifications.include_replies)
1647 .disabled(notifications.level == ChannelNotificationLevel::Off)
1648 .on_click(move |_, _, cx| {
1649 let changed = ChannelNotifications {
1650 level: notifications.level,
1651 include_replies: !notifications.include_replies,
1652 };
1653 replies_state.update(cx, |state, cx| {
1654 state.set_channel_notifications(&replies_id, changed, cx)
1655 });
1656 }),
1657 )
1658 },
1659 )
1660}
1661
1662fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1663 !collapsed_teams.contains(team_id)
1664}
1665
1666fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1667 store
1668 .meta(COLLAPSED_TEAMS_META_KEY)
1669 .ok()
1670 .flatten()
1671 .map(|value| parse_collapsed_teams(&value))
1672 .unwrap_or_default()
1673}
1674
1675fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1676 let _ = store.set_meta(
1677 COLLAPSED_TEAMS_META_KEY,
1678 &serialize_collapsed_teams(collapsed_teams),
1679 );
1680}
1681
1682fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1683 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1684 team_ids.sort_unstable();
1685 serde_json::to_string(&team_ids).unwrap_or_default()
1686}
1687
1688fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1689 serde_json::from_str(value).unwrap_or_default()
1690}
1691
1692fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1693 entry
1694 .channels
1695 .iter()
1696 .any(|channel| selected == Some(&Selection::Channel(channel.id.clone())))
1697}
1698
1699fn hidden_channels_label(count: usize) -> String {
1700 if count == 1 {
1701 "1 hidden channel".to_owned()
1702 } else {
1703 format!("{count} hidden channels")
1704 }
1705}
1706
1707fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1708 match spec {
1709 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1710 AvatarSpec::Pair(first, second) => {
1711 faces.extend(first.user_id.clone());
1712 faces.extend(second.user_id.clone());
1713 }
1714 AvatarSpec::Meeting => {}
1715 }
1716}
1717
1718fn with_spacer(list: Div, skipped_height: &mut f32) -> Div {
1719 let height = std::mem::take(skipped_height);
1720 if height > 0. {
1721 list.child(div().h(px(height)).flex_none())
1722 } else {
1723 list
1724 }
1725}
1726
1727impl Render for SidebarView {
1728 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1729 let window_height = f32::from(window.viewport_size().height);
1730 let body = match self.tab {
1731 SidebarTab::Activity => self.activity_panel.clone().into_any_element(),
1732 SidebarTab::Chats => self.chats_body(window_height, cx),
1733 SidebarTab::Channels => self.channels_body(cx),
1734 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1735 SidebarTab::Saved => self.saved_panel.clone().into_any_element(),
1736 };
1737 let header = match self.tab {
1738 SidebarTab::Chats => Some(
1739 page_header(self.tab.title())
1740 .child(self.chat_list_menu_button(cx))
1741 .child(self.new_chat_button(cx)),
1742 ),
1743 SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),
1744 SidebarTab::Activity | SidebarTab::Saved => None,
1745 };
1746 v_flex()
1747 .debug_selector(|| "shell/islands/sidebar".into())
1748 .w(px(SIDEBAR_WIDTH))
1749 .h_full()
1750 .flex_none()
1751 .bg(theme::surface())
1752 .rounded(px(10.))
1753 .overflow_hidden()
1754 .children(header)
1755 .child(body)
1756 }
1757}
1758
1759#[cfg(test)]
1760mod tests {
1761 use std::collections::HashSet;
1762
1763 use super::{
1764 drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,
1765 team_expanded,
1766 };
1767 use crate::data::PENDING_FOLDER_PREFIX;
1768 use crate::sidebar_model::{Section, SectionKind};
1769
1770 fn section(id: &str, kind: SectionKind) -> Section {
1771 Section {
1772 id: id.to_owned(),
1773 name: id.to_owned(),
1774 kind,
1775 collapsed: false,
1776 count: 0,
1777 unread_chats: 0,
1778 items: Vec::new(),
1779 hidden_count: 0,
1780 list_expanded: false,
1781 show_empty_hint: false,
1782 }
1783 }
1784
1785 #[test]
1786 fn pending_sections_take_no_dropped_chats() {
1787 let pending = format!("{PENDING_FOLDER_PREFIX}1");
1788 assert_eq!(drop_target(&section(&pending, SectionKind::Folder)), None);
1789 assert_eq!(
1790 drop_target(&section("work", SectionKind::Folder)),
1791 Some(Some("work".to_owned()))
1792 );
1793 assert_eq!(
1794 drop_target(&section("recent", SectionKind::Others)),
1795 Some(None)
1796 );
1797 }
1798
1799 #[test]
1800 fn teams_start_expanded() {
1801 assert!(team_expanded("t1", &HashSet::new()));
1802 }
1803
1804 #[test]
1805 fn collapsed_team_stays_closed() {
1806 let collapsed = HashSet::from(["t1".to_owned()]);
1807 assert!(!team_expanded("t1", &collapsed));
1808 assert!(team_expanded("t2", &collapsed));
1809 }
1810
1811 #[test]
1812 fn collapsed_teams_round_trip_as_json() {
1813 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1814 let json = serialize_collapsed_teams(&collapsed);
1815 assert_eq!(json, r#"["a","b"]"#);
1816 assert_eq!(parse_collapsed_teams(&json), collapsed);
1817 assert!(parse_collapsed_teams("garbage").is_empty());
1818 }
1819
1820 #[test]
1821 fn leave_text_counts_the_other_members() {
1822 assert_eq!(
1823 leave_description(4),
1824 "The 3 other members see that you left. You can only come back if someone adds you."
1825 );
1826 assert!(leave_description(2).starts_with("The other member sees"));
1827 assert!(leave_description(0).starts_with("The other members see"));
1828 }
1829}