BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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