BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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