BlueGit

ict rusty-teams

Files

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

sidebar.rs

sidebar.rs 62.8 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;
35
36const COLLAPSED_TEAMS_META_KEY: &str = "sidebar_collapsed_teams";
37pub const SIDEBAR_WIDTH: f32 = 300.;
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 MUTED_ICON_SIZE: f32 = 13.;
58const NOTIFICATION_ICON_SIZE: f32 = 13.;
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum SidebarTab {
62 Activity,
63 Chats,
64 Channels,
65 Calls,
66 Saved,
67}
68
69impl SidebarTab {
70 fn title(self) -> &'static str {
71 match self {
72 SidebarTab::Activity => "Activity",
73 SidebarTab::Chats => "Chats",
74 SidebarTab::Channels => "Channels",
75 SidebarTab::Calls => "Calls",
76 SidebarTab::Saved => "Saved",
77 }
78 }
79}
80
81#[derive(Clone)]
82struct DraggedChat {
83 id: String,
84 title: String,
85}
86
87struct DragGhost {
88 title: String,
89}
90
91impl Render for DragGhost {
92 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
93 div()
94 .px(px(12.))
95 .py(px(6.))
96 .rounded(px(8.))
97 .bg(theme::surface_raised())
98 .border_1()
99 .border_color(theme::accent())
100 .text_size(px(13.))
101 .text_color(theme::text())
102 .child(self.title.clone())
103 }
104}
105
106struct ChatMenuTarget {
107 id: String,
108 title: String,
109 pinned: bool,
110 unread: bool,
111 muted: bool,
112 is_group: bool,
113 member_count: usize,
114}
115
116#[derive(Clone)]
117struct MenuContext {
118 state: Entity<AppState>,
119 folders: Vec<(String, String)>,
120 favorites_id: Option<String>,
121}
122
123fn menu_icon(name: IconName) -> gpui_kit::component::Icon {
124 icon(name, MENU_ICON_SIZE, theme::text_muted())
125}
126
127fn chat_menu(
128 popup: PopupMenu,
129 window: &mut Window,
130 cx: &mut Context<PopupMenu>,
131 context: &MenuContext,
132 target: &ChatMenuTarget,
133) -> PopupMenu {
134 let pinned = target.pinned;
135 let pin_state = context.state.clone();
136 let pin_id = target.id.clone();
137 let mut popup = popup.item(
138 PopupMenuItem::new(if pinned { "Unpin" } else { "Pin" })
139 .icon(menu_icon(if pinned {
140 IconName::PinOff
141 } else {
142 IconName::Pin
143 }))
144 .on_click(move |_, _, cx| {
145 pin_state.update(cx, |state, cx| {
146 if pinned {
147 state.move_chat(&pin_id, None, cx);
148 } else {
149 state.pin_chat(&pin_id, cx);
150 }
151 });
152 }),
153 );
154 if !context.folders.is_empty() {
155 let folders = context.folders.clone();
156 let move_state = context.state.clone();
157 let move_id = target.id.clone();
158 popup = popup.submenu_with_icon(
159 Some(menu_icon(IconName::Folder)),
160 "Move to folder",
161 window,
162 cx,
163 move |submenu, _, _| {
164 folders.iter().fold(submenu, |submenu, (folder_id, name)| {
165 let (state, chat_id, folder_id) =
166 (move_state.clone(), move_id.clone(), folder_id.clone());
167 submenu.item(PopupMenuItem::new(name.clone()).on_click(move |_, _, cx| {
168 state.update(cx, |state, cx| {
169 state.move_chat(&chat_id, Some(&folder_id), cx)
170 });
171 }))
172 })
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
437fn 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 collapsed_teams: HashSet<String>,
476 revealed_channel_teams: HashSet<String>,
477 hidden_teams_open: bool,
478 chats_scroll: ScrollHandle,
479 older_chats_trigger_top: Cell<Option<f32>>,
480 older_chats_seen: Cell<(bool, bool)>,
481 channels_scroll: ScrollHandle,
482 calls_scroll: ScrollHandle,
483 _subscription: Subscription,
484 _state_observation: Subscription,
485 _agent_observation: Option<Subscription>,
486}
487
488fn preview_text(preview: &Preview) -> Option<(String, bool)> {
489 match preview {
490 Preview::Empty => None,
491 Preview::Deleted => Some((DELETED_PREVIEW.to_owned(), true)),
492 Preview::Typing(text) => Some((text.clone(), true)),
493 Preview::Text {
494 prefix: Some(prefix),
495 text,
496 } => Some((format!("{prefix}: {text}"), false)),
497 Preview::Text { prefix: None, text } => Some((text.clone(), false)),
498 }
499}
500
501fn preview_icon(text: &str) -> Option<IconName> {
502 match text.rsplit(": ").next()? {
503 "Image" => Some(IconName::Image),
504 "File" => Some(IconName::File),
505 _ => None,
506 }
507}
508
509fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
510 let row = h_flex()
511 .flex_1()
512 .min_w_0()
513 .overflow_hidden()
514 .gap(px(4.))
515 .items_center()
516 .text_size(px(12.5))
517 .text_color(color);
518 match preview {
519 LocalPreview::Draft(text) => row
520 .child(
521 div()
522 .flex_none()
523 .text_color(theme::accent_text())
524 .child("Draft:"),
525 )
526 .child(div().truncate().child(text.clone())),
527 LocalPreview::NotSent => row.child(
528 div()
529 .flex_none()
530 .text_color(theme::red_soft())
531 .child("Not sent"),
532 ),
533 }
534}
535
536impl SidebarView {
537 pub fn new(
538 state: Entity<AppState>,
539 activity_panel: Entity<ActivityPanel>,
540 saved_panel: Entity<SavedPanel>,
541 cx: &mut Context<Self>,
542 ) -> Self {
543 let subscription = cx.subscribe(&state, |this, state, event: &AppEvent, cx| {
544 if matches!(event, AppEvent::Selection) {
545 if state.read(cx).new_chat {
546 this.tab = SidebarTab::Chats;
547 }
548 this.expand_team_of_selection(cx);
549 }
550 if matches!(
551 event,
552 AppEvent::Sidebar
553 | AppEvent::CallHistory
554 | AppEvent::Selection
555 | AppEvent::Directory
556 | AppEvent::Typing
557 | AppEvent::LocalPreviews
558 ) {
559 cx.notify();
560 }
561 });
562 let state_observation = cx.observe(&state, |_, _, cx| cx.notify());
563 let agent_observation =
564 crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
565 let tab = if state.read(cx).start_on_channels {
566 SidebarTab::Channels
567 } else {
568 SidebarTab::Chats
569 };
570 let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
571 cx.spawn(async move |this, cx| {
572 loop {
573 cx.background_executor().timer(CALLS_REFRESH).await;
574 let alive = this.update(cx, |view, cx| {
575 if view.tab == SidebarTab::Calls {
576 cx.notify();
577 }
578 });
579 if alive.is_err() {
580 break;
581 }
582 }
583 })
584 .detach();
585 SidebarView {
586 state,
587 tab,
588 activity_panel,
589 saved_panel,
590 collapsed_teams,
591 revealed_channel_teams: HashSet::new(),
592 hidden_teams_open: false,
593 chats_scroll: ScrollHandle::new(),
594 older_chats_trigger_top: Cell::new(None),
595 older_chats_seen: Cell::new((false, false)),
596 channels_scroll: ScrollHandle::new(),
597 calls_scroll: ScrollHandle::new(),
598 _subscription: subscription,
599 _state_observation: state_observation,
600 _agent_observation: agent_observation,
601 }
602 }
603
604 pub fn tab(&self) -> SidebarTab {
605 self.tab
606 }
607
608 pub fn show_activity(&mut self, cx: &mut Context<Self>) {
609 self.open_tab(SidebarTab::Activity, cx);
610 }
611
612 pub fn show_chats(&mut self, cx: &mut Context<Self>) {
613 self.open_tab(SidebarTab::Chats, cx);
614 }
615
616 pub fn show_channels(&mut self, cx: &mut Context<Self>) {
617 self.open_tab(SidebarTab::Channels, cx);
618 }
619
620 pub fn show_calls(&mut self, cx: &mut Context<Self>) {
621 self.open_tab(SidebarTab::Calls, cx);
622 }
623
624 pub fn show_saved(&mut self, cx: &mut Context<Self>) {
625 self.open_tab(SidebarTab::Saved, cx);
626 }
627
628 pub fn open_tab(&mut self, tab: SidebarTab, cx: &mut Context<Self>) {
629 self.tab = tab;
630 match tab {
631 SidebarTab::Calls => self.state.update(cx, |state, cx| {
632 state.refresh_call_history(cx);
633 state.refresh_calendar(cx);
634 }),
635 SidebarTab::Saved => self.state.update(cx, |state, cx| state.refresh_saved(cx)),
636 _ => {}
637 }
638 cx.notify();
639 }
640
641 pub fn select_adjacent(&mut self, step: Step, cx: &mut Context<Self>) {
642 let selection = match self.tab {
643 SidebarTab::Chats => self
644 .state
645 .read(cx)
646 .adjacent_chat_id(step)
647 .map(Selection::Chat),
648 SidebarTab::Channels => self.adjacent_channel_id(step, cx).map(Selection::Channel),
649 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,
650 };
651 if let Some(selection) = selection {
652 self.state
653 .update(cx, |state, cx| state.select(selection, cx));
654 }
655 }
656
657 fn adjacent_channel_id(&self, step: Step, cx: &mut Context<Self>) -> Option<String> {
658 let state = self.state.read(cx);
659 let selected_channel = match &state.selection {
660 Some(Selection::Channel(channel_id)) => Some(channel_id.as_str()),
661 _ => None,
662 };
663 let input = ChannelOrderInput {
664 teams: &state.sidebar.teams,
665 pinned_ids: &state.directory.pinned_channels,
666 collapsed_teams: &self.collapsed_teams,
667 revealed_channel_teams: &self.revealed_channel_teams,
668 hidden_teams_open: self.hidden_teams_open,
669 selected_channel,
670 };
671 step_id(&visible_channel_ids(&input), selected_channel, step)
672 }
673
674 fn expand_team_of_selection(&mut self, cx: &mut Context<Self>) {
675 let state = self.state.read(cx);
676 let Some(Selection::Channel(channel_id)) = state.selection.clone() else {
677 return;
678 };
679 let team_id = state
680 .sidebar
681 .teams
682 .iter()
683 .find(|entry| {
684 entry
685 .channels
686 .iter()
687 .any(|channel| channel.id == channel_id)
688 })
689 .map(|entry| entry.team.id.clone());
690 if let Some(team_id) = team_id
691 && self.collapsed_teams.remove(&team_id)
692 {
693 save_collapsed_teams(&self.state.read(cx).store, &self.collapsed_teams);
694 }
695 }
696
697 fn new_chat_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
698 let active = self.state.read(cx).new_chat;
699 div()
700 .id("new-chat")
701 .size(px(NEW_CHAT_BUTTON_SIZE))
702 .flex_none()
703 .flex()
704 .items_center()
705 .justify_center()
706 .rounded(px(8.))
707 .bg(theme::surface_raised())
708 .cursor_pointer()
709 .when(active, |button| button.bg(theme::popup_hover()))
710 .hover(|button| button.bg(theme::popup_hover()))
711 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
712 .child(icon(IconName::Pencil, 16., theme::text_soft()))
713 .on_click(cx.listener(|this, _, _, cx| {
714 this.state.update(cx, |state, cx| state.start_new_chat(cx));
715 }))
716 }
717
718 fn chat_list_menu_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
719 let state = self.state.clone();
720 let read_only = self.state.read(cx).mode.read_only;
721 Button::new("chat-list-more")
722 .icon(IconName::Ellipsis)
723 .ghost()
724 .size(px(NEW_CHAT_BUTTON_SIZE))
725 .rounded(px(8.))
726 .tooltip("More options")
727 .dropdown_menu(move |menu, _, _| menu.item(new_section_item(&state, read_only)))
728 }
729
730 fn draft_row(&self) -> impl IntoElement {
731 h_flex()
732 .id("new-chat-draft")
733 .mx(px(6.))
734 .h(px(ROW_HEIGHT))
735 .px(px(10.))
736 .gap(px(12.))
737 .items_center()
738 .rounded(px(8.))
739 .bg(theme::surface_raised())
740 .child(
741 div()
742 .size(px(AVATAR_SIZE))
743 .flex_none()
744 .flex()
745 .items_center()
746 .justify_center()
747 .rounded_full()
748 .bg(theme::border_strong())
749 .child(icon(IconName::Pencil, 16., theme::text())),
750 )
751 .child(
752 v_flex()
753 .flex_1()
754 .min_w_0()
755 .gap(px(2.))
756 .child(
757 div()
758 .truncate()
759 .text_size(px(14.))
760 .text_color(theme::text())
761 .child("New chat"),
762 )
763 .child(
764 div()
765 .truncate()
766 .text_size(px(12.5))
767 .text_color(theme::text_muted())
768 .child("Draft"),
769 ),
770 )
771 }
772
773 fn section_header(
774 &self,
775 section: &Section,
776 menu: SectionMenuTarget,
777 cx: &mut Context<Self>,
778 ) -> impl IntoElement {
779 let drop_target = drop_target(section);
780 let toggle_id = section.id.clone();
781 let menu_state = self.state.clone();
782 h_flex()
783 .id(SharedString::from(format!("section-{}", section.id)))
784 .h(px(SECTION_HEIGHT))
785 .mt(px(SECTION_GAP))
786 .mx(px(6.))
787 .px(px(10.))
788 .gap(px(6.))
789 .items_center()
790 .rounded(px(6.))
791 .cursor_pointer()
792 .hover(|header| header.bg(theme::row_hover()))
793 .when_some(drop_target, |header, drop_target| {
794 header
795 .drag_over::<DraggedChat>(|style, _, _, _| {
796 style
797 .bg(theme::drop_background())
798 .border_1()
799 .border_dashed()
800 .border_color(theme::accent())
801 })
802 .on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
803 let target = drop_target.clone();
804 this.state.update(cx, |state, cx| {
805 state.move_chat(&dragged.id, target.as_deref(), cx)
806 });
807 }))
808 })
809 .child(icon(
810 if section.collapsed {
811 IconName::ChevronRight
812 } else {
813 IconName::ChevronDown
814 },
815 12.,
816 theme::text_muted(),
817 ))
818 .child(
819 div()
820 .flex_1()
821 .min_w_0()
822 .truncate()
823 .text_size(px(12.))
824 .font_weight(FontWeight::SEMIBOLD)
825 .text_color(theme::text_soft())
826 .child(section.name.clone()),
827 )
828 .when(section.collapsed && section.unread_chats > 0, |header| {
829 header.child(count_badge(section.unread_chats, false))
830 })
831 .child(
832 div()
833 .text_size(px(11.))
834 .text_color(theme::text_faint())
835 .child(section.count.to_string()),
836 )
837 .on_click(cx.listener(move |this, _, _, cx| {
838 let id = toggle_id.clone();
839 this.state
840 .update(cx, |state, cx| state.toggle_collapsed(&id, cx));
841 }))
842 .context_menu(move |popup, _, _| section_menu(popup, &menu_state, &menu))
843 }
844
845 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
846 let toggle_id = section.id.clone();
847 let label = if section.hidden_count > 0 {
848 format!("See more ({})", section.hidden_count)
849 } else {
850 "See less".to_owned()
851 };
852 div()
853 .id(SharedString::from(format!("see-more-{}", section.id)))
854 .mx(px(6.))
855 .pl(px(10. + AVATAR_SIZE + 12.))
856 .h(px(SEE_MORE_HEIGHT))
857 .flex()
858 .items_center()
859 .rounded(px(6.))
860 .cursor_pointer()
861 .text_size(px(12.5))
862 .text_color(theme::accent_text())
863 .hover(|row| row.bg(theme::row_hover()))
864 .child(label)
865 .on_click(cx.listener(move |this, _, _, cx| {
866 let id = toggle_id.clone();
867 this.state
868 .update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
869 }))
870 }
871
872 fn chat_row(
873 &self,
874 item: &ChatItem,
875 selected: bool,
876 local_preview: Option<&LocalPreview>,
877 proposal_agent: Option<&'static str>,
878 directory: &Directory,
879 menu: &MenuContext,
880 ) -> AnyElement {
881 let ring = if selected {
882 theme::surface_raised()
883 } else {
884 theme::surface()
885 };
886 let unread = item.unread.is_unread();
887 let presence = item
888 .presence_user
889 .as_deref()
890 .map(|user_id| directory.presence_of(user_id));
891 let avatar = spec_avatar(directory, &item.avatar, AVATAR_SIZE, ring);
892 let avatar = match presence {
893 Some(kind) => with_presence(avatar, kind, AVATAR_SIZE, ring).into_any_element(),
894 None => avatar,
895 };
896 let name = div()
897 .flex_1()
898 .min_w_0()
899 .truncate()
900 .text_size(px(14.))
901 .font_weight(if unread {
902 FontWeight::BOLD
903 } else {
904 FontWeight::NORMAL
905 })
906 .text_color(theme::text())
907 .child(item.title.clone());
908 let time = h_flex()
909 .flex_none()
910 .gap(px(4.))
911 .items_center()
912 .text_size(px(11.))
913 .text_color(if unread {
914 theme::accent_text()
915 } else {
916 theme::text_muted()
917 })
918 .when(item.muted, |time| {
919 time.child(icon(
920 IconName::BellOff,
921 MUTED_ICON_SIZE,
922 theme::text_faint(),
923 ))
924 })
925 .child(item.time_label.clone());
926 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
927 theme::accent_text()
928 } else if item.muted {
929 theme::text_faint()
930 } else if unread {
931 theme::text_strong()
932 } else {
933 theme::text_muted()
934 };
935 let preview = match (proposal_agent, local_preview) {
936 (Some(agent), _) => Some(
937 h_flex()
938 .flex_1()
939 .min_w_0()
940 .overflow_hidden()
941 .text_size(px(12.5))
942 .text_color(theme::accent_text())
943 .child(div().truncate().child(format!("Proposal from {agent}"))),
944 ),
945 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
946 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
947 let glyph = preview_icon(&text);
948 h_flex()
949 .flex_1()
950 .min_w_0()
951 .overflow_hidden()
952 .gap(px(4.))
953 .items_center()
954 .text_size(px(12.5))
955 .when(italic, |preview| preview.italic())
956 .text_color(preview_color)
957 .children(glyph.map(|name| icon(name, 12., preview_color)))
958 .child(div().truncate().child(text))
959 }),
960 };
961 let lines = v_flex()
962 .flex_1()
963 .min_w_0()
964 .gap(px(2.))
965 .child(
966 h_flex()
967 .gap(px(8.))
968 .items_baseline()
969 .child(name)
970 .child(time),
971 )
972 .child(
973 h_flex()
974 .h(px(18.))
975 .gap(px(8.))
976 .items_center()
977 .child(preview.unwrap_or_else(|| div().flex_1()))
978 .children(match proposal_agent {
979 Some(_) => Some(
980 div()
981 .size(px(PROPOSAL_DOT_SIZE))
982 .flex_none()
983 .rounded_full()
984 .bg(theme::accent())
985 .into_any_element(),
986 ),
987 None => unread_marker(item.unread, item.muted)
988 .map(IntoElement::into_any_element),
989 }),
990 );
991 let state = self.state.clone();
992 let chat_id = item.id.clone();
993 let dragged = DraggedChat {
994 id: item.id.clone(),
995 title: item.title.clone(),
996 };
997 let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;
998 let menu_context = menu.clone();
999 let target = ChatMenuTarget {
1000 id: item.id.clone(),
1001 title: item.title.clone(),
1002 pinned,
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 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
1055 };
1056 let section_menus =
1057 section_menu_targets(&sections, &state.directory, state.mode.read_only);
1058 (sections, section_menus, menu, state.local_previews.clone())
1059 };
1060
1061 let top = -f32::from(self.chats_scroll.offset().y);
1062 let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
1063 let height = if measured > 1. {
1064 measured
1065 } else {
1066 window_height.max(FALLBACK_VIEWPORT)
1067 };
1068 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
1069
1070 let (selected, drafting) = {
1071 let state = self.state.read(cx);
1072 (
1073 state.selection.clone().filter(|_| !state.new_chat),
1074 state.new_chat,
1075 )
1076 };
1077 let mut faces: Vec<String> = Vec::new();
1078 let mut presence_users: Vec<String> = Vec::new();
1079 let mut y = 0.;
1080 let mut list = v_flex().w_full().pb(px(12.));
1081 let mut skipped_height = 0.;
1082 let mut others_end = None;
1083 let directory_state = self.state.clone();
1084 if drafting {
1085 list = list.child(self.draft_row());
1086 y += ROW_HEIGHT;
1087 }
1088 for (section, section_menu) in sections.iter().zip(section_menus) {
1089 list = with_spacer(list, &mut skipped_height);
1090 list = list.child(self.section_header(section, section_menu, cx));
1091 y += SECTION_GAP + SECTION_HEIGHT;
1092 if section.collapsed {
1093 continue;
1094 }
1095 for item in &section.items {
1096 let on_screen = y + ROW_HEIGHT >= visible_from && y <= visible_to;
1097 if on_screen {
1098 collect_faces(&item.avatar, &mut faces);
1099 presence_users.extend(item.presence_user.clone());
1100 }
1101 if on_screen {
1102 list = with_spacer(list, &mut skipped_height);
1103 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
1104 let directory = &directory_state.read(cx).directory;
1105 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
1106 list = list.child(self.chat_row(
1107 item,
1108 is_selected,
1109 local_preview,
1110 proposal_agents.get(&item.id).copied(),
1111 directory,
1112 &menu,
1113 ));
1114 } else {
1115 skipped_height += ROW_HEIGHT;
1116 }
1117 y += ROW_HEIGHT;
1118 }
1119 if section.kind == SectionKind::Others {
1120 others_end = Some(y);
1121 }
1122 if section.hidden_count > 0 || section.list_expanded {
1123 list = with_spacer(list, &mut skipped_height);
1124 list = list.child(self.see_more_row(section, cx));
1125 y += SEE_MORE_HEIGHT;
1126 }
1127 if section.show_empty_hint {
1128 list = with_spacer(list, &mut skipped_height);
1129 list = list.child(
1130 div()
1131 .ml(px(16.))
1132 .mr(px(16.))
1133 .h(px(HINT_HEIGHT))
1134 .flex()
1135 .items_center()
1136 .text_size(px(12.))
1137 .italic()
1138 .text_color(theme::text_faint())
1139 .child(EMPTY_FOLDER_HINT),
1140 );
1141 y += HINT_HEIGHT;
1142 }
1143 }
1144 let (has_older, loading_older) = self.state.read(cx).older_chats();
1145 let previous = self.older_chats_seen.replace((has_older, loading_older));
1146 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
1147 self.older_chats_trigger_top.set(None);
1148 }
1149 if has_older
1150 && wants_older_chats(
1151 others_end,
1152 top + height,
1153 top,
1154 self.older_chats_trigger_top.get(),
1155 loading_older,
1156 )
1157 {
1158 self.older_chats_trigger_top.set(Some(top));
1159 let state = self.state.clone();
1160 cx.defer(move |cx| state.read(cx).request_older_chats());
1161 }
1162 if loading_older {
1163 list = with_spacer(list, &mut skipped_height);
1164 list = list.child(
1165 div()
1166 .pl(px(16. + AVATAR_SIZE + 12.))
1167 .h(px(SEE_MORE_HEIGHT))
1168 .flex()
1169 .items_center()
1170 .text_size(px(12.5))
1171 .italic()
1172 .text_color(theme::text_faint())
1173 .child(LOADING_OLDER_LABEL),
1174 );
1175 }
1176 list = with_spacer(list, &mut skipped_height);
1177 self.request_lazy_data(faces, presence_users, cx);
1178 div()
1179 .id("chats-scroll")
1180 .flex_1()
1181 .min_h_0()
1182 .overflow_y_scroll()
1183 .track_scroll(&self.chats_scroll)
1184 .child(list)
1185 .into_any_element()
1186 }
1187
1188 fn request_lazy_data(
1189 &self,
1190 faces: Vec<String>,
1191 presence_users: Vec<String>,
1192 cx: &mut Context<Self>,
1193 ) {
1194 if faces.is_empty() && presence_users.is_empty() {
1195 return;
1196 }
1197 let state = self.state.clone();
1198 cx.defer(move |cx| {
1199 state.update(cx, |state, cx| {
1200 state.request_avatars(faces, cx);
1201 state.request_presence(presence_users, cx);
1202 });
1203 });
1204 }
1205
1206 fn channel_row(
1207 &self,
1208 channel_id: &str,
1209 team: &TeamRecord,
1210 channel: &ChannelRecord,
1211 selected: bool,
1212 notifications: ChannelNotifications,
1213 ) -> AnyElement {
1214 let unread = channel.unread;
1215 let 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(if unread {
1255 FontWeight::BOLD
1256 } else {
1257 FontWeight::NORMAL
1258 })
1259 .text_color(theme::text())
1260 .child(format!("{} / {}", team.name, channel.name)),
1261 )
1262 .children(notification_badge(notifications.level))
1263 .child(
1264 div()
1265 .flex_none()
1266 .text_size(px(11.))
1267 .text_color(if unread {
1268 theme::accent_text()
1269 } else {
1270 theme::text_muted()
1271 })
1272 .child(time),
1273 ),
1274 )
1275 .child(
1276 h_flex()
1277 .gap(px(8.))
1278 .items_center()
1279 .child(
1280 div()
1281 .flex_1()
1282 .min_w_0()
1283 .truncate()
1284 .text_size(px(12.))
1285 .text_color(theme::text_muted())
1286 .child(team.name.clone()),
1287 )
1288 .when(unread, |line| line.child(dot(7.))),
1289 ),
1290 )
1291 .on_click(move |_, _, cx| {
1292 let selection = selection.clone();
1293 state.update(cx, |state, cx| state.select(selection, cx));
1294 })
1295 .context_menu(move |popup, window, cx| {
1296 channel_menu(
1297 popup,
1298 window,
1299 cx,
1300 menu_state.clone(),
1301 &menu_channel_id,
1302 notifications,
1303 )
1304 })
1305 .into_any_element()
1306 }
1307
1308 fn plain_header(&self, label: &str) -> impl IntoElement {
1309 div()
1310 .h(px(SECTION_HEIGHT))
1311 .mt(px(SECTION_GAP))
1312 .px(px(16.))
1313 .flex()
1314 .items_center()
1315 .text_size(px(12.))
1316 .font_weight(FontWeight::SEMIBOLD)
1317 .text_color(theme::text_soft())
1318 .child(label.to_owned())
1319 }
1320
1321 fn team_block(
1322 &self,
1323 mut list: Div,
1324 entry: &SidebarTeam,
1325 selected: Option<&Selection>,
1326 cx: &mut Context<Self>,
1327 ) -> Div {
1328 let team_id = entry.team.id.clone();
1329 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1330 let unread = entry.channels.iter().any(|channel| channel.unread);
1331 let toggle_id = team_id.clone();
1332 list = list.child(
1333 h_flex()
1334 .id(SharedString::from(format!("team-{team_id}")))
1335 .mx(px(6.))
1336 .h(px(TEAM_ROW_HEIGHT))
1337 .px(px(10.))
1338 .gap(px(8.))
1339 .items_center()
1340 .rounded(px(8.))
1341 .cursor_pointer()
1342 .hover(|row| row.bg(theme::row_hover()))
1343 .child(icon(
1344 if expanded {
1345 IconName::ChevronDown
1346 } else {
1347 IconName::ChevronRight
1348 },
1349 14.,
1350 theme::text_muted(),
1351 ))
1352 .child(square_avatar(&entry.team.name, &entry.team.id, 28., 7.))
1353 .child(
1354 div()
1355 .flex_1()
1356 .min_w_0()
1357 .truncate()
1358 .text_size(px(13.5))
1359 .font_weight(if unread || expanded {
1360 FontWeight::SEMIBOLD
1361 } else {
1362 FontWeight::NORMAL
1363 })
1364 .text_color(theme::text())
1365 .child(entry.team.name.clone()),
1366 )
1367 .when(unread && !expanded, |row| row.child(dot(7.)))
1368 .on_click(cx.listener(move |this, _, _, cx| {
1369 if !this.collapsed_teams.remove(&toggle_id) {
1370 this.collapsed_teams.insert(toggle_id.clone());
1371 }
1372 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1373 cx.notify();
1374 })),
1375 );
1376 if !expanded {
1377 return list;
1378 }
1379 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1380 let is_selected =
1381 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1382 for channel in entry
1383 .channels
1384 .iter()
1385 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1386 {
1387 list = list.child(self.team_channel_row(
1388 channel,
1389 is_selected(channel),
1390 entry.channel_notifications(&channel.id),
1391 ));
1392 }
1393 let hidden: Vec<&ChannelRecord> = entry
1394 .channels
1395 .iter()
1396 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1397 .collect();
1398 if hidden.is_empty() {
1399 return list;
1400 }
1401 let revealed = self.revealed_channel_teams.contains(&team_id);
1402 let toggle_id = team_id.clone();
1403 list = list.child(self.reveal_row(
1404 SharedString::from(format!("hidden-channels-{team_id}")),
1405 hidden_channels_label(hidden.len()),
1406 revealed,
1407 40.,
1408 cx.listener(move |this, _, _, cx| {
1409 if !this.revealed_channel_teams.remove(&toggle_id) {
1410 this.revealed_channel_teams.insert(toggle_id.clone());
1411 }
1412 cx.notify();
1413 }),
1414 ));
1415 if revealed {
1416 for channel in hidden {
1417 list = list.child(self.team_channel_row(
1418 channel,
1419 false,
1420 entry.channel_notifications(&channel.id),
1421 ));
1422 }
1423 }
1424 list
1425 }
1426
1427 fn reveal_row(
1428 &self,
1429 id: SharedString,
1430 label: String,
1431 open: bool,
1432 indent: f32,
1433 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1434 ) -> impl IntoElement {
1435 h_flex()
1436 .id(id)
1437 .mx(px(6.))
1438 .h(px(REVEAL_ROW_HEIGHT))
1439 .pl(px(indent))
1440 .pr(px(10.))
1441 .gap(px(8.))
1442 .items_center()
1443 .rounded(px(8.))
1444 .cursor_pointer()
1445 .hover(|row| row.bg(theme::row_hover()))
1446 .child(icon(
1447 if open {
1448 IconName::ChevronDown
1449 } else {
1450 IconName::ChevronRight
1451 },
1452 12.,
1453 theme::text_faint(),
1454 ))
1455 .child(
1456 div()
1457 .text_size(px(12.5))
1458 .text_color(theme::text_muted())
1459 .child(label),
1460 )
1461 .on_click(on_click)
1462 }
1463
1464 fn team_channel_row(
1465 &self,
1466 channel: &ChannelRecord,
1467 is_selected: bool,
1468 notifications: ChannelNotifications,
1469 ) -> impl IntoElement {
1470 let state = self.state.clone();
1471 let menu_state = self.state.clone();
1472 let menu_channel_id = channel.id.clone();
1473 let selection = Selection::Channel(channel.id.clone());
1474 h_flex()
1475 .id(SharedString::from(format!("channel-{}", channel.id)))
1476 .mx(px(6.))
1477 .h(px(TEAM_ROW_HEIGHT))
1478 .pl(px(40.))
1479 .pr(px(10.))
1480 .gap(px(8.))
1481 .items_center()
1482 .rounded(px(8.))
1483 .cursor_pointer()
1484 .when(is_selected, |row| row.bg(theme::surface_raised()))
1485 .when(!is_selected, |row| {
1486 row.hover(|row| row.bg(theme::row_hover()))
1487 })
1488 .child(
1489 div()
1490 .w(px(14.))
1491 .flex()
1492 .justify_center()
1493 .text_size(px(15.))
1494 .text_color(theme::text_faint())
1495 .child("#"),
1496 )
1497 .child(
1498 div()
1499 .flex_1()
1500 .min_w_0()
1501 .truncate()
1502 .text_size(px(13.5))
1503 .font_weight(if channel.unread {
1504 FontWeight::BOLD
1505 } else {
1506 FontWeight::NORMAL
1507 })
1508 .text_color(theme::text())
1509 .child(channel.name.clone()),
1510 )
1511 .children(notification_badge(notifications.level))
1512 .when(channel.unread, |row| row.child(dot(7.)))
1513 .on_click(move |_, _, cx| {
1514 let selection = selection.clone();
1515 state.update(cx, |state, cx| state.select(selection, cx));
1516 })
1517 .context_menu(move |popup, window, cx| {
1518 channel_menu(
1519 popup,
1520 window,
1521 cx,
1522 menu_state.clone(),
1523 &menu_channel_id,
1524 notifications,
1525 )
1526 })
1527 }
1528
1529 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1530 let (sidebar, pinned_ids, selected) = {
1531 let state = self.state.read(cx);
1532 (
1533 state.sidebar.clone(),
1534 state.directory.pinned_channels.clone(),
1535 state.selection.clone().filter(|_| !state.new_chat),
1536 )
1537 };
1538 let mut list = v_flex().w_full().pb(px(12.));
1539 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1540 .iter()
1541 .filter_map(|id| {
1542 sidebar.teams.iter().find_map(|entry| {
1543 entry
1544 .channels
1545 .iter()
1546 .find(|channel| &channel.id == id)
1547 .map(|channel| (entry, channel))
1548 })
1549 })
1550 .collect();
1551 if !pinned.is_empty() {
1552 list = list.child(self.plain_header(PINNED_LABEL));
1553 for (entry, channel) in pinned {
1554 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1555 list = list.child(self.channel_row(
1556 &channel.id,
1557 &entry.team,
1558 channel,
1559 is_selected,
1560 entry.channel_notifications(&channel.id),
1561 ));
1562 }
1563 }
1564 list = list.child(self.plain_header(TEAMS_LABEL));
1565 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1566 sidebar.teams.iter().partition(|entry| !entry.hidden);
1567 for entry in shown_teams {
1568 list = self.team_block(list, entry, selected.as_ref(), cx);
1569 }
1570 if !hidden_teams.is_empty() {
1571 let holds_selection = hidden_teams
1572 .iter()
1573 .any(|entry| team_holds(entry, selected.as_ref()));
1574 let open = self.hidden_teams_open || holds_selection;
1575 list = list.child(self.reveal_row(
1576 "hidden-teams".into(),
1577 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1578 open,
1579 10.,
1580 cx.listener(|this, _, _, cx| {
1581 this.hidden_teams_open = !this.hidden_teams_open;
1582 cx.notify();
1583 }),
1584 ));
1585 if open {
1586 for entry in hidden_teams {
1587 list = self.team_block(list, entry, selected.as_ref(), cx);
1588 }
1589 }
1590 }
1591 div()
1592 .id("channels-scroll")
1593 .flex_1()
1594 .min_h_0()
1595 .overflow_y_scroll()
1596 .track_scroll(&self.channels_scroll)
1597 .child(list)
1598 .into_any_element()
1599 }
1600}
1601
1602fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1603 let name = match level {
1604 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1605 ChannelNotificationLevel::Off => IconName::BellOff,
1606 ChannelNotificationLevel::Feed => return None,
1607 };
1608 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1609}
1610
1611fn channel_menu(
1612 popup: PopupMenu,
1613 window: &mut Window,
1614 cx: &mut Context<PopupMenu>,
1615 state: Entity<AppState>,
1616 channel_id: &str,
1617 notifications: ChannelNotifications,
1618) -> PopupMenu {
1619 let channel_id = channel_id.to_owned();
1620 popup.submenu_with_icon(
1621 Some(menu_icon(IconName::Bell)),
1622 "Notifications",
1623 window,
1624 cx,
1625 move |submenu, _, _| {
1626 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1627 let (state, channel_id) = (state.clone(), channel_id.clone());
1628 PopupMenuItem::new(label)
1629 .checked(notifications.level == level)
1630 .on_click(move |_, _, cx| {
1631 let changed = ChannelNotifications {
1632 level,
1633 include_replies: notifications.include_replies
1634 && level != ChannelNotificationLevel::Off,
1635 };
1636 state.update(cx, |state, cx| {
1637 state.set_channel_notifications(&channel_id, changed, cx)
1638 });
1639 })
1640 };
1641 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1642 submenu
1643 .item(level_item(
1644 "Banner and activity",
1645 ChannelNotificationLevel::BannerAndFeed,
1646 ))
1647 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1648 .item(level_item("Off", ChannelNotificationLevel::Off))
1649 .separator()
1650 .item(
1651 PopupMenuItem::new("Include thread replies")
1652 .checked(notifications.include_replies)
1653 .disabled(notifications.level == ChannelNotificationLevel::Off)
1654 .on_click(move |_, _, cx| {
1655 let changed = ChannelNotifications {
1656 level: notifications.level,
1657 include_replies: !notifications.include_replies,
1658 };
1659 replies_state.update(cx, |state, cx| {
1660 state.set_channel_notifications(&replies_id, changed, cx)
1661 });
1662 }),
1663 )
1664 },
1665 )
1666}
1667
1668fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1669 !collapsed_teams.contains(team_id)
1670}
1671
1672fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1673 store
1674 .meta(COLLAPSED_TEAMS_META_KEY)
1675 .ok()
1676 .flatten()
1677 .map(|value| parse_collapsed_teams(&value))
1678 .unwrap_or_default()
1679}
1680
1681fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1682 let _ = store.set_meta(
1683 COLLAPSED_TEAMS_META_KEY,
1684 &serialize_collapsed_teams(collapsed_teams),
1685 );
1686}
1687
1688fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1689 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1690 team_ids.sort_unstable();
1691 serde_json::to_string(&team_ids).unwrap_or_default()
1692}
1693
1694fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1695 serde_json::from_str(value).unwrap_or_default()
1696}
1697
1698fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1699 entry
1700 .channels
1701 .iter()
1702 .any(|channel| selected == Some(&Selection::Channel(channel.id.clone())))
1703}
1704
1705fn hidden_channels_label(count: usize) -> String {
1706 if count == 1 {
1707 "1 hidden channel".to_owned()
1708 } else {
1709 format!("{count} hidden channels")
1710 }
1711}
1712
1713fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1714 match spec {
1715 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1716 AvatarSpec::Pair(first, second) => {
1717 faces.extend(first.user_id.clone());
1718 faces.extend(second.user_id.clone());
1719 }
1720 }
1721}
1722
1723fn with_spacer(list: Div, skipped_height: &mut f32) -> Div {
1724 let height = std::mem::take(skipped_height);
1725 if height > 0. {
1726 list.child(div().h(px(height)).flex_none())
1727 } else {
1728 list
1729 }
1730}
1731
1732impl Render for SidebarView {
1733 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1734 let window_height = f32::from(window.viewport_size().height);
1735 let body = match self.tab {
1736 SidebarTab::Activity => self.activity_panel.clone().into_any_element(),
1737 SidebarTab::Chats => self.chats_body(window_height, cx),
1738 SidebarTab::Channels => self.channels_body(cx),
1739 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1740 SidebarTab::Saved => self.saved_panel.clone().into_any_element(),
1741 };
1742 let header = match self.tab {
1743 SidebarTab::Chats => Some(
1744 page_header(self.tab.title())
1745 .child(self.chat_list_menu_button(cx))
1746 .child(self.new_chat_button(cx)),
1747 ),
1748 SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),
1749 SidebarTab::Activity | SidebarTab::Saved => None,
1750 };
1751 v_flex()
1752 .debug_selector(|| "shell/islands/sidebar".into())
1753 .w(px(SIDEBAR_WIDTH))
1754 .h_full()
1755 .flex_none()
1756 .bg(theme::surface())
1757 .rounded(px(10.))
1758 .overflow_hidden()
1759 .children(header)
1760 .child(body)
1761 }
1762}
1763
1764#[cfg(test)]
1765mod tests {
1766 use std::collections::HashSet;
1767
1768 use super::{
1769 drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,
1770 team_expanded,
1771 };
1772 use crate::data::PENDING_FOLDER_PREFIX;
1773 use crate::sidebar_model::{Section, SectionKind};
1774
1775 fn section(id: &str, kind: SectionKind) -> Section {
1776 Section {
1777 id: id.to_owned(),
1778 name: id.to_owned(),
1779 kind,
1780 collapsed: false,
1781 count: 0,
1782 unread_chats: 0,
1783 items: Vec::new(),
1784 hidden_count: 0,
1785 list_expanded: false,
1786 show_empty_hint: false,
1787 }
1788 }
1789
1790 #[test]
1791 fn pending_sections_take_no_dropped_chats() {
1792 let pending = format!("{PENDING_FOLDER_PREFIX}1");
1793 assert_eq!(drop_target(&section(&pending, SectionKind::Folder)), None);
1794 assert_eq!(
1795 drop_target(&section("work", SectionKind::Folder)),
1796 Some(Some("work".to_owned()))
1797 );
1798 assert_eq!(
1799 drop_target(&section("recent", SectionKind::Others)),
1800 Some(None)
1801 );
1802 }
1803
1804 #[test]
1805 fn teams_start_expanded() {
1806 assert!(team_expanded("t1", &HashSet::new()));
1807 }
1808
1809 #[test]
1810 fn collapsed_team_stays_closed() {
1811 let collapsed = HashSet::from(["t1".to_owned()]);
1812 assert!(!team_expanded("t1", &collapsed));
1813 assert!(team_expanded("t2", &collapsed));
1814 }
1815
1816 #[test]
1817 fn collapsed_teams_round_trip_as_json() {
1818 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1819 let json = serialize_collapsed_teams(&collapsed);
1820 assert_eq!(json, r#"["a","b"]"#);
1821 assert_eq!(parse_collapsed_teams(&json), collapsed);
1822 assert!(parse_collapsed_teams("garbage").is_empty());
1823 }
1824
1825 #[test]
1826 fn leave_text_counts_the_other_members() {
1827 assert_eq!(
1828 leave_description(4),
1829 "The 3 other members see that you left. You can only come back if someone adds you."
1830 );
1831 assert!(leave_description(2).starts_with("The other member sees"));
1832 assert!(leave_description(0).starts_with("The other members see"));
1833 }
1834}