BlueGit

ict rusty-teams

Files

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

sidebar.rs

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