BlueGit

ict rusty-teams

Files

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

sidebar.rs

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