BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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