BlueGit

ict rusty-teams

Files

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

sidebar.rs

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