BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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