BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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