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_color(theme::accent())
800 })
801 .on_drop(cx.listener(move |this, dragged: &DraggedChat, _, cx| {
802 let target = drop_target.clone();
803 this.state.update(cx, |state, cx| {
804 state.move_chat(&dragged.id, target.as_deref(), cx)
805 });
806 }))
807 })
808 .child(icon(
809 if section.collapsed {
810 IconName::ChevronRight
811 } else {
812 IconName::ChevronDown
813 },
814 12.,
815 theme::text_muted(),
816 ))
817 .child(
818 div()
819 .flex_1()
820 .min_w_0()
821 .truncate()
822 .text_size(px(12.))
823 .font_weight(FontWeight::SEMIBOLD)
824 .text_color(theme::text_soft())
825 .child(section.name.clone()),
826 )
827 .when(section.collapsed && section.unread_chats > 0, |header| {
828 header.child(count_badge(section.unread_chats, false))
829 })
830 .child(
831 div()
832 .text_size(px(11.))
833 .text_color(theme::text_faint())
834 .child(section.count.to_string()),
835 )
836 .on_click(cx.listener(move |this, _, _, cx| {
837 let id = toggle_id.clone();
838 this.state
839 .update(cx, |state, cx| state.toggle_collapsed(&id, cx));
840 }))
841 .context_menu(move |popup, _, _| section_menu(popup, &menu_state, &menu))
842 }
843
844 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
845 let toggle_id = section.id.clone();
846 let label = if section.hidden_count > 0 {
847 format!("See more ({})", section.hidden_count)
848 } else {
849 "See less".to_owned()
850 };
851 div()
852 .id(SharedString::from(format!("see-more-{}", section.id)))
853 .mx(px(6.))
854 .pl(px(10. + AVATAR_SIZE + 12.))
855 .h(px(SEE_MORE_HEIGHT))
856 .flex()
857 .items_center()
858 .rounded(px(6.))
859 .cursor_pointer()
860 .text_size(px(12.5))
861 .text_color(theme::accent_text())
862 .hover(|row| row.bg(theme::row_hover()))
863 .child(label)
864 .on_click(cx.listener(move |this, _, _, cx| {
865 let id = toggle_id.clone();
866 this.state
867 .update(cx, |state, cx| state.toggle_list_expanded(&id, cx));
868 }))
869 }
870
871 fn chat_row(
872 &self,
873 item: &ChatItem,
874 selected: bool,
875 local_preview: Option<&LocalPreview>,
876 proposal_agent: Option<&'static str>,
877 directory: &Directory,
878 menu: &MenuContext,
879 ) -> AnyElement {
880 let ring = if selected {
881 theme::surface_raised()
882 } else {
883 theme::surface()
884 };
885 let unread = item.unread.is_unread();
886 let presence = item
887 .presence_user
888 .as_deref()
889 .map(|user_id| directory.presence_of(user_id));
890 let avatar = spec_avatar(directory, &item.avatar, AVATAR_SIZE, ring);
891 let avatar = match presence {
892 Some(kind) => with_presence(avatar, kind, AVATAR_SIZE, ring).into_any_element(),
893 None => avatar,
894 };
895 let name = div()
896 .flex_1()
897 .min_w_0()
898 .truncate()
899 .text_size(px(14.))
900 .font_weight(if unread {
901 FontWeight::BOLD
902 } else {
903 FontWeight::NORMAL
904 })
905 .text_color(theme::text())
906 .child(item.title.clone());
907 let time = h_flex()
908 .flex_none()
909 .gap(px(4.))
910 .items_center()
911 .text_size(px(11.))
912 .text_color(if unread {
913 theme::accent_text()
914 } else {
915 theme::text_muted()
916 })
917 .when(item.muted, |time| {
918 time.child(icon(
919 IconName::BellOff,
920 MUTED_ICON_SIZE,
921 theme::text_faint(),
922 ))
923 })
924 .child(item.time_label.clone());
925 let preview_color = if matches!(item.preview, Preview::Typing(_)) {
926 theme::accent_text()
927 } else if item.muted {
928 theme::text_faint()
929 } else if unread {
930 theme::text_strong()
931 } else {
932 theme::text_muted()
933 };
934 let preview = match (proposal_agent, local_preview) {
935 (Some(agent), _) => Some(
936 h_flex()
937 .flex_1()
938 .min_w_0()
939 .overflow_hidden()
940 .text_size(px(12.5))
941 .text_color(theme::accent_text())
942 .child(div().truncate().child(format!("Proposal from {agent}"))),
943 ),
944 (None, Some(local)) => Some(local_preview_row(local, preview_color)),
945 (None, None) => preview_text(&item.preview).map(|(text, italic)| {
946 let glyph = preview_icon(&text);
947 h_flex()
948 .flex_1()
949 .min_w_0()
950 .overflow_hidden()
951 .gap(px(4.))
952 .items_center()
953 .text_size(px(12.5))
954 .when(italic, |preview| preview.italic())
955 .text_color(preview_color)
956 .children(glyph.map(|name| icon(name, 12., preview_color)))
957 .child(div().truncate().child(text))
958 }),
959 };
960 let lines = v_flex()
961 .flex_1()
962 .min_w_0()
963 .gap(px(2.))
964 .child(
965 h_flex()
966 .gap(px(8.))
967 .items_baseline()
968 .child(name)
969 .child(time),
970 )
971 .child(
972 h_flex()
973 .h(px(18.))
974 .gap(px(8.))
975 .items_center()
976 .child(preview.unwrap_or_else(|| div().flex_1()))
977 .children(match proposal_agent {
978 Some(_) => Some(
979 div()
980 .size(px(PROPOSAL_DOT_SIZE))
981 .flex_none()
982 .rounded_full()
983 .bg(theme::accent())
984 .into_any_element(),
985 ),
986 None => unread_marker(item.unread, item.muted)
987 .map(IntoElement::into_any_element),
988 }),
989 );
990 let state = self.state.clone();
991 let chat_id = item.id.clone();
992 let dragged = DraggedChat {
993 id: item.id.clone(),
994 title: item.title.clone(),
995 };
996 let pinned = menu.favorites_id.is_some() && item.folder_id == menu.favorites_id;
997 let menu_context = menu.clone();
998 let target = ChatMenuTarget {
999 id: item.id.clone(),
1000 title: item.title.clone(),
1001 pinned,
1002 unread,
1003 muted: item.muted,
1004 is_group: item.is_group,
1005 member_count: item.member_count,
1006 };
1007 h_flex()
1008 .id(SharedString::from(format!("chat-{}", item.id)))
1009 .mx(px(6.))
1010 .h(px(ROW_HEIGHT))
1011 .px(px(10.))
1012 .gap(px(12.))
1013 .items_center()
1014 .rounded(px(8.))
1015 .cursor_pointer()
1016 .when(selected, |row| row.bg(theme::surface_raised()))
1017 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1018 .on_drag(dragged, |dragged, _, _, cx| {
1019 let title = dragged.title.clone();
1020 cx.new(|_| DragGhost { title })
1021 })
1022 .child(avatar)
1023 .child(lines)
1024 .on_click(move |_, _, cx| {
1025 let selection = Selection::Chat(chat_id.clone());
1026 state.update(cx, |state, cx| state.select(selection, cx));
1027 })
1028 .context_menu(move |popup, window, cx| {
1029 chat_menu(popup, window, cx, &menu_context, &target)
1030 })
1031 .into_any_element()
1032 }
1033
1034 fn chats_body(&self, window_height: f32, cx: &mut Context<Self>) -> AnyElement {
1035 let proposal_agents = crate::agent_api::pending_agents(cx);
1036 let (sections, section_menus, menu, local_previews) = {
1037 let state = self.state.read(cx);
1038 let now = Utc::now();
1039 let offset = Local::now().offset().fix();
1040 let input = SectionInput {
1041 chats: &state.sidebar.chats,
1042 directory: &state.directory,
1043 collapsed: &state.collapsed,
1044 expanded_lists: &state.expanded_lists,
1045 typing: &state.typing,
1046 now,
1047 offset,
1048 };
1049 let sections = build_sections(&input);
1050 let menu = MenuContext {
1051 state: self.state.clone(),
1052 folders: state.directory.move_targets(),
1053 favorites_id: state.directory.favorites().map(|folder| folder.id.clone()),
1054 };
1055 let section_menus =
1056 section_menu_targets(&sections, &state.directory, state.mode.read_only);
1057 (sections, section_menus, menu, state.local_previews.clone())
1058 };
1059
1060 let top = -f32::from(self.chats_scroll.offset().y);
1061 let measured: f32 = f32::from(self.chats_scroll.bounds().size.height);
1062 let height = if measured > 1. {
1063 measured
1064 } else {
1065 window_height.max(FALLBACK_VIEWPORT)
1066 };
1067 let (visible_from, visible_to) = (top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
1068
1069 let (selected, drafting) = {
1070 let state = self.state.read(cx);
1071 (
1072 state.selection.clone().filter(|_| !state.new_chat),
1073 state.new_chat,
1074 )
1075 };
1076 let mut faces: Vec<String> = Vec::new();
1077 let mut presence_users: Vec<String> = Vec::new();
1078 let mut y = 0.;
1079 let mut list = v_flex().w_full().pb(px(12.));
1080 let mut skipped_height = 0.;
1081 let mut others_end = None;
1082 let directory_state = self.state.clone();
1083 if drafting {
1084 list = list.child(self.draft_row());
1085 y += ROW_HEIGHT;
1086 }
1087 for (section, section_menu) in sections.iter().zip(section_menus) {
1088 list = with_spacer(list, &mut skipped_height);
1089 list = list.child(self.section_header(section, section_menu, cx));
1090 y += SECTION_GAP + SECTION_HEIGHT;
1091 if section.collapsed {
1092 continue;
1093 }
1094 for item in &section.items {
1095 let on_screen = y + ROW_HEIGHT >= visible_from && y <= visible_to;
1096 if on_screen {
1097 collect_faces(&item.avatar, &mut faces);
1098 presence_users.extend(item.presence_user.clone());
1099 }
1100 if on_screen {
1101 list = with_spacer(list, &mut skipped_height);
1102 let is_selected = selected == Some(Selection::Chat(item.id.clone()));
1103 let directory = &directory_state.read(cx).directory;
1104 let local_preview = local_previews.get(&item.id).filter(|_| !is_selected);
1105 list = list.child(self.chat_row(
1106 item,
1107 is_selected,
1108 local_preview,
1109 proposal_agents.get(&item.id).copied(),
1110 directory,
1111 &menu,
1112 ));
1113 } else {
1114 skipped_height += ROW_HEIGHT;
1115 }
1116 y += ROW_HEIGHT;
1117 }
1118 if section.kind == SectionKind::Others {
1119 others_end = Some(y);
1120 }
1121 if section.hidden_count > 0 || section.list_expanded {
1122 list = with_spacer(list, &mut skipped_height);
1123 list = list.child(self.see_more_row(section, cx));
1124 y += SEE_MORE_HEIGHT;
1125 }
1126 if section.show_empty_hint {
1127 list = with_spacer(list, &mut skipped_height);
1128 list = list.child(
1129 div()
1130 .ml(px(16.))
1131 .mr(px(16.))
1132 .h(px(HINT_HEIGHT))
1133 .flex()
1134 .items_center()
1135 .text_size(px(12.))
1136 .italic()
1137 .text_color(theme::text_faint())
1138 .child(EMPTY_FOLDER_HINT),
1139 );
1140 y += HINT_HEIGHT;
1141 }
1142 }
1143 let (has_older, loading_older) = self.state.read(cx).older_chats();
1144 let previous = self.older_chats_seen.replace((has_older, loading_older));
1145 if older_chats_trigger_resets(previous, (has_older, loading_older)) {
1146 self.older_chats_trigger_top.set(None);
1147 }
1148 if has_older
1149 && wants_older_chats(
1150 others_end,
1151 top + height,
1152 top,
1153 self.older_chats_trigger_top.get(),
1154 loading_older,
1155 )
1156 {
1157 self.older_chats_trigger_top.set(Some(top));
1158 let state = self.state.clone();
1159 cx.defer(move |cx| state.read(cx).request_older_chats());
1160 }
1161 if loading_older {
1162 list = with_spacer(list, &mut skipped_height);
1163 list = list.child(
1164 div()
1165 .pl(px(16. + AVATAR_SIZE + 12.))
1166 .h(px(SEE_MORE_HEIGHT))
1167 .flex()
1168 .items_center()
1169 .text_size(px(12.5))
1170 .italic()
1171 .text_color(theme::text_faint())
1172 .child(LOADING_OLDER_LABEL),
1173 );
1174 }
1175 list = with_spacer(list, &mut skipped_height);
1176 self.request_lazy_data(faces, presence_users, cx);
1177 div()
1178 .id("chats-scroll")
1179 .flex_1()
1180 .min_h_0()
1181 .overflow_y_scroll()
1182 .track_scroll(&self.chats_scroll)
1183 .child(list)
1184 .into_any_element()
1185 }
1186
1187 fn request_lazy_data(
1188 &self,
1189 faces: Vec<String>,
1190 presence_users: Vec<String>,
1191 cx: &mut Context<Self>,
1192 ) {
1193 if faces.is_empty() && presence_users.is_empty() {
1194 return;
1195 }
1196 let state = self.state.clone();
1197 cx.defer(move |cx| {
1198 state.update(cx, |state, cx| {
1199 state.request_avatars(faces, cx);
1200 state.request_presence(presence_users, cx);
1201 });
1202 });
1203 }
1204
1205 fn channel_row(
1206 &self,
1207 channel_id: &str,
1208 team: &TeamRecord,
1209 channel: &ChannelRecord,
1210 selected: bool,
1211 notifications: ChannelNotifications,
1212 ) -> AnyElement {
1213 let unread = channel.unread;
1214 let state = self.state.clone();
1215 let menu_state = self.state.clone();
1216 let menu_channel_id = channel_id.to_owned();
1217 let selection = Selection::Channel(channel_id.to_owned());
1218 let now = Utc::now();
1219 let offset = Local::now().offset().fix();
1220 let time = channel
1221 .last_message_at
1222 .map(|time| {
1223 format::list_time_label(time, now.with_timezone(&offset).date_naive(), offset)
1224 })
1225 .unwrap_or_default();
1226 h_flex()
1227 .id(SharedString::from(format!("pinned-{channel_id}")))
1228 .mx(px(6.))
1229 .h(px(PINNED_CHANNEL_HEIGHT))
1230 .px(px(10.))
1231 .gap(px(12.))
1232 .items_center()
1233 .rounded(px(8.))
1234 .cursor_pointer()
1235 .when(selected, |row| row.bg(theme::surface_raised()))
1236 .when(!selected, |row| row.hover(|row| row.bg(theme::row_hover())))
1237 .child(square_avatar(&team.name, &team.id, 28., 7.))
1238 .child(
1239 v_flex()
1240 .flex_1()
1241 .min_w_0()
1242 .gap(px(1.))
1243 .child(
1244 h_flex()
1245 .gap(px(8.))
1246 .items_baseline()
1247 .child(
1248 div()
1249 .flex_1()
1250 .min_w_0()
1251 .truncate()
1252 .text_size(px(13.5))
1253 .font_weight(if unread {
1254 FontWeight::BOLD
1255 } else {
1256 FontWeight::NORMAL
1257 })
1258 .text_color(theme::text())
1259 .child(format!("{} / {}", team.name, channel.name)),
1260 )
1261 .children(notification_badge(notifications.level))
1262 .child(
1263 div()
1264 .flex_none()
1265 .text_size(px(11.))
1266 .text_color(if unread {
1267 theme::accent_text()
1268 } else {
1269 theme::text_muted()
1270 })
1271 .child(time),
1272 ),
1273 )
1274 .child(
1275 h_flex()
1276 .gap(px(8.))
1277 .items_center()
1278 .child(
1279 div()
1280 .flex_1()
1281 .min_w_0()
1282 .truncate()
1283 .text_size(px(12.))
1284 .text_color(theme::text_muted())
1285 .child(team.name.clone()),
1286 )
1287 .when(unread, |line| line.child(dot(7.))),
1288 ),
1289 )
1290 .on_click(move |_, _, cx| {
1291 let selection = selection.clone();
1292 state.update(cx, |state, cx| state.select(selection, cx));
1293 })
1294 .context_menu(move |popup, window, cx| {
1295 channel_menu(
1296 popup,
1297 window,
1298 cx,
1299 menu_state.clone(),
1300 &menu_channel_id,
1301 notifications,
1302 )
1303 })
1304 .into_any_element()
1305 }
1306
1307 fn plain_header(&self, label: &str) -> impl IntoElement {
1308 div()
1309 .h(px(SECTION_HEIGHT))
1310 .mt(px(SECTION_GAP))
1311 .px(px(16.))
1312 .flex()
1313 .items_center()
1314 .text_size(px(12.))
1315 .font_weight(FontWeight::SEMIBOLD)
1316 .text_color(theme::text_soft())
1317 .child(label.to_owned())
1318 }
1319
1320 fn team_block(
1321 &self,
1322 mut list: Div,
1323 entry: &SidebarTeam,
1324 selected: Option<&Selection>,
1325 cx: &mut Context<Self>,
1326 ) -> Div {
1327 let team_id = entry.team.id.clone();
1328 let expanded = team_expanded(&team_id, &self.collapsed_teams);
1329 let unread = entry.channels.iter().any(|channel| channel.unread);
1330 let toggle_id = team_id.clone();
1331 list = list.child(
1332 h_flex()
1333 .id(SharedString::from(format!("team-{team_id}")))
1334 .mx(px(6.))
1335 .h(px(TEAM_ROW_HEIGHT))
1336 .px(px(10.))
1337 .gap(px(8.))
1338 .items_center()
1339 .rounded(px(8.))
1340 .cursor_pointer()
1341 .hover(|row| row.bg(theme::row_hover()))
1342 .child(icon(
1343 if expanded {
1344 IconName::ChevronDown
1345 } else {
1346 IconName::ChevronRight
1347 },
1348 14.,
1349 theme::text_muted(),
1350 ))
1351 .child(square_avatar(&entry.team.name, &entry.team.id, 28., 7.))
1352 .child(
1353 div()
1354 .flex_1()
1355 .min_w_0()
1356 .truncate()
1357 .text_size(px(13.5))
1358 .font_weight(if unread || expanded {
1359 FontWeight::SEMIBOLD
1360 } else {
1361 FontWeight::NORMAL
1362 })
1363 .text_color(theme::text())
1364 .child(entry.team.name.clone()),
1365 )
1366 .when(unread && !expanded, |row| row.child(dot(7.)))
1367 .on_click(cx.listener(move |this, _, _, cx| {
1368 if !this.collapsed_teams.remove(&toggle_id) {
1369 this.collapsed_teams.insert(toggle_id.clone());
1370 }
1371 save_collapsed_teams(&this.state.read(cx).store, &this.collapsed_teams);
1372 cx.notify();
1373 })),
1374 );
1375 if !expanded {
1376 return list;
1377 }
1378 let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
1379 let is_selected =
1380 |channel: &ChannelRecord| selected == Some(&Selection::Channel(channel.id.clone()));
1381 for channel in entry
1382 .channels
1383 .iter()
1384 .filter(|channel| !is_hidden(channel) || is_selected(channel))
1385 {
1386 list = list.child(self.team_channel_row(
1387 channel,
1388 is_selected(channel),
1389 entry.channel_notifications(&channel.id),
1390 ));
1391 }
1392 let hidden: Vec<&ChannelRecord> = entry
1393 .channels
1394 .iter()
1395 .filter(|channel| is_hidden(channel) && !is_selected(channel))
1396 .collect();
1397 if hidden.is_empty() {
1398 return list;
1399 }
1400 let revealed = self.revealed_channel_teams.contains(&team_id);
1401 let toggle_id = team_id.clone();
1402 list = list.child(self.reveal_row(
1403 SharedString::from(format!("hidden-channels-{team_id}")),
1404 hidden_channels_label(hidden.len()),
1405 revealed,
1406 40.,
1407 cx.listener(move |this, _, _, cx| {
1408 if !this.revealed_channel_teams.remove(&toggle_id) {
1409 this.revealed_channel_teams.insert(toggle_id.clone());
1410 }
1411 cx.notify();
1412 }),
1413 ));
1414 if revealed {
1415 for channel in hidden {
1416 list = list.child(self.team_channel_row(
1417 channel,
1418 false,
1419 entry.channel_notifications(&channel.id),
1420 ));
1421 }
1422 }
1423 list
1424 }
1425
1426 fn reveal_row(
1427 &self,
1428 id: SharedString,
1429 label: String,
1430 open: bool,
1431 indent: f32,
1432 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
1433 ) -> impl IntoElement {
1434 h_flex()
1435 .id(id)
1436 .mx(px(6.))
1437 .h(px(REVEAL_ROW_HEIGHT))
1438 .pl(px(indent))
1439 .pr(px(10.))
1440 .gap(px(8.))
1441 .items_center()
1442 .rounded(px(8.))
1443 .cursor_pointer()
1444 .hover(|row| row.bg(theme::row_hover()))
1445 .child(icon(
1446 if open {
1447 IconName::ChevronDown
1448 } else {
1449 IconName::ChevronRight
1450 },
1451 12.,
1452 theme::text_faint(),
1453 ))
1454 .child(
1455 div()
1456 .text_size(px(12.5))
1457 .text_color(theme::text_muted())
1458 .child(label),
1459 )
1460 .on_click(on_click)
1461 }
1462
1463 fn team_channel_row(
1464 &self,
1465 channel: &ChannelRecord,
1466 is_selected: bool,
1467 notifications: ChannelNotifications,
1468 ) -> impl IntoElement {
1469 let state = self.state.clone();
1470 let menu_state = self.state.clone();
1471 let menu_channel_id = channel.id.clone();
1472 let selection = Selection::Channel(channel.id.clone());
1473 h_flex()
1474 .id(SharedString::from(format!("channel-{}", channel.id)))
1475 .mx(px(6.))
1476 .h(px(TEAM_ROW_HEIGHT))
1477 .pl(px(40.))
1478 .pr(px(10.))
1479 .gap(px(8.))
1480 .items_center()
1481 .rounded(px(8.))
1482 .cursor_pointer()
1483 .when(is_selected, |row| row.bg(theme::surface_raised()))
1484 .when(!is_selected, |row| {
1485 row.hover(|row| row.bg(theme::row_hover()))
1486 })
1487 .child(
1488 div()
1489 .w(px(14.))
1490 .flex()
1491 .justify_center()
1492 .text_size(px(15.))
1493 .text_color(theme::text_faint())
1494 .child("#"),
1495 )
1496 .child(
1497 div()
1498 .flex_1()
1499 .min_w_0()
1500 .truncate()
1501 .text_size(px(13.5))
1502 .font_weight(if channel.unread {
1503 FontWeight::BOLD
1504 } else {
1505 FontWeight::NORMAL
1506 })
1507 .text_color(theme::text())
1508 .child(channel.name.clone()),
1509 )
1510 .children(notification_badge(notifications.level))
1511 .when(channel.unread, |row| row.child(dot(7.)))
1512 .on_click(move |_, _, cx| {
1513 let selection = selection.clone();
1514 state.update(cx, |state, cx| state.select(selection, cx));
1515 })
1516 .context_menu(move |popup, window, cx| {
1517 channel_menu(
1518 popup,
1519 window,
1520 cx,
1521 menu_state.clone(),
1522 &menu_channel_id,
1523 notifications,
1524 )
1525 })
1526 }
1527
1528 fn channels_body(&self, cx: &mut Context<Self>) -> AnyElement {
1529 let (sidebar, pinned_ids, selected) = {
1530 let state = self.state.read(cx);
1531 (
1532 state.sidebar.clone(),
1533 state.directory.pinned_channels.clone(),
1534 state.selection.clone().filter(|_| !state.new_chat),
1535 )
1536 };
1537 let mut list = v_flex().w_full().pb(px(12.));
1538 let pinned: Vec<(&SidebarTeam, &ChannelRecord)> = pinned_ids
1539 .iter()
1540 .filter_map(|id| {
1541 sidebar.teams.iter().find_map(|entry| {
1542 entry
1543 .channels
1544 .iter()
1545 .find(|channel| &channel.id == id)
1546 .map(|channel| (entry, channel))
1547 })
1548 })
1549 .collect();
1550 if !pinned.is_empty() {
1551 list = list.child(self.plain_header(PINNED_LABEL));
1552 for (entry, channel) in pinned {
1553 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1554 list = list.child(self.channel_row(
1555 &channel.id,
1556 &entry.team,
1557 channel,
1558 is_selected,
1559 entry.channel_notifications(&channel.id),
1560 ));
1561 }
1562 }
1563 list = list.child(self.plain_header(TEAMS_LABEL));
1564 let (shown_teams, hidden_teams): (Vec<&SidebarTeam>, Vec<&SidebarTeam>) =
1565 sidebar.teams.iter().partition(|entry| !entry.hidden);
1566 for entry in shown_teams {
1567 list = self.team_block(list, entry, selected.as_ref(), cx);
1568 }
1569 if !hidden_teams.is_empty() {
1570 let holds_selection = hidden_teams
1571 .iter()
1572 .any(|entry| team_holds(entry, selected.as_ref()));
1573 let open = self.hidden_teams_open || holds_selection;
1574 list = list.child(self.reveal_row(
1575 "hidden-teams".into(),
1576 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1577 open,
1578 10.,
1579 cx.listener(|this, _, _, cx| {
1580 this.hidden_teams_open = !this.hidden_teams_open;
1581 cx.notify();
1582 }),
1583 ));
1584 if open {
1585 for entry in hidden_teams {
1586 list = self.team_block(list, entry, selected.as_ref(), cx);
1587 }
1588 }
1589 }
1590 div()
1591 .id("channels-scroll")
1592 .flex_1()
1593 .min_h_0()
1594 .overflow_y_scroll()
1595 .track_scroll(&self.channels_scroll)
1596 .child(list)
1597 .into_any_element()
1598 }
1599}
1600
1601fn notification_badge(level: ChannelNotificationLevel) -> Option<impl IntoElement> {
1602 let name = match level {
1603 ChannelNotificationLevel::BannerAndFeed => IconName::Bell,
1604 ChannelNotificationLevel::Off => IconName::BellOff,
1605 ChannelNotificationLevel::Feed => return None,
1606 };
1607 Some(icon(name, NOTIFICATION_ICON_SIZE, theme::text_muted()))
1608}
1609
1610fn channel_menu(
1611 popup: PopupMenu,
1612 window: &mut Window,
1613 cx: &mut Context<PopupMenu>,
1614 state: Entity<AppState>,
1615 channel_id: &str,
1616 notifications: ChannelNotifications,
1617) -> PopupMenu {
1618 let channel_id = channel_id.to_owned();
1619 popup.submenu_with_icon(
1620 Some(menu_icon(IconName::Bell)),
1621 "Notifications",
1622 window,
1623 cx,
1624 move |submenu, _, _| {
1625 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
1626 let (state, channel_id) = (state.clone(), channel_id.clone());
1627 PopupMenuItem::new(label)
1628 .checked(notifications.level == level)
1629 .on_click(move |_, _, cx| {
1630 let changed = ChannelNotifications {
1631 level,
1632 include_replies: notifications.include_replies
1633 && level != ChannelNotificationLevel::Off,
1634 };
1635 state.update(cx, |state, cx| {
1636 state.set_channel_notifications(&channel_id, changed, cx)
1637 });
1638 })
1639 };
1640 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
1641 submenu
1642 .item(level_item(
1643 "Banner and activity",
1644 ChannelNotificationLevel::BannerAndFeed,
1645 ))
1646 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
1647 .item(level_item("Off", ChannelNotificationLevel::Off))
1648 .separator()
1649 .item(
1650 PopupMenuItem::new("Include thread replies")
1651 .checked(notifications.include_replies)
1652 .disabled(notifications.level == ChannelNotificationLevel::Off)
1653 .on_click(move |_, _, cx| {
1654 let changed = ChannelNotifications {
1655 level: notifications.level,
1656 include_replies: !notifications.include_replies,
1657 };
1658 replies_state.update(cx, |state, cx| {
1659 state.set_channel_notifications(&replies_id, changed, cx)
1660 });
1661 }),
1662 )
1663 },
1664 )
1665}
1666
1667fn team_expanded(team_id: &str, collapsed_teams: &HashSet<String>) -> bool {
1668 !collapsed_teams.contains(team_id)
1669}
1670
1671fn load_collapsed_teams(store: &Store) -> HashSet<String> {
1672 store
1673 .meta(COLLAPSED_TEAMS_META_KEY)
1674 .ok()
1675 .flatten()
1676 .map(|value| parse_collapsed_teams(&value))
1677 .unwrap_or_default()
1678}
1679
1680fn save_collapsed_teams(store: &Store, collapsed_teams: &HashSet<String>) {
1681 let _ = store.set_meta(
1682 COLLAPSED_TEAMS_META_KEY,
1683 &serialize_collapsed_teams(collapsed_teams),
1684 );
1685}
1686
1687fn serialize_collapsed_teams(collapsed_teams: &HashSet<String>) -> String {
1688 let mut team_ids: Vec<&String> = collapsed_teams.iter().collect();
1689 team_ids.sort_unstable();
1690 serde_json::to_string(&team_ids).unwrap_or_default()
1691}
1692
1693fn parse_collapsed_teams(value: &str) -> HashSet<String> {
1694 serde_json::from_str(value).unwrap_or_default()
1695}
1696
1697fn team_holds(entry: &SidebarTeam, selected: Option<&Selection>) -> bool {
1698 entry
1699 .channels
1700 .iter()
1701 .any(|channel| selected == Some(&Selection::Channel(channel.id.clone())))
1702}
1703
1704fn hidden_channels_label(count: usize) -> String {
1705 if count == 1 {
1706 "1 hidden channel".to_owned()
1707 } else {
1708 format!("{count} hidden channels")
1709 }
1710}
1711
1712fn collect_faces(spec: &AvatarSpec, faces: &mut Vec<String>) {
1713 match spec {
1714 AvatarSpec::Single(face) => faces.extend(face.user_id.clone()),
1715 AvatarSpec::Pair(first, second) => {
1716 faces.extend(first.user_id.clone());
1717 faces.extend(second.user_id.clone());
1718 }
1719 }
1720}
1721
1722fn with_spacer(list: Div, skipped_height: &mut f32) -> Div {
1723 let height = std::mem::take(skipped_height);
1724 if height > 0. {
1725 list.child(div().h(px(height)).flex_none())
1726 } else {
1727 list
1728 }
1729}
1730
1731impl Render for SidebarView {
1732 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1733 let window_height = f32::from(window.viewport_size().height);
1734 let body = match self.tab {
1735 SidebarTab::Activity => self.activity_panel.clone().into_any_element(),
1736 SidebarTab::Chats => self.chats_body(window_height, cx),
1737 SidebarTab::Channels => self.channels_body(cx),
1738 SidebarTab::Calls => calls_body(&self.state, &self.calls_scroll, window_height, cx),
1739 SidebarTab::Saved => self.saved_panel.clone().into_any_element(),
1740 };
1741 let header = match self.tab {
1742 SidebarTab::Chats => Some(
1743 page_header(self.tab.title())
1744 .child(self.chat_list_menu_button(cx))
1745 .child(self.new_chat_button(cx)),
1746 ),
1747 SidebarTab::Channels | SidebarTab::Calls => Some(page_header(self.tab.title())),
1748 SidebarTab::Activity | SidebarTab::Saved => None,
1749 };
1750 v_flex()
1751 .debug_selector(|| "shell/islands/sidebar".into())
1752 .w(px(SIDEBAR_WIDTH))
1753 .h_full()
1754 .flex_none()
1755 .bg(theme::surface())
1756 .rounded(px(10.))
1757 .overflow_hidden()
1758 .children(header)
1759 .child(body)
1760 }
1761}
1762
1763#[cfg(test)]
1764mod tests {
1765 use std::collections::HashSet;
1766
1767 use super::{
1768 drop_target, leave_description, parse_collapsed_teams, serialize_collapsed_teams,
1769 team_expanded,
1770 };
1771 use crate::data::PENDING_FOLDER_PREFIX;
1772 use crate::sidebar_model::{Section, SectionKind};
1773
1774 fn section(id: &str, kind: SectionKind) -> Section {
1775 Section {
1776 id: id.to_owned(),
1777 name: id.to_owned(),
1778 kind,
1779 collapsed: false,
1780 count: 0,
1781 unread_chats: 0,
1782 items: Vec::new(),
1783 hidden_count: 0,
1784 list_expanded: false,
1785 show_empty_hint: false,
1786 }
1787 }
1788
1789 #[test]
1790 fn pending_sections_take_no_dropped_chats() {
1791 let pending = format!("{PENDING_FOLDER_PREFIX}1");
1792 assert_eq!(drop_target(&section(&pending, SectionKind::Folder)), None);
1793 assert_eq!(
1794 drop_target(&section("work", SectionKind::Folder)),
1795 Some(Some("work".to_owned()))
1796 );
1797 assert_eq!(
1798 drop_target(&section("recent", SectionKind::Others)),
1799 Some(None)
1800 );
1801 }
1802
1803 #[test]
1804 fn teams_start_expanded() {
1805 assert!(team_expanded("t1", &HashSet::new()));
1806 }
1807
1808 #[test]
1809 fn collapsed_team_stays_closed() {
1810 let collapsed = HashSet::from(["t1".to_owned()]);
1811 assert!(!team_expanded("t1", &collapsed));
1812 assert!(team_expanded("t2", &collapsed));
1813 }
1814
1815 #[test]
1816 fn collapsed_teams_round_trip_as_json() {
1817 let collapsed = HashSet::from(["b".to_owned(), "a".to_owned()]);
1818 let json = serialize_collapsed_teams(&collapsed);
1819 assert_eq!(json, r#"["a","b"]"#);
1820 assert_eq!(parse_collapsed_teams(&json), collapsed);
1821 assert!(parse_collapsed_teams("garbage").is_empty());
1822 }
1823
1824 #[test]
1825 fn leave_text_counts_the_other_members() {
1826 assert_eq!(
1827 leave_description(4),
1828 "The 3 other members see that you left. You can only come back if someone adds you."
1829 );
1830 assert!(leave_description(2).starts_with("The other member sees"));
1831 assert!(leave_description(0).starts_with("The other members see"));
1832 }
1833}