BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 63.3 KiB Download Raw
1use std::cell::Cell;
2use std::collections::HashSet;
3use std::time::Duration;
4
5use chrono::{Local, Offset, Utc};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::dialog::DialogFooter;
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
10use gpui_kit::component::{WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13use store::{
14 ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
15};
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_CHAT_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
437pub(crate) fn 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_CHAT_PREVIEW.to_owned(), true)),
494 Preview::Event(text) => Some((text.clone(), true)),
495 Preview::Typing(text) => Some((text.clone(), true)),
496 Preview::Text {
497 prefix: Some(prefix),
498 text,
499 } => Some((format!("{prefix}: {text}"), false)),
500 Preview::Text { prefix: None, text } => Some((text.clone(), false)),
501 }
502}
503
504fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
505 let row = h_flex()
506 .flex_1()
507 .min_w_0()
508 .overflow_hidden()
509 .gap(px(4.))
510 .items_center()
511 .text_size(px(12.5))
512 .text_color(color);
513 match preview {
514 LocalPreview::Draft(text) => row
515 .child(
516 div()
517 .flex_none()
518 .text_color(theme::accent_text())
519 .child("Draft:"),
520 )
521 .child(div().truncate().child(text.clone())),
522 LocalPreview::NotSent => row.child(
523 div()
524 .flex_none()
525 .text_color(theme::red_soft())
526 .child("Not sent"),
527 ),
528 }
529}
530
531impl SidebarView {
532 pub fn new(
533 state: Entity<AppState>,
534 activity_panel: Entity<ActivityPanel>,
535 saved_panel: Entity<SavedPanel>,
536 agents_panel: Option<Entity<AgentsPanel>>,
537 cx: &mut Context<Self>,
538 ) -> Self {
539 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
540 if matches!(event, AppEvent::Selection) {
541 if state.read(cx).new_chat {
542 this.tab = SidebarTab::Chats;
543 }
544 this.expand_team_of_selection(cx);
545 }
546 if matches!(
547 event,
548 AppEvent::Sidebar
549 | AppEvent::CallHistory
550 | AppEvent::Selection
551 | AppEvent::Directory
552 | AppEvent::Typing
553 | AppEvent::LocalPreviews
554 ) {
555 cx.notify();
556 }
557 });
558 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
559 let agent_observation =
560 crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
561 let runs_observation = crate::agents::runs_handle(cx).map(|runs| {
562 cx.observe(&runs, |view, _, cx| {
563 if view.tab == SidebarTab::Agents && !crate::agents::agents_enabled(cx) {
564 view.open_tab(SidebarTab::Chats, cx);
565 }
566 })
567 });
568 let tab = if state.read(cx).start_on_channels {
569 SidebarTab::Channels
570 } else {
571 SidebarTab::Chats
572 };
573 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
574 cx.spawn(async move |this, cx| {
575 loop {
576 cx.background_executor().timer(CALLS_REFRESH).await;
577 let alive = this.update(cx, |view, cx| {
578 if view.tab == SidebarTab::Calls {
579 cx.notify();
580 }
581 });
582 if alive.is_err() {
583 break;
584 }
585 }
586 })
587 .detach();
588 SidebarView {
589 state,
590 tab,
591 activity_panel,
592 saved_panel,
593 agents_panel,
594 collapsed_teams,
595 revealed_channel_teams: HashSet::new(),
596 hidden_teams_open: false,
597 chats_scroll: ScrollHandle::new(),
598 older_chats_trigger_top: Cell::new(None),
599 older_chats_seen: Cell::new((false, false)),
600 channels_scroll: ScrollHandle::new(),
601 calls_scroll: ScrollHandle::new(),
602 _subscription: subscription,
603 _state_observation: state_observation,
604 _agent_observation: agent_observation,
605 _runs_observation: runs_observation,
606 }
607 }
608
609 pub fn tab(&self) -> SidebarTab {
610 self.tab
611 }
612
613 pub fn show_activity(&mut self, cx: &mut Context<Self>) {
614 self.open_tab(SidebarTab::Activity, cx);
615 }
616
617 pub fn show_chats(&mut self, cx: &mut Context<Self>) {
618 self.open_tab(SidebarTab::Chats, cx);
619 }
620
621 pub fn show_channels(&mut self, cx: &mut Context<Self>) {
622 self.open_tab(SidebarTab::Channels, cx);
623 }
624
625 pub fn show_calls(&mut self, cx: &mut Context<Self>) {
626 self.open_tab(SidebarTab::Calls, cx);
627 }
628
629 pub fn show_saved(&mut self, cx: &mut Context<Self>) {
630 self.open_tab(SidebarTab::Saved, cx);
631 }
632
633 pub fn show_agents(&mut self, cx: &mut Context<Self>) {
634 self.open_tab(SidebarTab::Agents, cx);
635 }
636
637 pub fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
638 if tab == SidebarTab::Agents && !crate::agents::agents_enabled(cx) {
639 return;
640 }
641 self.tab = tab;
642 match tab {
643 SidebarTab::Calls => self.state.update(cx, |state, cx| {
644 state.refresh_call_history(cx);
645 state.refresh_calendar(cx);
646 }),
647 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
648 _ => {}
649 }
650 cx.notify();
651 }
652
653 pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {
654 let selection = match self.tab {
655 SidebarTab::Chats => self
656 .state
657 .read(cx)
658 .adjacent_chat_id(step)
659 .map(Selection::Chat),
660 SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),
661 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved | SidebarTab::Agents => {
662 None
663 }
664 };
665 if let Some(selection) = selection {
666 self.state
667 .update(cx, |state, cx| state.select(selection, cx));
668 }
669 }
670
671 fn adjacent_channel_id(&self, step: Step, cx: &mut Context<Self>) -> Option<String> {
672 let state = self.state.read(cx);
673 let selected_channel = match &state.selection {
674 Some(Selection::Channel(channel_id)) => Some(channel_id.as_str()),
675 _ => None,
676 };
677 let input = ChannelOrderInput {
678 teams: &state.sidebar.teams,
679 pinned_ids: &state.directory.pinned_channels,
680 collapsed_teams: &self.collapsed_teams,
681 revealed_channel_teams: &self.revealed_channel_teams,
682 hidden_teams_open: self.hidden_teams_open,
683 selected_channel,
684 };
685 step_id(&visible_channel_ids(&input), selected_channel, step)
686 }
687
688 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
689 let state = self.state.read(cx);
690 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
691 return;
692 };
693 let team_id = state
694 .sidebar
695 .teams
696 .iter()
697 .find(|entry| {
698 entry
699 .channels
700 .iter()
701 .any(|channel| channel.id == channel_id)
702 })
703 .map(|entry| entry.team.id.clone());
704 if let Some(team_id) = team_id
705 && self.collapsed_teams.remove(&team_id)
706 {
707 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
708 }
709 }
710
711 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
712 let active = self.state.read(cx).new_chat;
713 div()
714 .id("new-chat")
715 .size(px(NEW_CHAT_BUTTON_SIZE))
716 .flex_none()
717 .flex()
718 .items_center()
719 .justify_center()
720 .rounded(px(8.))
721 .bg(theme::surface_raised())
722 .cursor_pointer()
723 .when(active, |button| button.bg(theme::popup_hover()))
724 .hover(|button| button.bg(theme::popup_hover()))
725 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
726 .child(icon(IconName::Pencil, 16., theme::text_soft()))
727 .on_click(cx.listener(|this, _, _, cx| {
728 this.state.update(cx, |state, cx| state.start_new_chat(cx));
729 }))
730 }
731
732 fn chat_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
733 let state = self.state.clone();
734 let read_only = self.state.read(cx).mode.read_only;
735 Button::new("chat-list-more")
736 .icon(IconName::Ellipsis)
737 .ghost()
738 .size(px(NEW_CHAT_BUTTON_SIZE))
739 .rounded(px(8.))
740 .tooltip("More options")
741 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
742 }
743
744 fn draft_row(&self) -> impl IntoElement {
745 h_flex()
746 .id("new-chat-draft")
747 .mx(px(6.))
748 .h(px(ROW_HEIGHT))
749 .flex_none()
750 .px(px(10.))
751 .gap(px(12.))
752 .items_center()
753 .rounded(px(8.))
754 .bg(theme::surface_raised())
755 .child(
756 div()
757 .size(px(AVATAR_SIZE))
758 .flex_none()
759 .flex()
760 .items_center()
761 .justify_center()
762 .rounded_full()
763 .bg(theme::border_strong())
764 .child(icon(IconName::Pencil, 16., theme::text())),
765 )
766 .child(
767 v_flex()
768 .flex_1()
769 .min_w_0()
770 .gap(px(2.))
771 .child(
772 div()
773 .truncate()
774 .text_size(px(14.))
775 .text_color(theme::text())
776 .child("New chat"),
777 )
778 .child(
779 div()
780 .truncate()
781 .text_size(px(12.5))
782 .text_color(theme::text_muted())
783 .child("Draft"),
784 ),
785 )
786 }
787
788 fn section_header(
789 &self,
790 section: &Section,
791 menu: SectionMenuTarget,
792 cx: &mut Context<Self>,
793 ) -> impl IntoElement {
794 let drop_target = drop_target(section);
795 let toggle_id = section.id.clone();
796 let menu_state = self.state.clone();
797 h_flex()
798 .id(SharedString::from(format!("section-{}", section.id)))
799 .h(px(SECTION_HEIGHT))
800 .mt(px(SECTION_GAP))
801 .mx(px(6.))
802 .px(px(10.))
803 .gap(px(6.))
804 .items_center()
805 .rounded(px(6.))
806 .cursor_pointer()
807 .hover(|header| header.bg(theme::row_hover()))
808 .when_some(drop_target, |header, drop_target| {
809 header
810 .drag_over::<DraggedChat>(|style, _, _, _| {
811 style
812 .bg(theme::drop_background())
813 .border_1()
814 .border_color(theme::accent())
815 })
816 .on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
817 let target = drop_target.clone();
818 this.state.update(cx, |state, cx| {
819 state.move_chat(&dragged.id, target.as_deref(), cx)
820 });
821 }))
822 })
823 .child(icon(
824 if section.collapsed {
825 IconName::ChevronRight
826 } else {
827 IconName::ChevronDown
828 },
829 12.,
830 theme::text_muted(),
831 ))
832 .child(
833 div()
834 .flex_1()
835 .min_w_0()
836 .truncate()
837 .text_size(px(12.))
838 .font_weight(FontWeight::SEMIBOLD)
839 .text_color(theme::text_soft())
840 .child(section.name.clone()),
841 )
842 .when(section.collapsed && section.unread_chats > 0, |header| {
843 header.child(count_badge(section.unread_chats, false))
844 })
845 .child(
846 div()
847 .text_size(px(11.))
848 .text_color(theme::text_faint())
849 .child(section.count.to_string()),
850 )
851 .on_click(cx.listener(move |this, _, _, cx| {
852 let id = toggle_id.clone();
853 this.state
854 .update(cx, |state, cx| state.toggle_collapsed(&id, cx));
855 }))
856 .context_menu(move |popup, _, _| section_menu(popup, &menu_state, &menu))
857 }
858
859 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
860 let toggle_id = section.id.clone();
861 let label = if section.hidden_count > 0 {
862 format!("See more ({})", section.hidden_count)
863 } else {
864 "See less".to_owned()
865 };
866 div()
867 .id(SharedString::from(format!("see-more-{}", section.id)))
868 .mx(px(6.))
869 .pl(px(10. + AVATAR_SIZE + 12.))
870 .h(px(SEE_MORE_HEIGHT))
871 .flex()
872 .items_center()
873 .rounded(px(6.))
874 .cursor_pointer()
875 .text_size(px(12.5))
876 .text_color(theme::accent_text())
877 .hover(|row| row.bg(theme::row_hover()))
878 .child(label)
879 .on_click(cx.listener(move |this, _, _, cx| {
880 let id = toggle_id.clone();
881 this.state
882 .update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
883 }))
884 }
885
886 fn chat_row(
887 &self,
888 item: &ChatItem,
889 selected: bool,
890 local_preview: Option<&LocalPreview>,
891 proposal_agent: Option<&'static str>,
892 directory: &Directory,
893 menu: &MenuContext,
894 ) -> AnyElement {
895 let ring = if selected {
896 theme::surface_raised()
897 } else {
898 theme::surface()
899 };
900 let unread = item.unread.is_unread();
901 let presence = item
902 .presence_user
903 .as_deref()
904 .map(|user_id| directory.presence_of(user_id));
905 let avatar = spec_avatar(directory, &item.avatar, AVATAR_SIZE, ring);
906 let avatar = match presence {
907 Some(kind) => with_presence(avatar, kind, AVATAR_SIZE, ring).into_any_element(),
908 None => avatar,
909 };
910 let name = div()
911 .flex_1()
912 .min_w_0()
913 .truncate()
914 .text_size(px(14.))
915 .font_weight(if unread {
916 FontWeight::BOLD
917 } else {
918 FontWeight::NORMAL
919 })
920 .text_color(theme::text())
921 .child(item.title.clone());
922 let time = h_flex()
923 .flex_none()
924 .gap(px(4.))
925 .items_center()
926 .text_size(px(11.))
927 .text_color(if unread {
928 theme::accent_text()
929 } else {
930 theme::text_muted()
931 })
932 .child(item.time_label.clone());
933 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
934 theme::accent_text()
935 } else if unread {
936 theme::text_strong()
937 } else {
938 theme::text_muted()
939 };
940 let preview = match (proposal_agent, local_preview) {
941 (Some(agent), _) => Some(
942 h_flex()
943 .flex_1()
944 .min_w_0()
945 .overflow_hidden()
946 .text_size(px(12.5))
947 .text_color(theme::accent_text())
948 .child(div().truncate().child(format!("Proposal from {agent}"))),
949 ),
950 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
951 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
952 h_flex()
953 .flex_1()
954 .min_w_0()
955 .overflow_hidden()
956 .gap(px(4.))
957 .items_center()
958 .text_size(px(12.5))
959 .when(italic, |preview| preview.italic())
960 .text_color(preview_color)
961 .child(div().truncate().child(text))
962 }),
963 };
964 let lines = v_flex()
965 .flex_1()
966 .min_w_0()
967 .gap(px(2.))
968 .child(
969 h_flex()
970 .gap(px(8.))
971 .items_baseline()
972 .child(name)
973 .child(time),
974 )
975 .child(
976 h_flex()
977 .h(px(18.))
978 .gap(px(8.))
979 .items_center()
980 .child(preview.unwrap_or_else(|| div().flex_1()))
981 .children(match proposal_agent {
982 Some(_) => Some(
983 div()
984 .size(px(PROPOSAL_DOT_SIZE))
985 .flex_none()
986 .rounded_full()
987 .bg(theme::accent())
988 .into_any_element(),
989 ),
990 None => unread_marker(item.unread, item.muted)
991 .map(IntoElement::into_any_element),
992 }),
993 );
994 let state = self.state.clone();
995 let chat_id = item.id.clone();
996 let dragged = DraggedChat {
997 id: item.id.clone(),
998 title: item.title.clone(),
999 };
1000 let menu_context = menu.clone();
1001 let target = ChatMenuTarget {
1002 id: item.id.clone(),
1003 title: item.title.clone(),
1004 folder_id: item.folder_id.clone(),
1005 unread,
1006 muted: item.muted,
1007 is_group: item.is_group,
1008 member_count: item.member_count,
1009 };
1010 h_flex()
1011 .id(SharedString::from(format!("chat-{}", item.id)))
1012 .mx(px(6.))
1013 .h(px(ROW_HEIGHT))
1014 .flex_none()
1015 .px(px(10.))
1016 .gap(px(12.))
1017 .items_center()
1018 .rounded(px(8.))
1019 .cursor_pointer()
1020 .when(selected, |row| row.bg(theme::surface_raised()))
1021 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1022 .on_drag(dragged, |dragged, _, _, cx| {
1023 let title = dragged.title.clone();
1024 cx.new(|_| DragGhost { title })
1025 })
1026 .child(avatar)
1027 .child(lines)
1028 .on_click(move |_, _, cx| {
1029 let selection = Selection::Chat(chat_id.clone());
1030 state.update(cx, |state, cx| state.select(selection, cx));
1031 })
1032 .context_menu(move |popup, window, cx| {
1033 chat_menu(popup, window, cx, &menu_context, &target)
1034 })
1035 .into_any_element()
1036 }
1037
1038 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
1039 let proposal_agents = crate::agent_api::pending_agents(cx);
1040 let (sections, section_menus, menu, local_previews) = {
1041 let state = self.state.read(cx);
1042 let now = Utc::now();
1043 let offset = Local::now().offset().fix();
1044 let input = SectionInput {
1045 chats: &state.sidebar.chats,
1046 directory: &state.directory,
1047 collapsed: &state.collapsed,
1048 expanded_lists: &state.expanded_lists,
1049 typing: &state.typing,
1050 now,
1051 offset,
1052 };
1053 let sections = build_sections(&input);
1054 let menu = MenuContext {
1055 state: self.state.clone(),
1056 folders: state.directory.move_targets(),
1057 };
1058 let section_menus =
1059 section_menu_targets(&sections, &state.directory, state.mode.read_only);
1060 (sections, section_menus, menu, state.local_previews.clone())
1061 };
1062
1063 let top = -f32::from(self.chats_scroll.offset().y);
1064 let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
1065 let height = if measured > 1. {
1066 measured
1067 } else {
1068 window_height.max(FALLBACK_VIEWPORT)
1069 };
1070 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
1071
1072 let (selected, drafting) = {
1073 let state = self.state.read(cx);
1074 (
1075 state.selection.clone().filter(|_| !state.new_chat),
1076 state.new_chat,
1077 )
1078 };
1079 let mut faces: Vec<String> = Vec::new();
1080 let mut presence_users: Vec<String> = Vec::new();
1081 let mut y = 0.;
1082 let mut list = v_flex().w_full().pb(px(12.));
1083 let mut skipped_height = 0.;
1084 let mut others_end = None;
1085 let directory_state = self.state.clone();
1086 if drafting {
1087 list = list.child(self.draft_row());
1088 y += ROW_HEIGHT;
1089 }
1090 for (section, section_menu) in sections.iter().zip(section_menus) {
1091 list = with_spacer(list, &mut skipped_height);
1092 list = list.child(self.section_header(section, section_menu, cx));
1093 y += SECTION_GAP + SECTION_HEIGHT;
1094 if section.collapsed {
1095 continue;
1096 }
1097 for item in &section.items {
1098 let on_screen = y + ROW_HEIGHT >= visible_from && y <= visible_to;
1099 if on_screen {
1100 collect_faces(&item.avatar, &mut faces);
1101 presence_users.extend(item.presence_user.clone());
1102 }
1103 if on_screen {
1104 list = with_spacer(list, &mut skipped_height);
1105 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
1106 let directory = &directory_state.read(cx).directory;
1107 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
1108 list = list.child(self.chat_row(
1109 item,
1110 is_selected,
1111 local_preview,
1112 proposal_agents.get(&item.id).copied(),
1113 directory,
1114 &menu,
1115 ));
1116 } else {
1117 skipped_height += ROW_HEIGHT;
1118 }
1119 y += ROW_HEIGHT;
1120 }
1121 if section.kind == SectionKind::Others {
1122 others_end = Some(y);
1123 }
1124 if section.hidden_count > 0 || section.list_expanded {
1125 list = with_spacer(list, &mut skipped_height);
1126 list = list.child(self.see_more_row(section, cx));
1127 y += SEE_MORE_HEIGHT;
1128 }
1129 if section.show_empty_hint {
1130 list = with_spacer(list, &mut skipped_height);
1131 list = list.child(
1132 div()
1133 .ml(px(16.))
1134 .mr(px(16.))
1135 .h(px(HINT_HEIGHT))
1136 .flex()
1137 .items_center()
1138 .text_size(px(12.))
1139 .italic()
1140 .text_color(theme::text_faint())
1141 .child(EMPTY_FOLDER_HINT),
1142 );
1143 y += HINT_HEIGHT;
1144 }
1145 }
1146 let (has_older, loading_older) = self.state.read(cx).older_chats();
1147 let previous = self.older_chats_seen.replace((has_older, loading_older));
1148 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
1149 self.older_chats_trigger_top.set(None);
1150 }
1151 if has_older
1152 && wants_older_chats(
1153 others_end,
1154 top + height,
1155 top,
1156 self.older_chats_trigger_top.get(),
1157 loading_older,
1158 )
1159 {
1160 self.older_chats_trigger_top.set(Some(top));
1161 let state = self.state.clone();
1162 cx.defer(move |cx| state.read(cx).request_older_chats());
1163 }
1164 if loading_older {
1165 list = with_spacer(list, &mut skipped_height);
1166 list = list.child(
1167 div()
1168 .pl(px(16. + AVATAR_SIZE + 12.))
1169 .h(px(SEE_MORE_HEIGHT))
1170 .flex()
1171 .items_center()
1172 .text_size(px(12.5))
1173 .italic()
1174 .text_color(theme::text_faint())
1175 .child(LOADING_OLDER_LABEL),
1176 );
1177 }
1178 list = with_spacer(list, &mut skipped_height);
1179 self.request_lazy_data(faces, presence_users, cx);
1180 div()
1181 .id("chats-scroll")
1182 .flex_1()
1183 .min_h_0()
1184 .overflow_y_scroll()
1185 .track_scroll(&self.chats_scroll)
1186 .child(list)
1187 .into_any_element()
1188 }
1189
1190 fn request_lazy_data(
1191 &self,
1192 faces: Vec<String>,
1193 presence_users: Vec<String>,
1194 cx: &mut Context<Self>,
1195 ) {
1196 if faces.is_empty() && presence_users.is_empty() {
1197 return;
1198 }
1199 let state = self.state.clone();
1200 cx.defer(move |cx| {
1201 state.update(cx, |state, cx| {
1202 state.request_avatars(faces, cx);
1203 state.request_presence(presence_users, cx);
1204 });
1205 });
1206 }
1207
1208 fn channel_row(
1209 &self,
1210 channel_id: &str,
1211 team: &TeamRecord,
1212 channel: &ChannelRecord,
1213 selected: bool,
1214 notifications: ChannelNotifications,
1215 ) -> AnyElement {
1216 let unread = channel.unread;
1217 let name_style = channel_name_style(unread, true, selected);
1218 let state = self.state.clone();
1219 let menu_state = self.state.clone();
1220 let menu_channel_id = channel_id.to_owned();
1221 let selection = Selection::Channel(channel_id.to_owned());
1222 let now = Utc::now();
1223 let offset = Local::now().offset().fix();
1224 let time = channel
1225 .last_message_at
1226 .map(|time| {
1227 format::list_time_label(time, now.with_timezone(&offset).date_naive(), offset)
1228 })
1229 .unwrap_or_default();
1230 h_flex()
1231 .id(SharedString::from(format!("pinned-{channel_id}")))
1232 .mx(px(6.))
1233 .h(px(PINNED_CHANNEL_HEIGHT))
1234 .px(px(10.))
1235 .gap(px(12.))
1236 .items_center()
1237 .rounded(px(8.))
1238 .cursor_pointer()
1239 .when(selected, |row| row.bg(theme::surface_raised()))
1240 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1241 .child(square_avatar(&team.name, &team.id, 28., 7.))
1242 .child(
1243 v_flex()
1244 .flex_1()
1245 .min_w_0()
1246 .gap(px(1.))
1247 .child(
1248 h_flex()
1249 .gap(px(8.))
1250 .items_baseline()
1251 .child(
1252 div()
1253 .flex_1()
1254 .min_w_0()
1255 .truncate()
1256 .text_size(px(13.5))
1257 .font_weight(name_weight(name_style))
1258 .text_color(name_color(name_style))
1259 .child(format!("{} / {}", team.name, channel.name)),
1260 )
1261 .children(notification_badge(notifications.level))
1262 .child(
1263 div()
1264 .flex_none()
1265 .text_size(px(11.))
1266 .text_color(if unread {
1267 theme::accent_text()
1268 } else {
1269 theme::text_muted()
1270 })
1271 .child(time),
1272 ),
1273 )
1274 .child(
1275 h_flex().gap(px(8.)).items_center().child(
1276 div()
1277 .flex_1()
1278 .min_w_0()
1279 .truncate()
1280 .text_size(px(12.))
1281 .text_color(theme::text_muted())
1282 .child(team.name.clone()),
1283 ),
1284 ),
1285 )
1286 .on_click(move |_, _, cx| {
1287 let selection = selection.clone();
1288 state.update(cx, |state, cx| state.select(selection, cx));
1289 })
1290 .context_menu(move |popup, window, cx| {
1291 channel_menu(
1292 popup,
1293 window,
1294 cx,
1295 menu_state.clone(),
1296 &menu_channel_id,
1297 notifications,
1298 )
1299 })
1300 .into_any_element()
1301 }
1302
1303 fn plain_header(&self, label: &str) -> impl IntoElement {
1304 div()
1305 .h(px(SECTION_HEIGHT))
1306 .mt(px(SECTION_GAP))
1307 .px(px(16.))
1308 .flex()
1309 .items_center()
1310 .text_size(px(12.))
1311 .font_weight(FontWeight::SEMIBOLD)
1312 .text_color(theme::text_soft())
1313 .child(label.to_owned())
1314 }
1315
1316 fn team_block(
1317 &self,
1318 mut list: Div,
1319 entry: &SidebarTeam,
1320 selected: Option<&Selection>,
1321 cx: &mut Context<Self>,
1322 ) -> Div {
1323 let team_id = entry.team.id.clone();
1324 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1325 let name_style = team_name_style(entry, expanded);
1326 let toggle_id = team_id.clone();
1327 list = list.child(
1328 h_flex()
1329 .id(SharedString::from(format!("team-{team_id}")))
1330 .mx(px(6.))
1331 .h(px(TEAM_ROW_HEIGHT))
1332 .flex_none()
1333 .px(px(10.))
1334 .gap(px(8.))
1335 .items_center()
1336 .rounded(px(8.))
1337 .cursor_pointer()
1338 .hover(|row| row.bg(theme::row_hover()))
1339 .child(icon(
1340 if expanded {
1341 IconName::ChevronDown
1342 } else {
1343 IconName::ChevronRight
1344 },
1345 14.,
1346 theme::text_muted(),
1347 ))
1348 .child(square_avatar(&entry.team.name, &entry.team.id, 28., 7.))
1349 .child(
1350 div()
1351 .flex_1()
1352 .min_w_0()
1353 .truncate()
1354 .text_size(px(13.5))
1355 .font_weight(name_weight(name_style))
1356 .text_color(name_color(name_style))
1357 .child(entry.team.name.clone()),
1358 )
1359 .on_click(cx.listener(move |this, _, _, cx| {
1360 if !this.collapsed_teams.remove(&toggle_id) {
1361 this.collapsed_teams.insert(toggle_id.clone());
1362 }
1363 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1364 cx.notify();
1365 })),
1366 );
1367 if !expanded {
1368 return list;
1369 }
1370 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1371 let is_selected =
1372 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1373 for channel in entry
1374 .channels
1375 .iter()
1376 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1377 {
1378 list = list.child(self.team_channel_row(
1379 channel,
1380 is_selected(channel),
1381 channel_name_style(channel.unread, !is_hidden(channel), is_selected(channel)),
1382 entry.channel_notifications(&channel.id),
1383 ));
1384 }
1385 let hidden: Vec<&ChannelRecord> = entry
1386 .channels
1387 .iter()
1388 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1389 .collect();
1390 if hidden.is_empty() {
1391 return list;
1392 }
1393 let revealed = self.revealed_channel_teams.contains(&team_id);
1394 let toggle_id = team_id.clone();
1395 list = list.child(self.reveal_row(
1396 SharedString::from(format!("hidden-channels-{team_id}")),
1397 hidden_channels_label(hidden.len()),
1398 revealed,
1399 40.,
1400 cx.listener(move |this, _, _, cx| {
1401 if !this.revealed_channel_teams.remove(&toggle_id) {
1402 this.revealed_channel_teams.insert(toggle_id.clone());
1403 }
1404 cx.notify();
1405 }),
1406 ));
1407 if revealed {
1408 for channel in hidden {
1409 list = list.child(self.team_channel_row(
1410 channel,
1411 false,
1412 channel_name_style(channel.unread, false, false),
1413 entry.channel_notifications(&channel.id),
1414 ));
1415 }
1416 }
1417 list
1418 }
1419
1420 fn reveal_row(
1421 &self,
1422 id: SharedString,
1423 label: String,
1424 open: bool,
1425 indent: f32,
1426 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1427 ) -> impl IntoElement {
1428 h_flex()
1429 .id(id)
1430 .mx(px(6.))
1431 .h(px(REVEAL_ROW_HEIGHT))
1432 .flex_none()
1433 .pl(px(indent))
1434 .pr(px(10.))
1435 .gap(px(8.))
1436 .items_center()
1437 .rounded(px(8.))
1438 .cursor_pointer()
1439 .hover(|row| row.bg(theme::row_hover()))
1440 .child(icon(
1441 if open {
1442 IconName::ChevronDown
1443 } else {
1444 IconName::ChevronRight
1445 },
1446 12.,
1447 theme::text_faint(),
1448 ))
1449 .child(
1450 div()
1451 .text_size(px(12.5))
1452 .text_color(theme::text_muted())
1453 .child(label),
1454 )
1455 .on_click(on_click)
1456 }
1457
1458 fn team_channel_row(
1459 &self,
1460 channel: &ChannelRecord,
1461 is_selected: bool,
1462 name_style: NameStyle,
1463 notifications: ChannelNotifications,
1464 ) -> impl IntoElement {
1465 let state = self.state.clone();
1466 let menu_state = self.state.clone();
1467 let menu_channel_id = channel.id.clone();
1468 let selection = Selection::Channel(channel.id.clone());
1469 h_flex()
1470 .id(SharedString::from(format!("channel-{}", channel.id)))
1471 .mx(px(6.))
1472 .h(px(TEAM_ROW_HEIGHT))
1473 .flex_none()
1474 .pl(px(40.))
1475 .pr(px(10.))
1476 .gap(px(8.))
1477 .items_center()
1478 .rounded(px(8.))
1479 .cursor_pointer()
1480 .when(is_selected, |row| row.bg(theme::surface_raised()))
1481 .when(!is_selected, |row| {
1482 row.hover(|row| row.bg(theme::row_hover()))
1483 })
1484 .child(
1485 div()
1486 .w(px(14.))
1487 .flex()
1488 .justify_center()
1489 .text_size(px(15.))
1490 .text_color(theme::text_faint())
1491 .child("#"),
1492 )
1493 .child(
1494 div()
1495 .flex_1()
1496 .min_w_0()
1497 .truncate()
1498 .text_size(px(13.5))
1499 .font_weight(name_weight(name_style))
1500 .text_color(name_color(name_style))
1501 .child(channel.name.clone()),
1502 )
1503 .children(notification_badge(notifications.level))
1504 .on_click(move |_, _, cx| {
1505 let selection = selection.clone();
1506 state.update(cx, |state, cx| state.select(selection, cx));
1507 })
1508 .context_menu(move |popup, window, cx| {
1509 channel_menu(
1510 popup,
1511 window,
1512 cx,
1513 menu_state.clone(),
1514 &menu_channel_id,
1515 notifications,
1516 )
1517 })
1518 }
1519
1520 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1521 let (sidebar, pinned_ids, selected) = {
1522 let state = self.state.read(cx);
1523 (
1524 state.sidebar.clone(),
1525 state.directory.pinned_channels.clone(),
1526 state.selection.clone().filter(|_| !state.new_chat),
1527 )
1528 };
1529 let mut list = v_flex().w_full().pb(px(12.));
1530 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1531 .iter()
1532 .filter_map(|id| {
1533 sidebar.teams.iter().find_map(|entry| {
1534 entry
1535 .channels
1536 .iter()
1537 .find(|channel| &channel.id == id)
1538 .map(|channel| (entry, channel))
1539 })
1540 })
1541 .collect();
1542 if !pinned.is_empty() {
1543 list = list.child(self.plain_header(PINNED_LABEL));
1544 for (entry, channel) in pinned {
1545 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1546 list = list.child(self.channel_row(
1547 &channel.id,
1548 &entry.team,
1549 channel,
1550 is_selected,
1551 entry.channel_notifications(&channel.id),
1552 ));
1553 }
1554 }
1555 list = list.child(self.plain_header(TEAMS_LABEL));
1556 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1557 sidebar.teams.iter().partition(|entry| !entry.hidden);
1558 for entry in shown_teams {
1559 list = self.team_block(list, entry, selected.as_ref(), cx);
1560 }
1561 if !hidden_teams.is_empty() {
1562 let holds_selection = hidden_teams
1563 .iter()
1564 .any(|entry| team_holds(entry, selected.as_ref()));
1565 let open = self.hidden_teams_open || holds_selection;
1566 list = list.child(self.reveal_row(
1567 "hidden-teams".into(),
1568 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1569 open,
1570 10.,
1571 cx.listener(|this, _, _, cx| {
1572 this.hidden_teams_open = !this.hidden_teams_open;
1573 cx.notify();
1574 }),
1575 ));
1576 if open {
1577 for entry in hidden_teams {
1578 list = self.team_block(list, entry, selected.as_ref(), cx);
1579 }
1580 }
1581 }
1582 div()
1583 .id("channels-scroll")
1584 .flex_1()
1585 .min_h_0()
1586 .overflow_y_scroll()
1587 .track_scroll(&self.channels_scroll)
1588 .child(list)
1589 .into_any_element()
1590 }
1591}
1592
1593fn name_weight(style: NameStyle) -> FontWeight {
1594 match style.weight {
1595 NameWeight::Regular => FontWeight::NORMAL,
1596 NameWeight::Semibold => FontWeight::SEMIBOLD,
1597 NameWeight::Bold => FontWeight::BOLD,
1598 }
1599}
1600
1601fn name_color(style: NameStyle) -> Hsla {
1602 if style.highlighted {
1603 theme::text()
1604 } else {
1605 theme::text_muted()
1606 }
1607}
1608
1609fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1610 let name = match level {
1611 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1612 ChannelNotificationLevel::Off => IconName::BellOff,
1613 ChannelNotificationLevel::Feed => return None,
1614 };
1615 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1616}
1617
1618fn channel_menu(
1619 popup: PopupMenu,
1620 window: &mut Window,
1621 cx: &mut Context<PopupMenu>,
1622 state: Entity<AppState>,
1623 channel_id: &str,
1624 notifications: ChannelNotifications,
1625) -> PopupMenu {
1626 let channel_id = channel_id.to_owned();
1627 popup.submenu_with_icon(
1628 Some(menu_icon(IconName::Bell)),
1629 "Notifications",
1630 window,
1631 cx,
1632 move |submenu, _, _| {
1633 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1634 let (state, channel_id) = (state.clone(), channel_id.clone());
1635 PopupMenuItem::new(label)
1636 .checked(notifications.level == level)
1637 .on_click(move |_, _, cx| {
1638 let changed = ChannelNotifications {
1639 level,
1640 include_replies: notifications.include_replies
1641 && level != ChannelNotificationLevel::Off,
1642 };
1643 state.update(cx, |state, cx| {
1644 state.set_channel_notifications(&channel_id, changed, cx)
1645 });
1646 })
1647 };
1648 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1649 submenu
1650 .item(level_item(
1651 "Banner and activity",
1652 ChannelNotificationLevel::BannerAndFeed,
1653 ))
1654 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1655 .item(level_item("Off", ChannelNotificationLevel::Off))
1656 .separator()
1657 .item(
1658 PopupMenuItem::new("Include thread replies")
1659 .checked(notifications.include_replies)
1660 .disabled(notifications.level == ChannelNotificationLevel::Off)
1661 .on_click(move |_, _, cx| {
1662 let changed = ChannelNotifications {
1663 level: notifications.level,
1664 include_replies: !notifications.include_replies,
1665 };
1666 replies_state.update(cx, |state, cx| {
1667 state.set_channel_notifications(&replies_id, changed, cx)
1668 });
1669 }),
1670 )
1671 },
1672 )
1673}
1674
1675fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1676 !collapsed_teams.contains(team_id)
1677}
1678
1679fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1680 store
1681 .meta(COLLAPSED_TEAMS_META_KEY)
1682 .ok()
1683 .flatten()
1684 .map(|value| parse_collapsed_teams(&value))
1685 .unwrap_or_default()
1686}
1687
1688fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1689 let _ = store.set_meta(
1690 COLLAPSED_TEAMS_META_KEY,
1691 &serialize_collapsed_teams(collapsed_teams),
1692 );
1693}
1694
1695fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1696 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1697 team_ids.sort_unstable();
1698 serde_json::to_string(&team_ids).unwrap_or_default()
1699}
1700
1701fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1702 serde_json::from_str(value).unwrap_or_default()
1703}
1704
1705fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1706 entry
1707 .channels
1708 .iter()
1709 .any(|channel| selected == Some(&Selection::Channel(channel.id.clone())))
1710}
1711
1712fn hidden_channels_label(count: usize) -> String {
1713 if count == 1 {
1714 "1 hidden channel".to_owned()
1715 } else {
1716 format!("{count} hidden channels")
1717 }
1718}
1719
1720fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1721 match spec {
1722 AvatarSpec::Single(face) | AvatarSpec::Bot(face) => faces.extend(face.user_id.clone()),
1723 AvatarSpec::Pair(first, second) => {
1724 faces.extend(first.user_id.clone());
1725 faces.extend(second.user_id.clone());
1726 }
1727 AvatarSpec::Meeting | AvatarSpec::Muted => {}
1728 }
1729}
1730
1731fn with_spacer(list: Div, skipped_height: &mut f32) -> Div {
1732 let height = std::mem::take(skipped_height);
1733 if height > 0. {
1734 list.child(div().h(px(height)).flex_none())
1735 } else {
1736 list
1737 }
1738}
1739
1740impl Render for SidebarView {
1741 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1742 let window_height = f32::from(window.viewport_size().height);
1743 let body = match self.tab {
1744 SidebarTab::Activity => self.activity_panel.clone().into_any_element(),
1745 SidebarTab::Chats => self.chats_body(window_height, cx),
1746 SidebarTab::Channels => self.channels_body(cx),
1747 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1748 SidebarTab::Saved => self.saved_panel.clone().into_any_element(),
1749 SidebarTab::Agents => match &self.agents_panel {
1750 Some(panel) => panel.clone().into_any_element(),
1751 None => div().into_any_element(),
1752 },
1753 };
1754 let header = match self.tab {
1755 SidebarTab::Chats => Some(
1756 page_header(self.tab.title())
1757 .child(self.chat_list_menu_button(cx))
1758 .child(self.new_chat_button(cx)),
1759 ),
1760 SidebarTab::Channels | SidebarTab::Calls | SidebarTab::Agents => {
1761 Some(page_header(self.tab.title()))
1762 }
1763 SidebarTab::Activity | SidebarTab::Saved => None,
1764 };
1765 v_flex()
1766 .debug_selector(|| "shell/islands/sidebar".into())
1767 .w(px(SIDEBAR_WIDTH))
1768 .h_full()
1769 .flex_none()
1770 .bg(theme::surface())
1771 .rounded(px(10.))
1772 .overflow_hidden()
1773 .children(header)
1774 .child(body)
1775 }
1776}
1777
1778#[cfg(test)]
1779mod tests {
1780 use std::collections::HashSet;
1781
1782 use super::{
1783 drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,
1784 team_expanded,
1785 };
1786 use crate::data::PENDING_FOLDER_PREFIX;
1787 use crate::sidebar_model::{Section, SectionKind};
1788
1789 fn section(id: &str, kind: SectionKind) -> Section {
1790 Section {
1791 id: id.to_owned(),
1792 name: id.to_owned(),
1793 kind,
1794 collapsed: false,
1795 count: 0,
1796 unread_chats: 0,
1797 items: Vec::new(),
1798 hidden_count: 0,
1799 list_expanded: false,
1800 show_empty_hint: false,
1801 }
1802 }
1803
1804 #[test]
1805 fn pending_sections_take_no_dropped_chats() {
1806 let pending = format!("{PENDING_FOLDER_PREFIX}1");
1807 assert_eq!(drop_target(&section(&pending, SectionKind::Folder)), None);
1808 assert_eq!(
1809 drop_target(&section("work", SectionKind::Folder)),
1810 Some(Some("work".to_owned()))
1811 );
1812 assert_eq!(
1813 drop_target(&section("recent", SectionKind::Others)),
1814 Some(None)
1815 );
1816 }
1817
1818 #[test]
1819 fn teams_start_expanded() {
1820 assert!(team_expanded("t1", &HashSet::new()));
1821 }
1822
1823 #[test]
1824 fn collapsed_team_stays_closed() {
1825 let collapsed = HashSet::from(["t1".to_owned()]);
1826 assert!(!team_expanded("t1", &collapsed));
1827 assert!(team_expanded("t2", &collapsed));
1828 }
1829
1830 #[test]
1831 fn collapsed_teams_round_trip_as_json() {
1832 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1833 let json = serialize_collapsed_teams(&collapsed);
1834 assert_eq!(json, r#"["a","b"]"#);
1835 assert_eq!(parse_collapsed_teams(&json), collapsed);
1836 assert!(parse_collapsed_teams("garbage").is_empty());
1837 }
1838
1839 #[test]
1840 fn leave_text_counts_the_other_members() {
1841 assert_eq!(
1842 leave_description(4),
1843 "The 3 other members see that you left. You can only come back if someone adds you."
1844 );
1845 assert!(leave_description(2).starts_with("The other member sees"));
1846 assert!(leave_description(0).starts_with("The other members see"));
1847 }
1848}