BlueGit

ict rusty-teams

Files

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

sidebar.rs

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