BlueGit

ict rusty-teams

Files

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

sidebar.rs

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