BlueGit

ict rusty-teams

Files

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

sidebar.rs

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