BlueGit

ict rusty-teams

Files

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

sidebar.rs

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