BlueGit

ict rusty-teams

Files

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

sidebar.rs

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