BlueGit

ict rusty-teams

Files

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

sidebar.rs

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