BlueGit

ict rusty-teams

Files

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

sidebar.rs

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