BlueGit

ict rusty-teams

Files

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

activity_panel.rs

activity_panel.rs 34.6 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::rc::Rc;
4
5use chrono::{DateTime, Local, NaiveDate, Offset};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10use store::Sidebar;
11
12use super::avatar::person_avatar;
13use super::scroll_edge::{scroll_offset, with_top_edge};
14use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
15use super::widgets::{Corner, corner_badge, dot, icon};
16use crate::activity::{ActivityCenter, Entry, Filter, Kind};
17use crate::agent_api::{
18 self,
19 pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
20};
21use crate::app_state::{AppState, chat_title};
22use crate::chat_filter::{FEWER_FILTERS, MORE_FILTERS};
23use crate::data::is_one_on_one;
24use crate::format;
25use crate::people::resolve_names;
26use crate::theme;
27
28const AVATAR_SIZE: f32 = 32.;
29const KIND_MARKER_SIZE: f32 = 16.;
30const BUTTON_SIZE: f32 = 32.;
31const MARK_READ_SIZE: f32 = 20.;
32const ROW_HEIGHT: f32 = 58.;
33const HEADER_HEIGHT: f32 = 30.;
34const EMPTY_HEIGHT: f32 = 84.;
35const FALLBACK_VIEWPORT: f32 = 900.;
36const VIEWPORT_MARGIN: f32 = 300.;
37const FILTER_KEY: &str = "activity_filter";
38const PROPOSALS_LABEL: &str = "Agent proposals";
39pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
40
41pub enum ActivityPanelEvent {
42 OpenSettings,
43 Open {
44 conversation_id: String,
45 message_id: String,
46 link: Option<String>,
47 },
48}
49
50pub struct ActivityPanel {
51 app: Entity<AppState>,
52 activity: Entity<ActivityCenter>,
53 filter: Filter,
54 more_filters_open: bool,
55 scroll: ScrollHandle,
56 resolved_names: HashMap<String, String>,
57 looked_up: HashSet<String>,
58 _observations: [Subscription; 2],
59}
60
61impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
62
63impl ActivityPanel {
64 pub fn activity(&self) -> Entity<ActivityCenter> {
65 self.activity.clone()
66 }
67
68 pub fn new(
69 app: Entity<AppState>,
70 activity: Entity<ActivityCenter>,
71 cx: &mut Context<Self>,
72 ) -> Self {
73 let observations = [
74 cx.observe(&app, |_, _, cx| cx.notify()),
75 cx.observe(&activity, |_, _, cx| cx.notify()),
76 ];
77 let filter = app
78 .read(cx)
79 .store
80 .meta(FILTER_KEY)
81 .ok()
82 .flatten()
83 .and_then(|key| Filter::from_key(&key))
84 .unwrap_or_default();
85 ActivityPanel {
86 app,
87 activity,
88 filter,
89 more_filters_open: false,
90 scroll: ScrollHandle::new(),
91 resolved_names: HashMap::new(),
92 looked_up: HashSet::new(),
93 _observations: observations,
94 }
95 }
96
97 fn open(&mut self, id: &str, cx: &mut Context<Self>) {
98 let Some(entry) = self.activity.read(cx).feed().get(id) else {
99 return;
100 };
101 let stored_reply = entry.reply_id.clone().filter(|reply_id| {
102 self.app
103 .read(cx)
104 .store
105 .messages_by_id(&entry.conversation_id, std::slice::from_ref(reply_id))
106 .is_ok_and(|found| !found.is_empty())
107 });
108 let event = ActivityPanelEvent::Open {
109 conversation_id: entry.conversation_id.clone(),
110 message_id: stored_reply.unwrap_or_else(|| entry.message_id.clone()),
111 link: entry.link.clone(),
112 };
113 self.activity
114 .update(cx, |activity, cx| activity.mark_read(id, cx));
115 cx.emit(event);
116 }
117
118 fn filter_pill(&self, filter: Filter, cx: &mut Context<Self>) -> impl IntoElement {
119 let selected = filter == self.filter;
120 div()
121 .id(ElementId::Name(
122 format!("activity-filter-{}", filter.label()).into(),
123 ))
124 .h(px(24.))
125 .px(px(12.))
126 .flex()
127 .flex_none()
128 .items_center()
129 .rounded_full()
130 .cursor_pointer()
131 .text_size(px(12.))
132 .when(selected, |pill| {
133 pill.bg(theme::accent()).text_color(theme::on_accent())
134 })
135 .when(!selected, |pill| {
136 pill.bg(theme::surface_raised())
137 .text_color(theme::text_soft())
138 .hover(|pill| pill.bg(theme::border_strong()))
139 })
140 .child(filter.label())
141 .on_click(cx.listener(move |this, _, _, cx| {
142 this.filter = filter;
143 let _ = this.app.read(cx).store.set_meta(FILTER_KEY, filter.key());
144 cx.notify();
145 }))
146 }
147
148 fn more_filters_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
149 let open = self.more_filters_open;
150 let label = if open { FEWER_FILTERS } else { MORE_FILTERS };
151 div()
152 .id("activity-filter-more")
153 .size(px(24.))
154 .flex()
155 .flex_none()
156 .items_center()
157 .justify_center()
158 .rounded_full()
159 .cursor_pointer()
160 .bg(theme::surface_raised())
161 .hover(|pill| pill.bg(theme::border_strong()))
162 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
163 .child(icon(
164 if open {
165 IconName::ChevronUp
166 } else {
167 IconName::ChevronDown
168 },
169 14.,
170 theme::text_soft(),
171 ))
172 .on_click(cx.listener(|this, _, _, cx| {
173 this.more_filters_open = !this.more_filters_open;
174 cx.notify();
175 }))
176 }
177
178 fn header(&self, cx: &mut Context<Self>) -> Div {
179 let overflow_active = Filter::OVERFLOW.contains(&self.filter);
180 let mut pills: Vec<AnyElement> = Filter::PRIMARY
181 .into_iter()
182 .map(|filter| self.filter_pill(filter, cx).into_any_element())
183 .collect();
184 if self.more_filters_open || overflow_active {
185 pills.extend(
186 Filter::OVERFLOW
187 .into_iter()
188 .map(|filter| self.filter_pill(filter, cx).into_any_element()),
189 );
190 }
191 if !overflow_active {
192 pills.push(self.more_filters_button(cx).into_any_element());
193 }
194 v_flex()
195 .flex_none()
196 .child(
197 h_flex()
198 .h(px(52.))
199 .pl(px(16.))
200 .pr(px(12.))
201 .gap(px(4.))
202 .items_center()
203 .child(
204 div()
205 .flex_1()
206 .text_size(px(16.))
207 .font_weight(FontWeight::BOLD)
208 .text_color(theme::text())
209 .child("Activity"),
210 )
211 .child(
212 div()
213 .id("activity-mark-all-read")
214 .px(px(8.))
215 .h(px(BUTTON_SIZE))
216 .flex()
217 .items_center()
218 .rounded(px(8.))
219 .cursor_pointer()
220 .text_size(px(12.))
221 .text_color(theme::accent_text())
222 .hover(|button| button.bg(theme::surface_raised()))
223 .child("Mark all as read")
224 .on_click(cx.listener(|this, _, _, cx| {
225 this.activity
226 .update(cx, |activity, cx| activity.mark_all_read(cx));
227 })),
228 )
229 .child(
230 div()
231 .id("activity-settings")
232 .size(px(BUTTON_SIZE))
233 .flex()
234 .flex_none()
235 .items_center()
236 .justify_center()
237 .rounded(px(8.))
238 .cursor_pointer()
239 .hover(|button| button.bg(theme::surface_raised()))
240 .child(icon(IconName::Settings, 16., theme::text_muted()))
241 .on_click(cx.listener(|_, _, _, cx| {
242 cx.emit(ActivityPanelEvent::OpenSettings);
243 })),
244 ),
245 )
246 .child(
247 h_flex()
248 .px(px(16.))
249 .pb(px(12.))
250 .flex_wrap()
251 .gap(px(6.))
252 .children(pills),
253 )
254 }
255
256 fn row(
257 &self,
258 entry: &Entry,
259 sidebar: &Sidebar,
260 directory: &crate::data::Directory,
261 today: NaiveDate,
262 offset: chrono::FixedOffset,
263 panel: Entity<ActivityPanel>,
264 ) -> AnyElement {
265 let activity = self.activity.clone();
266 let id = entry.id.clone();
267 let actor = entry.latest_actor();
268 let avatar = person_avatar(
269 directory,
270 actor.and_then(|actor| actor.user_id.as_deref()),
271 actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
272 AVATAR_SIZE,
273 );
274 let group = SharedString::from(format!("activity-row-group-{id}"));
275 row_frame(RowParts {
276 element_id: format!("activity-row-{id}"),
277 avatar: avatar.into_any_element(),
278 marker: kind_marker(entry, group.clone()),
279 group,
280 headline: headline(entry, sidebar, &self.resolved_names),
281 detail: detail(entry),
282 unread: !entry.read,
283 time: format::list_time_label(entry.updated_at, today, offset),
284 mark_read: Rc::new({
285 let id = id.clone();
286 move |cx: &mut App| activity.update(cx, |activity, cx| activity.mark_read(&id, cx))
287 }),
288 })
289 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(&id, cx)))
290 .into_any_element()
291 }
292
293 fn proposal_row(
294 &self,
295 pending: &PendingProposal,
296 sidebar: &Sidebar,
297 today: NaiveDate,
298 offset: chrono::FixedOffset,
299 panel: Entity<ActivityPanel>,
300 ) -> AnyElement {
301 let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
302 let label = proposal_conversation_label(sidebar, &pending.conversation_id);
303 let proposal_id = pending.id.clone();
304 let opened = pending.clone();
305 row_frame(RowParts {
306 element_id: format!("activity-proposal-{}", pending.id),
307 avatar: agent_avatar().into_any_element(),
308 marker: proposal_marker(pending, group.clone()),
309 group,
310 headline: pending.headline(label.as_deref()),
311 detail: pending.detail(),
312 unread: !pending.seen,
313 time: format::list_time_label(pending.created_at, today, offset),
314 mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
315 })
316 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
317 .into_any_element()
318 }
319
320 fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
321 agent_api::mark_proposal_seen(&pending.id, cx);
322 cx.emit(ActivityPanelEvent::Open {
323 conversation_id: pending.conversation_id.clone(),
324 message_id: pending.jump_message_id().to_owned(),
325 link: None,
326 });
327 }
328}
329
330struct RowParts {
331 element_id: String,
332 group: SharedString,
333 avatar: AnyElement,
334 marker: Div,
335 headline: String,
336 detail: String,
337 unread: bool,
338 time: String,
339 mark_read: MarkRead,
340}
341
342type MarkRead = Rc<dyn Fn(&mut App)>;
343
344fn row_frame(parts: RowParts) -> Stateful<Div> {
345 let RowParts {
346 element_id,
347 group,
348 avatar,
349 marker,
350 headline,
351 detail,
352 unread,
353 time,
354 mark_read,
355 } = parts;
356 let selector = element_id.clone();
357 h_flex()
358 .id(ElementId::Name(element_id.clone().into()))
359 .debug_selector(move || selector)
360 .group(group.clone())
361 .h(px(ROW_HEIGHT))
362 .flex_none()
363 .mx(px(6.))
364 .px(px(10.))
365 .py(px(8.))
366 .gap(px(12.))
367 .items_start()
368 .rounded(px(8.))
369 .cursor_pointer()
370 .hover(|row| row.bg(theme::row_hover()))
371 .child(
372 div()
373 .relative()
374 .flex_none()
375 .size(px(AVATAR_SIZE))
376 .child(avatar)
377 .child(marker),
378 )
379 .child(
380 v_flex()
381 .flex_1()
382 .min_w_0()
383 .gap(px(2.))
384 .child(
385 div()
386 .truncate()
387 .text_size(px(13.))
388 .font_weight(if unread {
389 FontWeight::SEMIBOLD
390 } else {
391 FontWeight::NORMAL
392 })
393 .text_color(if unread {
394 theme::text()
395 } else {
396 theme::text_soft()
397 })
398 .child(headline),
399 )
400 .child(
401 div()
402 .truncate()
403 .text_size(px(12.))
404 .text_color(if unread {
405 theme::text_soft()
406 } else {
407 theme::text_muted()
408 })
409 .child(detail),
410 ),
411 )
412 .child(
413 v_flex()
414 .flex_none()
415 .items_end()
416 .child(
417 div()
418 .text_size(px(11.))
419 .text_color(theme::text_muted())
420 .child(time),
421 )
422 .child(status_slot(element_id, unread, group, mark_read)),
423 )
424}
425
426fn agent_avatar() -> Div {
427 div()
428 .size(px(AVATAR_SIZE))
429 .flex()
430 .items_center()
431 .justify_center()
432 .rounded_full()
433 .bg(theme::accent_soft())
434 .child(icon(IconName::Bot, 16., theme::accent_text()))
435}
436
437fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
438 match filter {
439 Filter::All => true,
440 Filter::Mentions => false,
441 Filter::Unread => !pending.seen,
442 Filter::Replies | Filter::Reactions | Filter::MissedCalls => false,
443 }
444}
445
446fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
447 let slot = div()
448 .h(px(MARK_READ_SIZE))
449 .flex()
450 .flex_none()
451 .items_center()
452 .justify_end();
453 if !unread {
454 return slot;
455 }
456 // Toggle visibility, never display: gpui reads hover in prepaint and paint from different frames.
457 slot.relative()
458 .w(px(MARK_READ_SIZE))
459 .child(
460 div()
461 .flex()
462 .group_hover(group.clone(), |wrapper| wrapper.invisible())
463 .mr(px(8.))
464 .child(dot(8.)),
465 )
466 .child(
467 div()
468 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
469 .absolute()
470 .top_0()
471 .right_0()
472 .invisible()
473 .group_hover(group, |button| button.visible())
474 .size(px(MARK_READ_SIZE))
475 .flex()
476 .items_center()
477 .justify_center()
478 .rounded(px(6.))
479 .bg(theme::surface_raised())
480 .cursor_pointer()
481 .child(icon(IconName::Check, 12., theme::text()))
482 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
483 .on_click(move |_, _, cx| {
484 cx.stop_propagation();
485 mark_read(cx);
486 }),
487 )
488}
489
490fn marker_frame(row_group: SharedString) -> Div {
491 corner_badge(Corner::BottomRight, 4.)
492 .size(px(KIND_MARKER_SIZE))
493 .flex()
494 .items_center()
495 .justify_center()
496 .rounded_full()
497 .border_2()
498 .border_color(theme::surface())
499 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
500 .bg(theme::surface_raised())
501 .text_size(px(10.))
502}
503
504fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
505 let marker = marker_frame(row_group);
506 match &pending.kind {
507 PendingKind::Reply { .. } => {
508 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
509 }
510 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
511 }
512}
513
514fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
515 let marker = marker_frame(row_group);
516 let muted_icon = |name: IconName| icon(name, 10., theme::text_muted());
517 match entry.kind {
518 Kind::Mention => marker
519 .text_color(theme::accent_text())
520 .font_weight(FontWeight::BOLD)
521 .child("@"),
522 Kind::Reaction => match entry.glyphs.first() {
523 Some(glyph) => marker.child(glyph.clone()),
524 None => marker.child(muted_icon(IconName::Heart)),
525 },
526 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
527 Kind::Reply => marker.child(muted_icon(IconName::Reply)),
528 Kind::Call => marker.child(muted_icon(IconName::Phone)),
529 Kind::Posted => marker.child(muted_icon(IconName::MessageSquare)),
530 Kind::Team => marker.child(muted_icon(IconName::Users)),
531 Kind::App => marker.child(muted_icon(IconName::AppWindow)),
532 Kind::Other => marker.child(muted_icon(IconName::Bell)),
533 }
534}
535
536fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
537 let actor = entry
538 .latest_actor()
539 .map(|actor| actor.display_name(resolved_names).to_owned())
540 .unwrap_or_default();
541 let names = if entry.count > 1 && matches!(entry.kind, Kind::Reaction | Kind::Reply) {
542 format!("{actor} +{}", entry.count - 1)
543 } else {
544 actor.clone()
545 };
546 let channel = channel_of(sidebar, &entry.conversation_id);
547 let verb = match (entry.kind, entry.subtype.as_str()) {
548 (Kind::Mention, "everyone") => format!("{names} mentioned Everyone"),
549 (Kind::Mention, "channel") => match channel {
550 Some((_, channel_name)) => format!("{names} mentioned {channel_name}"),
551 None => format!("{names} mentioned the channel"),
552 },
553 (Kind::Mention, "team") => match channel {
554 Some((team_name, _)) => format!("{names} mentioned {team_name}"),
555 None => format!("{names} mentioned the team"),
556 },
557 (Kind::Mention, _) => format!("{names} mentioned you"),
558 (Kind::Reply, _) => reply_headline(entry, &names),
559 (Kind::Reaction, _) => format!("{names} reacted to your message"),
560 (Kind::MissedCall, _) => format!("Missed call from {actor}"),
561 (Kind::Call, "voicemail") => format!("Voicemail from {actor}"),
562 (Kind::Call, "missedMeetingNudge") => format!("{actor} asked you to join a meeting"),
563 (Kind::Call, _) => actor,
564 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
565 (Kind::Posted, _) => format!("{names} posted a new message"),
566 (Kind::Team, "promotedToTeamAdmin") => {
567 return format!("{actor} made you an owner of {}", team_label(entry, channel));
568 }
569 (Kind::Team, _) => {
570 return format!("{actor} added you to {}", team_label(entry, channel));
571 }
572 (Kind::App, _) => entry.source_label.clone().unwrap_or(actor),
573 (Kind::Other, _) => actor,
574 };
575 match conversation_label(sidebar, &entry.conversation_id) {
576 Some(label) => format!("{verb} in {label}"),
577 None => verb,
578 }
579}
580
581fn reply_headline(entry: &Entry, names: &str) -> String {
582 match entry.activity_type.as_str() {
583 "reply" => format!("{names} replied to your post"),
584 "replyInChat" => format!("{names} replied to message"),
585 _ => format!("{names} replied"),
586 }
587}
588
589fn team_label(entry: &Entry, channel: Option<(&str, &str)>) -> String {
590 channel
591 .map(|(team_name, _)| team_name.to_owned())
592 .or_else(|| entry.source_label.clone())
593 .unwrap_or_else(|| "a team".to_owned())
594}
595
596fn channel_of<'a>(sidebar: &'a Sidebar, conversation_id: &str) -> Option<(&'a str, &'a str)> {
597 sidebar.teams.iter().find_map(|team| {
598 team.channels
599 .iter()
600 .find(|channel| channel.id == conversation_id)
601 .map(|channel| (team.team.name.as_str(), channel.name.as_str()))
602 })
603}
604
605fn detail(entry: &Entry) -> String {
606 match entry.kind {
607 Kind::Reaction if !entry.glyphs.is_empty() => {
608 format!("{} to: {}", entry.glyphs.join(" "), entry.preview)
609 }
610 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
611 _ => entry.preview.clone(),
612 }
613}
614
615fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
616 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
617 return (!is_one_on_one(chat)).then(|| chat_title(chat));
618 }
619 sidebar.teams.iter().find_map(|team| {
620 team.channels
621 .iter()
622 .find(|channel| channel.id == conversation_id)
623 .map(|channel| format!("{} > {}", team.team.name, channel.name))
624 })
625}
626
627fn group_header(label: &'static str) -> Div {
628 div()
629 .h(px(HEADER_HEIGHT - 4.))
630 .mt(px(4.))
631 .px(px(16.))
632 .flex()
633 .flex_none()
634 .items_center()
635 .text_size(px(11.))
636 .font_weight(FontWeight::SEMIBOLD)
637 .text_color(theme::text_muted())
638 .child(label)
639}
640
641enum Slot<'a> {
642 Proposals(Vec<PendingProposal>),
643 Header(&'static str),
644 Row(&'a Entry),
645 Empty,
646}
647
648impl Slot<'_> {
649 fn height(&self) -> f32 {
650 match self {
651 Slot::Proposals(proposals) => HEADER_HEIGHT + proposals.len() as f32 * ROW_HEIGHT,
652 Slot::Header(_) => HEADER_HEIGHT,
653 Slot::Row(_) => ROW_HEIGHT,
654 Slot::Empty => EMPTY_HEIGHT,
655 }
656 }
657}
658
659#[derive(Debug, PartialEq)]
660struct VisibleSlots {
661 range: Range<usize>,
662 before: f32,
663 after: f32,
664}
665
666fn visible_slots(heights: &[f32], from: f32, to: f32) -> VisibleSlots {
667 let mut position = 0.;
668 let mut first = heights.len();
669 let mut last = heights.len();
670 let mut before = 0.;
671 for (index, height) in heights.iter().enumerate() {
672 let end = position + height;
673 if first == heights.len() && end >= from {
674 first = index;
675 before = position;
676 }
677 if position > to {
678 last = index;
679 break;
680 }
681 position = end;
682 }
683 if first == heights.len() {
684 before = position;
685 }
686 let last = last.max(first);
687 let after = heights[last..].iter().sum();
688 VisibleSlots {
689 range: first..last,
690 before,
691 after,
692 }
693}
694
695impl Render for ActivityPanel {
696 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
697 let now: DateTime<Local> = Local::now();
698 let (today, offset) = (now.date_naive(), now.offset().fix());
699 let panel = cx.entity();
700 let app = self.app.clone();
701 let activity = self.activity.clone();
702 let state = app.read(cx);
703 let sections = activity
704 .read(cx)
705 .feed()
706 .sections(self.filter, today, offset);
707 let mut slots: Vec<Slot> = Vec::new();
708 let proposals: Vec<PendingProposal> = agent_api::pending_proposals(cx)
709 .into_iter()
710 .filter(|pending| admits_proposal(self.filter, pending))
711 .collect();
712 if !proposals.is_empty() {
713 slots.push(Slot::Proposals(proposals));
714 }
715 for section in &sections {
716 slots.push(Slot::Header(section.bucket.label()));
717 slots.extend(section.entries.iter().map(|entry| Slot::Row(entry)));
718 }
719 if slots.is_empty() {
720 slots.push(Slot::Empty);
721 }
722 let heights: Vec<f32> = slots.iter().map(Slot::height).collect();
723 let top = -f32::from(scroll_offset(&self.scroll).y);
724 let measured = f32::from(self.scroll.bounds().size.height);
725 let height = if measured > 1. {
726 measured
727 } else {
728 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
729 };
730 let visible = visible_slots(&heights, top - VIEWPORT_MARGIN, top + height + VIEWPORT_MARGIN);
731 let visible_slots = &slots[visible.range.clone()];
732 let unresolved: Vec<String> = visible_slots
733 .iter()
734 .filter_map(|slot| match slot {
735 Slot::Row(entry) => Some(entry.unresolved_user_ids()),
736 _ => None,
737 })
738 .flatten()
739 .filter(|user_id| !self.looked_up.contains(*user_id))
740 .cloned()
741 .collect();
742 if !unresolved.is_empty() {
743 self.looked_up.extend(unresolved.iter().cloned());
744 self.resolved_names
745 .extend(resolve_names(state, &unresolved));
746 }
747 let mut rows: Vec<AnyElement> = Vec::new();
748 if visible.before > 0. {
749 rows.push(div().h(px(visible.before)).flex_none().into_any_element());
750 }
751 for slot in visible_slots {
752 rows.push(match slot {
753 Slot::Proposals(proposals) => v_flex()
754 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
755 .child(group_header(PROPOSALS_LABEL))
756 .children(proposals.iter().map(|pending| {
757 self.proposal_row(pending, &state.sidebar, today, offset, panel.clone())
758 }))
759 .into_any_element(),
760 Slot::Header(label) => group_header(label).into_any_element(),
761 Slot::Row(entry) => self.row(
762 entry,
763 &state.sidebar,
764 &state.directory,
765 today,
766 offset,
767 panel.clone(),
768 ),
769 Slot::Empty => div()
770 .h(px(EMPTY_HEIGHT))
771 .flex()
772 .flex_none()
773 .items_center()
774 .justify_center()
775 .text_size(px(13.))
776 .text_color(theme::text_muted())
777 .child(self.filter.empty_label())
778 .into_any_element(),
779 });
780 }
781 if visible.after > 0. {
782 rows.push(div().h(px(visible.after)).flex_none().into_any_element());
783 }
784 let list = v_flex()
785 .id("activity-list")
786 .flex_1()
787 .min_h_0()
788 .pb(px(12.))
789 .overflow_y_scroll()
790 .track_scroll(&self.scroll)
791 .children(rows);
792 v_flex()
793 .flex_1()
794 .min_h_0()
795 .child(self.header(cx))
796 .child(with_top_edge(list, &self.scroll, SIDEBAR_SCROLL_DIVIDER))
797 }
798}
799
800#[cfg(test)]
801mod tests {
802 use std::collections::HashMap;
803 use std::sync::Arc;
804
805 use chrono::{Local, Offset, TimeZone, Utc};
806 use gpui_kit::{AppContext as _, Modifiers, TestAppContext};
807 use store::{ChatRecord, Sidebar, Store};
808
809 use super::{
810 ActivityPanel, ROW_HEIGHT, VIEWPORT_MARGIN, VisibleSlots, detail, headline, visible_slots,
811 };
812 use crate::activity::{ActivityCenter, Actor, Entry, Filter, Kind};
813 use crate::app_state::{AppState, Mode};
814
815 fn entry(kind: Kind, count: u32) -> Entry {
816 Entry {
817 id: "1".into(),
818 conversation_id: "chat".into(),
819 kind,
820 message_id: "m1".into(),
821 actors: vec![Actor {
822 user_id: Some("u1".into()),
823 name: "Anna".into(),
824 }],
825 preview: "hello".into(),
826 glyphs: vec!["A".into(), "B".into()],
827 count,
828 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
829 ..Entry::default()
830 }
831 }
832
833 fn with(kind: Kind, activity_type: &str, subtype: &str, count: u32) -> Entry {
834 Entry {
835 activity_type: activity_type.into(),
836 subtype: subtype.into(),
837 ..entry(kind, count)
838 }
839 }
840
841 #[test]
842 fn only_rows_near_the_viewport_are_built() {
843 let heights = vec![ROW_HEIGHT; 300];
844 let viewport = 900.;
845 let at_top = visible_slots(&heights, -VIEWPORT_MARGIN, viewport + VIEWPORT_MARGIN);
846 assert_eq!(
847 at_top,
848 VisibleSlots {
849 range: 0..21,
850 before: 0.,
851 after: 279. * ROW_HEIGHT,
852 }
853 );
854 let scrolled = visible_slots(
855 &heights,
856 5000. - VIEWPORT_MARGIN,
857 5000. + viewport + VIEWPORT_MARGIN,
858 );
859 assert_eq!(scrolled.range, 81..107);
860 assert_eq!(scrolled.before, 81. * ROW_HEIGHT);
861 assert_eq!(scrolled.after, 193. * ROW_HEIGHT);
862 let past_the_end = visible_slots(&heights, 90_000., 91_000.);
863 assert_eq!(past_the_end.range, 300..300);
864 assert_eq!(past_the_end.before, 300. * ROW_HEIGHT);
865 assert_eq!(past_the_end.after, 0.);
866 }
867
868 #[test]
869 fn detail_follows_the_kind() {
870 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
871 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
872 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
873 assert_eq!(detail(&entry(Kind::Reply, 2)), "hello");
874 }
875
876 #[test]
877 fn headline_uses_the_teams_activity_texts() {
878 let sidebar = Sidebar {
879 chats: vec![ChatRecord {
880 id: "chat".into(),
881 kind: "oneOnOne".into(),
882 ..Default::default()
883 }],
884 teams: Vec::new(),
885 };
886 let cases = [
887 (with(Kind::Mention, "mentionInChat", "person", 1), "Anna mentioned you"),
888 (with(Kind::Mention, "mentionInChat", "everyone", 1), "Anna mentioned Everyone"),
889 (with(Kind::Reaction, "reactionInChat", "like", 1), "Anna reacted to your message"),
890 (with(Kind::Reaction, "reactionInChat", "like", 3), "Anna +2 reacted to your message"),
891 (with(Kind::Reply, "reply", "", 1), "Anna replied to your post"),
892 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
893 (with(Kind::MissedCall, "call", "missedCall", 1), "Missed call from Anna"),
894 (with(Kind::Call, "call", "missedMeetingNudge", 1), "Anna asked you to join a meeting"),
895 (with(Kind::Posted, "follow", "channelNewMessage", 1), "Anna posted a new message"),
896 ];
897 for (entry, expected) in cases {
898 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
899 }
900 }
901
902 #[test]
903 fn headline_names_channel_and_team_mentions() {
904 let sidebar = Sidebar {
905 chats: Vec::new(),
906 teams: vec![store::SidebarTeam {
907 team: store::TeamRecord {
908 id: "team".into(),
909 name: "Platform".into(),
910 },
911 channels: vec![store::ChannelRecord {
912 id: "chat".into(),
913 team_id: "team".into(),
914 name: "Releases".into(),
915 membership_type: None,
916 last_message_at: None,
917 unread: false,
918 }],
919 hidden: false,
920 hidden_channel_ids: Vec::new(),
921 notifications: Default::default(),
922 mentions: Default::default(),
923 }],
924 };
925 assert_eq!(
926 headline(&with(Kind::Mention, "mention", "channel", 1), &sidebar, &HashMap::new()),
927 "Anna mentioned Releases in Platform > Releases"
928 );
929 assert_eq!(
930 headline(&with(Kind::Mention, "mention", "team", 1), &sidebar, &HashMap::new()),
931 "Anna mentioned Platform in Platform > Releases"
932 );
933 assert_eq!(
934 headline(
935 &with(Kind::Team, "teamMembershipChange", "addedToTeam", 1),
936 &sidebar,
937 &HashMap::new()
938 ),
939 "Anna added you to Platform"
940 );
941 }
942
943 #[test]
944 fn headline_resolves_an_unknown_actor() {
945 let mut stale = with(Kind::Reaction, "reactionInChat", "like", 1);
946 stale.actors[0].name = "Unknown".into();
947 let sidebar = Sidebar::default();
948 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
949 assert_eq!(
950 headline(&stale, &sidebar, &resolved),
951 "Anna reacted to your message"
952 );
953 }
954
955 #[gpui_kit::test]
956 fn row_sliding_under_a_resting_mouse_draws(cx: &mut TestAppContext) {
957 cx.update(gpui_kit::init);
958 let store = Arc::new(Store::open_in_memory().unwrap());
959 crate::demo::seed(&store);
960 let mode = Mode {
961 demo: true,
962 read_only: false,
963 demo_sync: None,
964 };
965 let app = cx.update(|cx| {
966 cx.new(|_| {
967 let mut state = AppState::new(store, mode);
968 crate::demo::seed_directory(&mut state);
969 state
970 })
971 });
972 let (panel, cx) = cx.add_window_view(|window, cx| {
973 let activity = cx.new(|cx| ActivityCenter::new(app.clone(), window, cx));
974 let mut panel = ActivityPanel::new(app.clone(), activity, cx);
975 panel.filter = Filter::Unread;
976 panel
977 });
978 cx.update(|window, cx| window.draw(cx).clear(cx));
979 let activity = cx.update(|_, cx| panel.read(cx).activity.clone());
980 let first_unread = cx.update(|_, cx| {
981 let now = Local::now();
982 activity
983 .read(cx)
984 .feed()
985 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
986 .entries[0]
987 .id
988 .clone()
989 });
990 let selector: &'static str = format!("activity-row-{first_unread}").leak();
991 let first_row = cx.debug_bounds(selector).unwrap();
992 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
993 cx.update(|window, cx| window.draw(cx).clear(cx));
994 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx)));
995 cx.update(|window, cx| window.draw(cx).clear(cx));
996 }
997}