BlueGit

ict rusty-teams

Files

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

sidebar.rs

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