BlueGit

ict rusty-teams

Files

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

activity_panel.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
activity_panel.rs 40.3 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::ops::Range;
3use std::rc::Rc;
4
5use app_ui_kit::layout::SIDEBAR_WIDTH;
6use chrono::{DateTime, Local, NaiveDate, Offset, TimeZone, Utc};
7use gpui_kit::assets::IconName;
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use store::Sidebar;
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| {
408 headline.line_clamp(2).text_ellipsis()
409 })
410 .when(!headline_wraps, |headline| headline.truncate())
411 .text_size(px(13.))
412 .line_height(px(HEADLINE_LINE_HEIGHT))
413 .font_weight(if unread {
414 FontWeight::SEMIBOLD
415 } else {
416 FontWeight::NORMAL
417 })
418 .text_color(if unread {
419 theme::text()
420 } else {
421 theme::text_soft()
422 })
423 .child(headline),
424 )
425 .child(
426 div()
427 .truncate()
428 .text_size(px(12.))
429 .text_color(if unread {
430 theme::text_soft()
431 } else {
432 theme::text_muted()
433 })
434 .child(detail),
435 )
436 .children(lines.into_iter().map(|line| {
437 div()
438 .truncate()
439 .text_size(px(12.))
440 .text_color(theme::text_muted())
441 .child(line)
442 })),
443 )
444 .child(
445 v_flex()
446 .flex_none()
447 .items_end()
448 .child(
449 div()
450 .text_size(px(11.))
451 .text_color(theme::text_muted())
452 .child(time),
453 )
454 .child(status_slot(element_id, unread, group, mark_read)),
455 )
456}
457
458fn agent_avatar() -> Div {
459 div()
460 .size(px(AVATAR_SIZE))
461 .flex()
462 .items_center()
463 .justify_center()
464 .rounded_full()
465 .bg(theme::accent_soft())
466 .child(icon(IconName::Bot, 16., theme::accent_text()))
467}
468
469fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
470 match filter {
471 Filter::All => true,
472 Filter::Mentions => false,
473 Filter::Unread => !pending.seen,
474 Filter::Replies | Filter::Reactions | Filter::MissedCalls => false,
475 }
476}
477
478fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
479 let slot = div()
480 .h(px(MARK_READ_SIZE))
481 .flex()
482 .flex_none()
483 .items_center()
484 .justify_end();
485 if !unread {
486 return slot;
487 }
488 // Toggle visibility, never display: gpui reads hover in prepaint and paint from different frames.
489 slot.relative()
490 .w(px(MARK_READ_SIZE))
491 .child(
492 div()
493 .flex()
494 .group_hover(group.clone(), |wrapper| wrapper.invisible())
495 .mr(px(8.))
496 .child(dot(8.)),
497 )
498 .child(
499 div()
500 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
501 .absolute()
502 .top_0()
503 .right_0()
504 .invisible()
505 .group_hover(group, |button| button.visible())
506 .size(px(MARK_READ_SIZE))
507 .flex()
508 .items_center()
509 .justify_center()
510 .rounded(px(6.))
511 .bg(theme::surface_raised())
512 .cursor_pointer()
513 .child(icon(IconName::Check, 12., theme::text()))
514 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
515 .on_click(move |_, _, cx| {
516 cx.stop_propagation();
517 mark_read(cx);
518 }),
519 )
520}
521
522fn marker_frame(row_group: SharedString) -> Div {
523 corner_badge(Corner::BottomRight, 4.)
524 .size(px(KIND_MARKER_SIZE))
525 .flex()
526 .items_center()
527 .justify_center()
528 .rounded_full()
529 .border_2()
530 .border_color(theme::surface())
531 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
532 .bg(theme::surface_raised())
533 .text_size(px(10.))
534}
535
536fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
537 let marker = marker_frame(row_group);
538 match &pending.kind {
539 PendingKind::Reply { .. } => {
540 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
541 }
542 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
543 }
544}
545
546fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
547 let marker = marker_frame(row_group);
548 let muted_icon = |name: IconName| icon(name, 10., theme::text_muted());
549 match entry.kind {
550 Kind::Mention => marker
551 .text_color(theme::accent_text())
552 .font_weight(FontWeight::BOLD)
553 .child("@"),
554 Kind::Reaction => match entry.glyphs.first() {
555 Some(glyph) => marker.child(glyph.clone()),
556 None => marker.child(muted_icon(IconName::Heart)),
557 },
558 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
559 Kind::Reply => marker.child(muted_icon(IconName::Reply)),
560 Kind::Call => marker.child(muted_icon(IconName::Phone)),
561 Kind::Posted => marker.child(muted_icon(IconName::MessageSquare)),
562 Kind::Team => marker.child(muted_icon(IconName::Users)),
563 Kind::App => marker.child(muted_icon(IconName::AppWindow)),
564 Kind::Other => marker.child(muted_icon(IconName::Bell)),
565 }
566}
567
568fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
569 let actor = entry
570 .latest_actor()
571 .map(|actor| actor.display_name(resolved_names).to_owned())
572 .unwrap_or_default();
573 let names = if entry.count > 1 && matches!(entry.kind, Kind::Reaction | Kind::Reply) {
574 format!("{actor} +{}", entry.count - 1)
575 } else {
576 actor.clone()
577 };
578 let channel = channel_of(sidebar, &entry.conversation_id);
579 let verb = match (entry.kind, entry.subtype.as_str()) {
580 (Kind::Mention, "everyone") => format!("{names} mentioned Everyone"),
581 (Kind::Mention, "channel") => match channel {
582 Some((_, channel_name)) => format!("{names} mentioned {channel_name}"),
583 None => format!("{names} mentioned the channel"),
584 },
585 (Kind::Mention, "team") => match channel {
586 Some((team_name, _)) => format!("{names} mentioned {team_name}"),
587 None => format!("{names} mentioned the team"),
588 },
589 (Kind::Mention, _) => format!("{names} mentioned you"),
590 (Kind::Reply, _) => reply_headline(entry, &names),
591 (Kind::Reaction, _) => format!("{names} reacted to your message"),
592 (Kind::MissedCall, _) => format!("Missed call from {actor}"),
593 (Kind::Call, "voicemail") => format!("Voicemail from {actor}"),
594 (Kind::Call, "missedMeetingNudge") => format!("{actor} asked you to join a meeting"),
595 (Kind::Call, _) => actor,
596 (Kind::Posted, "channelReplyMessage") => format!("{names} replied"),
597 (Kind::Posted, _) => format!("{names} posted a new message"),
598 (Kind::Team, "promotedToTeamAdmin") => {
599 return format!(
600 "{actor} made you an owner of {}",
601 team_label(entry, channel)
602 );
603 }
604 (Kind::Team, _) => {
605 return format!("{actor} added you to {}", team_label(entry, channel));
606 }
607 (Kind::App, _) => match &entry.title {
608 Some(title) => return title.clone(),
609 None => entry.source_label.clone().unwrap_or(actor),
610 },
611 (Kind::Other, _) => actor,
612 };
613 verb
614}
615
616fn event_line<Zone: TimeZone>(start: DateTime<Utc>, end: DateTime<Utc>, zone: &Zone) -> String
617where
618 Zone::Offset: std::fmt::Display,
619{
620 let (start, end) = (start.with_timezone(zone), end.with_timezone(zone));
621 let clock = crate::format::clock_format();
622 let dated = format!("%b %-d, {clock}");
623 let end_format = if end.date_naive() == start.date_naive() {
624 clock
625 } else {
626 dated.as_str()
627 };
628 format!("{} - {}", start.format(&dated), end.format(end_format))
629}
630
631fn reply_headline(entry: &Entry, names: &str) -> String {
632 match entry.activity_type.as_str() {
633 "reply" => format!("{names} replied to your post"),
634 "replyInChat" => format!("{names} replied to message"),
635 _ => format!("{names} replied"),
636 }
637}
638
639fn team_label(entry: &Entry, channel: Option<(&str, &str)>) -> String {
640 channel
641 .map(|(team_name, _)| team_name.to_owned())
642 .or_else(|| entry.source_label.clone())
643 .unwrap_or_else(|| "a team".to_owned())
644}
645
646fn channel_of<'a>(sidebar: &'a Sidebar, conversation_id: &str) -> Option<(&'a str, &'a str)> {
647 sidebar.teams.iter().find_map(|team| {
648 team.channels
649 .iter()
650 .find(|channel| channel.id == conversation_id)
651 .map(|channel| (team.team.name.as_str(), channel.name.as_str()))
652 })
653}
654
655fn detail(entry: &Entry) -> String {
656 match entry.kind {
657 Kind::Reaction if !entry.glyphs.is_empty() => {
658 format!("{} to: {}", entry.glyphs.join(" "), entry.preview)
659 }
660 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
661 _ => entry.preview.clone(),
662 }
663}
664
665fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
666 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
667 return match (is_one_on_one(chat), chat.title.trim().is_empty()) {
668 (true, _) => None,
669 (false, true) => Some(format!("Chat with {}", chat_title(chat))),
670 (false, false) => Some(chat_title(chat)),
671 };
672 }
673 sidebar.teams.iter().find_map(|team| {
674 team.channels
675 .iter()
676 .find(|channel| channel.id == conversation_id)
677 .map(|channel| format!("{} > {}", team.team.name, channel.name))
678 })
679}
680
681fn group_header(label: &'static str) -> Div {
682 div()
683 .h(px(HEADER_HEIGHT - 4.))
684 .mt(px(4.))
685 .px(px(16.))
686 .flex()
687 .flex_none()
688 .items_center()
689 .text_size(px(11.))
690 .font_weight(FontWeight::SEMIBOLD)
691 .text_color(theme::text_muted())
692 .child(label)
693}
694
695struct RowText {
696 headline_wraps: bool,
697 lines: Vec<String>,
698}
699
700impl RowText {
701 fn new(entry: &Entry, sidebar: &Sidebar, headline_wraps: bool) -> Self {
702 let lines = entry
703 .event_range
704 .map(|(start, end)| event_line(start, end, &Local))
705 .into_iter()
706 .chain(location_line(entry, sidebar))
707 .collect();
708 Self {
709 headline_wraps,
710 lines,
711 }
712 }
713
714 fn height(&self) -> f32 {
715 row_height(self.headline_wraps, self.lines.len())
716 }
717}
718
719fn row_height(headline_wraps: bool, extra_lines: usize) -> f32 {
720 let headline_extra = if headline_wraps {
721 HEADLINE_LINE_HEIGHT
722 } else {
723 0.
724 };
725 ROW_HEIGHT + headline_extra + extra_lines as f32 * EVENT_LINE_HEIGHT
726}
727
728fn is_recap(entry: &Entry) -> bool {
729 entry.kind == Kind::App && entry.subtype.starts_with("recapIsReady")
730}
731
732fn recap_tile() -> Div {
733 div()
734 .size(px(AVATAR_SIZE))
735 .flex_none()
736 .rounded(px(RECAP_TILE_RADIUS))
737 .bg(theme::accent())
738 .flex()
739 .items_center()
740 .justify_center()
741 .child(symbol("recap", RECAP_GLYPH_SIZE, theme::white()))
742}
743
744fn headline_wraps(headline: String, text_width: f32, window: &mut Window) -> bool {
745 if text_width <= 0. {
746 return false;
747 }
748 let mut run = window.text_style().to_run(headline.len());
749 run.font.weight = FontWeight::SEMIBOLD;
750 let width = window
751 .text_system()
752 .shape_line(headline.into(), px(13.), &[run], None)
753 .width;
754 f32::from(width) > text_width
755}
756
757fn location_line(entry: &Entry, sidebar: &Sidebar) -> Option<String> {
758 match entry.kind {
759 Kind::Mention | Kind::Reply | Kind::Reaction | Kind::Posted => {
760 conversation_label(sidebar, &entry.conversation_id)
761 }
762 _ => None,
763 }
764}
765
766enum Slot<'a> {
767 Proposals(Vec<PendingProposal>),
768 Header(&'static str),
769 Row(&'a Entry, RowText),
770 Empty,
771}
772
773impl Slot<'_> {
774 fn height(&self) -> f32 {
775 match self {
776 Slot::Proposals(proposals) => HEADER_HEIGHT + proposals.len() as f32 * ROW_HEIGHT,
777 Slot::Header(_) => HEADER_HEIGHT,
778 Slot::Row(_, text) => text.height(),
779 Slot::Empty => EMPTY_HEIGHT,
780 }
781 }
782}
783
784#[derive(Debug, PartialEq)]
785struct VisibleSlots {
786 range: Range<usize>,
787 before: f32,
788 after: f32,
789}
790
791fn visible_slots(heights: &[f32], from: f32, to: f32) -> VisibleSlots {
792 let mut position = 0.;
793 let mut first = heights.len();
794 let mut last = heights.len();
795 let mut before = 0.;
796 for (index, height) in heights.iter().enumerate() {
797 let end = position + height;
798 if first == heights.len() && end >= from {
799 first = index;
800 before = position;
801 }
802 if position > to {
803 last = index;
804 break;
805 }
806 position = end;
807 }
808 if first == heights.len() {
809 before = position;
810 }
811 let last = last.max(first);
812 let after = heights[last..].iter().sum();
813 VisibleSlots {
814 range: first..last,
815 before,
816 after,
817 }
818}
819
820impl Render for ActivityPanel {
821 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
822 let now: DateTime<Local> = Local::now();
823 let (today, offset) = (now.date_naive(), now.offset().fix());
824 let panel = cx.entity();
825 let app = self.app.clone();
826 let activity = self.activity.clone();
827 let state = app.read(cx);
828 let sections = activity
829 .read(cx)
830 .feed()
831 .sections(self.filter, today, offset);
832 let measured_width = f32::from(self.scroll.bounds().size.width);
833 let list_width = if measured_width > 1. {
834 measured_width
835 } else {
836 SIDEBAR_WIDTH
837 };
838 let text_width = list_width - ROW_CHROME_WIDTH;
839 let mut slots: Vec<Slot> = Vec::new();
840 let proposals: Vec<PendingProposal> = agent_api::pending_proposals(cx)
841 .into_iter()
842 .filter(|pending| admits_proposal(self.filter, pending))
843 .collect();
844 if !proposals.is_empty() {
845 slots.push(Slot::Proposals(proposals));
846 }
847 for section in &sections {
848 slots.push(Slot::Header(section.bucket.label()));
849 slots.extend(section.entries.iter().map(|entry| {
850 let text = headline(entry, &state.sidebar, &self.resolved_names);
851 let wraps = headline_wraps(text, text_width, window);
852 Slot::Row(entry, RowText::new(entry, &state.sidebar, wraps))
853 }));
854 }
855 if slots.is_empty() {
856 slots.push(Slot::Empty);
857 }
858 let heights: Vec<f32> = slots.iter().map(Slot::height).collect();
859 let top = -f32::from(scroll_offset(&self.scroll).y);
860 let measured = f32::from(self.scroll.bounds().size.height);
861 let height = if measured > 1. {
862 measured
863 } else {
864 f32::from(window.viewport_size().height).max(FALLBACK_VIEWPORT)
865 };
866 let visible = visible_slots(
867 &heights,
868 top - VIEWPORT_MARGIN,
869 top + height + VIEWPORT_MARGIN,
870 );
871 let visible_slots = &slots[visible.range.clone()];
872 let unresolved: Vec<String> = visible_slots
873 .iter()
874 .filter_map(|slot| match slot {
875 Slot::Row(entry, _) => Some(entry.unresolved_user_ids()),
876 _ => None,
877 })
878 .flatten()
879 .filter(|user_id| !self.looked_up.contains(*user_id))
880 .cloned()
881 .collect();
882 if !unresolved.is_empty() {
883 self.looked_up.extend(unresolved.iter().cloned());
884 self.resolved_names
885 .extend(resolve_names(state, &unresolved));
886 }
887 let mut rows: Vec<AnyElement> = Vec::new();
888 if visible.before > 0. {
889 rows.push(div().h(px(visible.before)).flex_none().into_any_element());
890 }
891 for slot in visible_slots {
892 rows.push(match slot {
893 Slot::Proposals(proposals) => v_flex()
894 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
895 .child(group_header(PROPOSALS_LABEL))
896 .children(proposals.iter().map(|pending| {
897 self.proposal_row(pending, &state.sidebar, today, offset, panel.clone())
898 }))
899 .into_any_element(),
900 Slot::Header(label) => group_header(label).into_any_element(),
901 Slot::Row(entry, text) => self.row(
902 entry,
903 text,
904 &state.sidebar,
905 &state.directory,
906 today,
907 offset,
908 panel.clone(),
909 ),
910 Slot::Empty => div()
911 .h(px(EMPTY_HEIGHT))
912 .flex()
913 .flex_none()
914 .items_center()
915 .justify_center()
916 .text_size(px(13.))
917 .text_color(theme::text_muted())
918 .child(self.filter.empty_label())
919 .into_any_element(),
920 });
921 }
922 if visible.after > 0. {
923 rows.push(div().h(px(visible.after)).flex_none().into_any_element());
924 }
925 let list = v_flex()
926 .id("activity-list")
927 .flex_1()
928 .min_h_0()
929 .pb(px(12.))
930 .overflow_y_scrollbar()
931 .track_scroll(&self.scroll)
932 .children(rows);
933 v_flex()
934 .flex_1()
935 .min_h_0()
936 .child(self.header(cx))
937 .child(with_top_edge(list, &self.scroll, SIDEBAR_SCROLL_DIVIDER))
938 }
939}
940
941#[cfg(test)]
942mod tests {
943 use std::collections::HashMap;
944 use std::sync::Arc;
945
946 use chrono::{Local, Offset, TimeZone, Utc};
947 use gpui_kit::{AppContext as _, Modifiers, TestAppContext};
948 use store::{ChatRecord, Sidebar, Store};
949
950 use super::{
951 ActivityPanel, ROW_HEIGHT, VIEWPORT_MARGIN, VisibleSlots, detail, headline, location_line,
952 visible_slots,
953 };
954 use crate::activity::{ActivityCenter, Actor, Entry, Filter, Kind};
955 use crate::app_state::{AppState, Mode};
956
957 fn entry(kind: Kind, count: u32) -> Entry {
958 Entry {
959 id: "1".into(),
960 conversation_id: "chat".into(),
961 kind,
962 message_id: "m1".into(),
963 actors: vec![Actor {
964 user_id: Some("u1".into()),
965 name: "Anna".into(),
966 }],
967 preview: "hello".into(),
968 glyphs: vec!["A".into(), "B".into()],
969 count,
970 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
971 ..Entry::default()
972 }
973 }
974
975 fn with(kind: Kind, activity_type: &str, subtype: &str, count: u32) -> Entry {
976 Entry {
977 activity_type: activity_type.into(),
978 subtype: subtype.into(),
979 ..entry(kind, count)
980 }
981 }
982
983 #[test]
984 fn only_rows_near_the_viewport_are_built() {
985 let heights = vec![ROW_HEIGHT; 300];
986 let viewport = 900.;
987 let at_top = visible_slots(&heights, -VIEWPORT_MARGIN, viewport + VIEWPORT_MARGIN);
988 assert_eq!(
989 at_top,
990 VisibleSlots {
991 range: 0..21,
992 before: 0.,
993 after: 279. * ROW_HEIGHT,
994 }
995 );
996 let scrolled = visible_slots(
997 &heights,
998 5000. - VIEWPORT_MARGIN,
999 5000. + viewport + VIEWPORT_MARGIN,
1000 );
1001 assert_eq!(scrolled.range, 81..107);
1002 assert_eq!(scrolled.before, 81. * ROW_HEIGHT);
1003 assert_eq!(scrolled.after, 193. * ROW_HEIGHT);
1004 let past_the_end = visible_slots(&heights, 90_000., 91_000.);
1005 assert_eq!(past_the_end.range, 300..300);
1006 assert_eq!(past_the_end.before, 300. * ROW_HEIGHT);
1007 assert_eq!(past_the_end.after, 0.);
1008 }
1009
1010 #[test]
1011 fn detail_follows_the_kind() {
1012 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
1013 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
1014 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
1015 assert_eq!(detail(&entry(Kind::Reply, 2)), "hello");
1016 }
1017
1018 #[test]
1019 fn event_line_shows_the_meeting_time_in_local_time() {
1020 let start = chrono::DateTime::from_timestamp_millis(1793865600000).unwrap();
1021 let end = chrono::DateTime::from_timestamp_millis(1793869200000).unwrap();
1022 let berlin = chrono::FixedOffset::east_opt(3600).unwrap();
1023 assert_eq!(
1024 super::event_line(start, end, &berlin),
1025 "Nov 5, 09:00 - 10:00"
1026 );
1027 let next_day = chrono::DateTime::from_timestamp_millis(1793955600000).unwrap();
1028 assert_eq!(
1029 super::event_line(start, next_day, &berlin),
1030 "Nov 5, 09:00 - Nov 6, 10:00"
1031 );
1032 }
1033
1034 #[test]
1035 fn headline_uses_the_teams_activity_texts() {
1036 let sidebar = Sidebar {
1037 chats: vec![ChatRecord {
1038 id: "chat".into(),
1039 kind: "oneOnOne".into(),
1040 ..Default::default()
1041 }],
1042 teams: Vec::new(),
1043 };
1044 let cases = [
1045 (
1046 with(Kind::Mention, "mentionInChat", "person", 1),
1047 "Anna mentioned you",
1048 ),
1049 (
1050 with(Kind::Mention, "mentionInChat", "everyone", 1),
1051 "Anna mentioned Everyone",
1052 ),
1053 (
1054 with(Kind::Reaction, "reactionInChat", "like", 1),
1055 "Anna reacted to your message",
1056 ),
1057 (
1058 with(Kind::Reaction, "reactionInChat", "like", 3),
1059 "Anna +2 reacted to your message",
1060 ),
1061 (
1062 with(Kind::Reply, "reply", "", 1),
1063 "Anna replied to your post",
1064 ),
1065 (with(Kind::Reply, "replyToReply", "", 1), "Anna replied"),
1066 (
1067 with(Kind::MissedCall, "call", "missedCall", 1),
1068 "Missed call from Anna",
1069 ),
1070 (
1071 with(Kind::Call, "call", "missedMeetingNudge", 1),
1072 "Anna asked you to join a meeting",
1073 ),
1074 (
1075 with(Kind::Posted, "follow", "channelNewMessage", 1),
1076 "Anna posted a new message",
1077 ),
1078 ];
1079 for (entry, expected) in cases {
1080 assert_eq!(headline(&entry, &sidebar, &HashMap::new()), expected);
1081 }
1082 }
1083
1084 #[test]
1085 fn headline_names_channel_and_team_mentions() {
1086 let sidebar = Sidebar {
1087 chats: Vec::new(),
1088 teams: vec![store::SidebarTeam {
1089 rights: Default::default(),
1090 team: store::TeamRecord {
1091 id: "team".into(),
1092 name: "Platform".into(),
1093 },
1094 channels: vec![store::ChannelRecord {
1095 id: "chat".into(),
1096 team_id: "team".into(),
1097 name: "Releases".into(),
1098 membership_type: None,
1099 last_message_at: None,
1100 unread: false,
1101 }],
1102 hidden: false,
1103 hidden_channel_ids: Vec::new(),
1104 notifications: Default::default(),
1105 mentions: Default::default(),
1106 }],
1107 };
1108 assert_eq!(
1109 headline(
1110 &with(Kind::Mention, "mention", "channel", 1),
1111 &sidebar,
1112 &HashMap::new()
1113 ),
1114 "Anna mentioned Releases"
1115 );
1116 assert_eq!(
1117 location_line(&with(Kind::Mention, "mention", "channel", 1), &sidebar).as_deref(),
1118 Some("Platform > Releases")
1119 );
1120 assert_eq!(
1121 headline(
1122 &with(Kind::Mention, "mention", "team", 1),
1123 &sidebar,
1124 &HashMap::new()
1125 ),
1126 "Anna mentioned Platform"
1127 );
1128 assert_eq!(
1129 headline(
1130 &with(Kind::Team, "teamMembershipChange", "addedToTeam", 1),
1131 &sidebar,
1132 &HashMap::new()
1133 ),
1134 "Anna added you to Platform"
1135 );
1136 }
1137
1138 #[test]
1139 fn headline_resolves_an_unknown_actor() {
1140 let mut stale = with(Kind::Reaction, "reactionInChat", "like", 1);
1141 stale.actors[0].name = "Unknown".into();
1142 let sidebar = Sidebar::default();
1143 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
1144 assert_eq!(
1145 headline(&stale, &sidebar, &resolved),
1146 "Anna reacted to your message"
1147 );
1148 }
1149
1150 #[gpui_kit::test]
1151 fn row_sliding_under_a_resting_mouse_draws(cx: &mut TestAppContext) {
1152 cx.update(gpui_kit::init);
1153 let store = Arc::new(Store::open_in_memory().unwrap());
1154 crate::demo::seed(&store);
1155 let mode = Mode {
1156 demo: true,
1157 read_only: false,
1158 demo_sync: None,
1159 };
1160 let app = cx.update(|cx| {
1161 cx.new(|_| {
1162 let mut state = AppState::new(store, mode);
1163 crate::demo::seed_directory(&mut state);
1164 state
1165 })
1166 });
1167 let (panel, cx) = cx.add_window_view(|window, cx| {
1168 let activity = cx.new(|cx| ActivityCenter::new(app.clone(), window, cx));
1169 let mut panel = ActivityPanel::new(app.clone(), activity, cx);
1170 panel.filter = Filter::Unread;
1171 panel
1172 });
1173 cx.update(|window, cx| window.draw(cx).clear(cx));
1174 let activity = cx.update(|_, cx| panel.read(cx).activity.clone());
1175 let first_unread = cx.update(|_, cx| {
1176 let now = Local::now();
1177 activity
1178 .read(cx)
1179 .feed()
1180 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
1181 .entries[0]
1182 .id
1183 .clone()
1184 });
1185 let selector: &'static str = format!("activity-row-{first_unread}").leak();
1186 let first_row = cx.debug_bounds(selector).unwrap();
1187 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
1188 cx.update(|window, cx| window.draw(cx).clear(cx));
1189 cx.update(|_, cx| {
1190 activity.update(cx, |activity, cx| activity.mark_read(&first_unread, cx))
1191 });
1192 cx.update(|window, cx| window.draw(cx).clear(cx));
1193 }
1194}