BlueGit

ict rusty-teams

Files

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

activity_panel.rs

activity_panel.rs 23.7 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::rc::Rc;
3
4use chrono::{DateTime, Local, NaiveDate, Offset};
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use store::Sidebar;
10
11use super::avatar::person_avatar;
12use super::scroll_edge::with_top_edge;
13use super::sidebar::SIDEBAR_SCROLL_DIVIDER;
14use super::widgets::{Corner, corner_badge, dot, icon};
15use crate::activity::{ActivityCenter, Entry, Filter, Kind};
16use crate::agent_api::{
17 self,
18 pending::{PendingKind, PendingProposal, conversation_label as proposal_conversation_label},
19};
20use crate::app_state::{AppState, chat_title};
21use crate::data::is_one_on_one;
22use crate::format;
23use crate::people::resolve_names;
24use crate::theme;
25
26const AVATAR_SIZE: f32 = 32.;
27const KIND_MARKER_SIZE: f32 = 16.;
28const BUTTON_SIZE: f32 = 32.;
29const MARK_READ_SIZE: f32 = 20.;
30const FILTER_KEY: &str = "activity_filter";
31const PROPOSALS_LABEL: &str = "Agent proposals";
32pub const ACTIVITY_PROPOSALS_TAG: &str = "shell/islands/sidebar/activity-proposals";
33
34pub enum ActivityPanelEvent {
35 OpenSettings,
36 Open {
37 conversation_id: String,
38 message_id: String,
39 },
40}
41
42pub struct ActivityPanel {
43 app: Entity<AppState>,
44 activity: Entity<ActivityCenter>,
45 filter: Filter,
46 scroll: ScrollHandle,
47 resolved_names: HashMap<String, String>,
48 looked_up: HashSet<String>,
49 _observations: [Subscription; 2],
50}
51
52impl EventEmitter<ActivityPanelEvent> for ActivityPanel {}
53
54impl ActivityPanel {
55 pub fn activity(&self) -> Entity<ActivityCenter> {
56 self.activity.clone()
57 }
58
59 pub fn new(
60 app: Entity<AppState>,
61 activity: Entity<ActivityCenter>,
62 cx: &mut Context<Self>,
63 ) -> Self {
64 let observations = [
65 cx.observe(&app, |_, _, cx| cx.notify()),
66 cx.observe(&activity, |_, _, cx| cx.notify()),
67 ];
68 let filter = app
69 .read(cx)
70 .store
71 .meta(FILTER_KEY)
72 .ok()
73 .flatten()
74 .and_then(|key| Filter::from_key(&key))
75 .unwrap_or_default();
76 ActivityPanel {
77 app,
78 activity,
79 filter,
80 scroll: ScrollHandle::new(),
81 resolved_names: HashMap::new(),
82 looked_up: HashSet::new(),
83 _observations: observations,
84 }
85 }
86
87 fn open(&mut self, id: i64, cx: &mut Context<Self>) {
88 let Some(entry) = self.activity.read(cx).feed().get(id) else {
89 return;
90 };
91 let event = ActivityPanelEvent::Open {
92 conversation_id: entry.conversation_id.clone(),
93 message_id: entry.message_id.clone(),
94 };
95 self.activity
96 .update(cx, |activity, cx| activity.mark_read(id, cx));
97 cx.emit(event);
98 }
99
100 fn header(&self, cx: &mut Context<Self>) -> Div {
101 let pills = Filter::ALL.into_iter().map(|filter| {
102 let selected = filter == self.filter;
103 div()
104 .id(ElementId::Name(
105 format!("activity-filter-{}", filter.label()).into(),
106 ))
107 .h(px(24.))
108 .px(px(12.))
109 .flex()
110 .items_center()
111 .rounded_full()
112 .cursor_pointer()
113 .text_size(px(12.))
114 .when(selected, |pill| {
115 pill.bg(theme::accent()).text_color(theme::on_accent())
116 })
117 .when(!selected, |pill| {
118 pill.bg(theme::surface_raised())
119 .text_color(theme::text_soft())
120 .hover(|pill| pill.bg(theme::border_strong()))
121 })
122 .child(filter.label())
123 .on_click(cx.listener(move |this, _, _, cx| {
124 this.filter = filter;
125 let _ = this.app.read(cx).store.set_meta(FILTER_KEY, filter.key());
126 cx.notify();
127 }))
128 });
129 v_flex()
130 .flex_none()
131 .child(
132 h_flex()
133 .h(px(52.))
134 .pl(px(16.))
135 .pr(px(12.))
136 .gap(px(4.))
137 .items_center()
138 .child(
139 div()
140 .flex_1()
141 .text_size(px(16.))
142 .font_weight(FontWeight::BOLD)
143 .text_color(theme::text())
144 .child("Activity"),
145 )
146 .child(
147 div()
148 .id("activity-mark-all-read")
149 .px(px(8.))
150 .h(px(BUTTON_SIZE))
151 .flex()
152 .items_center()
153 .rounded(px(8.))
154 .cursor_pointer()
155 .text_size(px(12.))
156 .text_color(theme::accent_text())
157 .hover(|button| button.bg(theme::surface_raised()))
158 .child("Mark all as read")
159 .on_click(cx.listener(|this, _, _, cx| {
160 this.activity
161 .update(cx, |activity, cx| activity.mark_all_read(cx));
162 })),
163 )
164 .child(
165 div()
166 .id("activity-settings")
167 .size(px(BUTTON_SIZE))
168 .flex()
169 .flex_none()
170 .items_center()
171 .justify_center()
172 .rounded(px(8.))
173 .cursor_pointer()
174 .hover(|button| button.bg(theme::surface_raised()))
175 .child(icon(IconName::Settings, 16., theme::text_muted()))
176 .on_click(cx.listener(|_, _, _, cx| {
177 cx.emit(ActivityPanelEvent::OpenSettings);
178 })),
179 ),
180 )
181 .child(h_flex().px(px(16.)).pb(px(12.)).gap(px(6.)).children(pills))
182 }
183
184 fn row(
185 &self,
186 entry: &Entry,
187 sidebar: &Sidebar,
188 directory: &crate::data::Directory,
189 today: NaiveDate,
190 offset: chrono::FixedOffset,
191 panel: Entity<ActivityPanel>,
192 ) -> AnyElement {
193 let activity = self.activity.clone();
194 let id = entry.id;
195 let actor = entry.latest_actor();
196 let avatar = person_avatar(
197 directory,
198 actor.and_then(|actor| actor.user_id.as_deref()),
199 actor.map_or("", |actor| actor.display_name(&self.resolved_names)),
200 AVATAR_SIZE,
201 );
202 let group = SharedString::from(format!("activity-row-group-{id}"));
203 row_frame(RowParts {
204 element_id: format!("activity-row-{id}"),
205 avatar: avatar.into_any_element(),
206 marker: kind_marker(entry, group.clone()),
207 group,
208 headline: headline(entry, sidebar, &self.resolved_names),
209 detail: detail(entry),
210 unread: !entry.read,
211 time: format::list_time_label(entry.updated_at, today, offset),
212 mark_read: Rc::new(move |cx: &mut App| {
213 activity.update(cx, |activity, cx| activity.mark_read(id, cx))
214 }),
215 })
216 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
217 .into_any_element()
218 }
219
220 fn proposal_row(
221 &self,
222 pending: &PendingProposal,
223 sidebar: &Sidebar,
224 today: NaiveDate,
225 offset: chrono::FixedOffset,
226 panel: Entity<ActivityPanel>,
227 ) -> AnyElement {
228 let group = SharedString::from(format!("activity-proposal-group-{}", pending.id));
229 let label = proposal_conversation_label(sidebar, &pending.conversation_id);
230 let proposal_id = pending.id.clone();
231 let opened = pending.clone();
232 row_frame(RowParts {
233 element_id: format!("activity-proposal-{}", pending.id),
234 avatar: agent_avatar().into_any_element(),
235 marker: proposal_marker(pending, group.clone()),
236 group,
237 headline: pending.headline(label.as_deref()),
238 detail: pending.detail(),
239 unread: !pending.seen,
240 time: format::list_time_label(pending.created_at, today, offset),
241 mark_read: Rc::new(move |cx: &mut App| agent_api::mark_proposal_seen(&proposal_id, cx)),
242 })
243 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open_proposal(&opened, cx)))
244 .into_any_element()
245 }
246
247 fn open_proposal(&mut self, pending: &PendingProposal, cx: &mut Context<Self>) {
248 agent_api::mark_proposal_seen(&pending.id, cx);
249 cx.emit(ActivityPanelEvent::Open {
250 conversation_id: pending.conversation_id.clone(),
251 message_id: pending.jump_message_id().to_owned(),
252 });
253 }
254}
255
256struct RowParts {
257 element_id: String,
258 group: SharedString,
259 avatar: AnyElement,
260 marker: Div,
261 headline: String,
262 detail: String,
263 unread: bool,
264 time: String,
265 mark_read: MarkRead,
266}
267
268type MarkRead = Rc<dyn Fn(&mut App)>;
269
270fn row_frame(parts: RowParts) -> Stateful<Div> {
271 let RowParts {
272 element_id,
273 group,
274 avatar,
275 marker,
276 headline,
277 detail,
278 unread,
279 time,
280 mark_read,
281 } = parts;
282 let selector = element_id.clone();
283 h_flex()
284 .id(ElementId::Name(element_id.clone().into()))
285 .debug_selector(move || selector)
286 .group(group.clone())
287 .mx(px(6.))
288 .px(px(10.))
289 .py(px(8.))
290 .gap(px(12.))
291 .items_start()
292 .rounded(px(8.))
293 .cursor_pointer()
294 .hover(|row| row.bg(theme::row_hover()))
295 .child(
296 div()
297 .relative()
298 .flex_none()
299 .size(px(AVATAR_SIZE))
300 .child(avatar)
301 .child(marker),
302 )
303 .child(
304 v_flex()
305 .flex_1()
306 .min_w_0()
307 .gap(px(2.))
308 .child(
309 div()
310 .truncate()
311 .text_size(px(13.))
312 .font_weight(if unread {
313 FontWeight::SEMIBOLD
314 } else {
315 FontWeight::NORMAL
316 })
317 .text_color(if unread {
318 theme::text()
319 } else {
320 theme::text_soft()
321 })
322 .child(headline),
323 )
324 .child(
325 div()
326 .truncate()
327 .text_size(px(12.))
328 .text_color(if unread {
329 theme::text_soft()
330 } else {
331 theme::text_muted()
332 })
333 .child(detail),
334 ),
335 )
336 .child(
337 v_flex()
338 .flex_none()
339 .items_end()
340 .child(
341 div()
342 .text_size(px(11.))
343 .text_color(theme::text_muted())
344 .child(time),
345 )
346 .child(status_slot(element_id, unread, group, mark_read)),
347 )
348}
349
350fn agent_avatar() -> Div {
351 div()
352 .size(px(AVATAR_SIZE))
353 .flex()
354 .items_center()
355 .justify_center()
356 .rounded_full()
357 .bg(theme::accent_soft())
358 .child(icon(IconName::Bot, 16., theme::accent_text()))
359}
360
361fn admits_proposal(filter: Filter, pending: &PendingProposal) -> bool {
362 match filter {
363 Filter::All => true,
364 Filter::Mentions => false,
365 Filter::Unread => !pending.seen,
366 }
367}
368
369fn status_slot(element_id: String, unread: bool, group: SharedString, mark_read: MarkRead) -> Div {
370 let slot = div()
371 .h(px(MARK_READ_SIZE))
372 .flex()
373 .flex_none()
374 .items_center()
375 .justify_end();
376 if !unread {
377 return slot;
378 }
379 // Toggle visibility, never display: gpui reads hover in prepaint and paint from different frames.
380 slot.relative()
381 .w(px(MARK_READ_SIZE))
382 .child(
383 div()
384 .flex()
385 .group_hover(group.clone(), |wrapper| wrapper.invisible())
386 .mr(px(8.))
387 .child(dot(8.)),
388 )
389 .child(
390 div()
391 .id(ElementId::Name(format!("{element_id}-mark-read").into()))
392 .absolute()
393 .top_0()
394 .right_0()
395 .invisible()
396 .group_hover(group, |button| button.visible())
397 .size(px(MARK_READ_SIZE))
398 .flex()
399 .items_center()
400 .justify_center()
401 .rounded(px(6.))
402 .bg(theme::surface_raised())
403 .cursor_pointer()
404 .child(icon(IconName::Check, 12., theme::text()))
405 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
406 .on_click(move |_, _, cx| {
407 cx.stop_propagation();
408 mark_read(cx);
409 }),
410 )
411}
412
413fn marker_frame(row_group: SharedString) -> Div {
414 corner_badge(Corner::BottomRight, 4.)
415 .size(px(KIND_MARKER_SIZE))
416 .flex()
417 .items_center()
418 .justify_center()
419 .rounded_full()
420 .border_2()
421 .border_color(theme::surface())
422 .group_hover(row_group, |marker| marker.border_color(theme::row_hover()))
423 .bg(theme::surface_raised())
424 .text_size(px(10.))
425}
426
427fn proposal_marker(pending: &PendingProposal, row_group: SharedString) -> Div {
428 let marker = marker_frame(row_group);
429 match &pending.kind {
430 PendingKind::Reply { .. } => {
431 marker.child(icon(IconName::MessageCircle, 10., theme::text_muted()))
432 }
433 PendingKind::Reaction { glyph, .. } => marker.child(glyph.clone()),
434 }
435}
436
437fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
438 let marker = marker_frame(row_group);
439 match entry.kind {
440 Kind::Messages => marker.child(icon(IconName::MessageCircle, 10., theme::text_muted())),
441 Kind::Mention => marker
442 .text_color(theme::accent_text())
443 .font_weight(FontWeight::BOLD)
444 .child("@"),
445 Kind::Reaction => marker.child(entry.glyphs.first().cloned().unwrap_or_default()),
446 Kind::MissedCall => marker.child(icon(IconName::PhoneOff, 10., theme::red())),
447 }
448}
449
450fn headline(entry: &Entry, sidebar: &Sidebar, resolved_names: &HashMap<String, String>) -> String {
451 let names = entry.names(resolved_names);
452 let verb = match entry.kind {
453 Kind::Messages => names,
454 Kind::Mention => format!("{names} mentioned you"),
455 Kind::Reaction => format!("{names} reacted"),
456 Kind::MissedCall => format!("Missed call from {names}"),
457 };
458 match conversation_label(sidebar, &entry.conversation_id) {
459 Some(label) => format!("{verb} in {label}"),
460 None => verb,
461 }
462}
463
464fn detail(entry: &Entry) -> String {
465 match entry.kind {
466 Kind::Messages if entry.count > 1 => {
467 format!("{} new messages: {}", entry.count, entry.preview)
468 }
469 Kind::Reaction => format!("{} to: {}", entry.glyphs.join(" "), entry.preview),
470 Kind::MissedCall if entry.count > 1 => format!("{} missed calls", entry.count),
471 _ => entry.preview.clone(),
472 }
473}
474
475fn conversation_label(sidebar: &Sidebar, conversation_id: &str) -> Option<String> {
476 if let Some(chat) = sidebar.chats.iter().find(|chat| chat.id == conversation_id) {
477 return (!is_one_on_one(chat)).then(|| chat_title(chat));
478 }
479 sidebar.teams.iter().find_map(|team| {
480 team.channels
481 .iter()
482 .find(|channel| channel.id == conversation_id)
483 .map(|channel| format!("{} > {}", team.team.name, channel.name))
484 })
485}
486
487fn group_header(label: &'static str) -> Div {
488 div()
489 .h(px(26.))
490 .mt(px(4.))
491 .px(px(16.))
492 .flex()
493 .flex_none()
494 .items_center()
495 .text_size(px(11.))
496 .font_weight(FontWeight::SEMIBOLD)
497 .text_color(theme::text_muted())
498 .child(label)
499}
500
501impl Render for ActivityPanel {
502 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
503 let now: DateTime<Local> = Local::now();
504 let (today, offset) = (now.date_naive(), now.offset().fix());
505 let panel = cx.entity();
506 let app = self.app.clone();
507 let activity = self.activity.clone();
508 let state = app.read(cx);
509 let sections = activity
510 .read(cx)
511 .feed()
512 .sections(self.filter, today, offset);
513 let unresolved: Vec<String> = sections
514 .iter()
515 .flat_map(|section| section.entries.iter())
516 .flat_map(|entry| entry.unresolved_user_ids())
517 .filter(|user_id| !self.looked_up.contains(*user_id))
518 .cloned()
519 .collect();
520 if !unresolved.is_empty() {
521 self.looked_up.extend(unresolved.iter().cloned());
522 self.resolved_names
523 .extend(resolve_names(state, &unresolved));
524 }
525 let mut rows: Vec<AnyElement> = Vec::new();
526 let proposal_rows: Vec<AnyElement> = agent_api::pending_proposals(cx)
527 .iter()
528 .filter(|pending| admits_proposal(self.filter, pending))
529 .map(|pending| self.proposal_row(pending, &state.sidebar, today, offset, panel.clone()))
530 .collect();
531 if !proposal_rows.is_empty() {
532 rows.push(
533 v_flex()
534 .debug_selector(|| ACTIVITY_PROPOSALS_TAG.into())
535 .child(group_header(PROPOSALS_LABEL))
536 .children(proposal_rows)
537 .into_any_element(),
538 );
539 }
540 for section in sections {
541 rows.push(group_header(section.bucket.label()).into_any_element());
542 for entry in section.entries {
543 rows.push(self.row(
544 entry,
545 &state.sidebar,
546 &state.directory,
547 today,
548 offset,
549 panel.clone(),
550 ));
551 }
552 }
553 if rows.is_empty() {
554 rows.push(
555 div()
556 .py(px(32.))
557 .flex()
558 .justify_center()
559 .text_size(px(13.))
560 .text_color(theme::text_muted())
561 .child(self.filter.empty_label())
562 .into_any_element(),
563 );
564 }
565 let list = v_flex()
566 .id("activity-list")
567 .flex_1()
568 .min_h_0()
569 .pb(px(12.))
570 .overflow_y_scroll()
571 .track_scroll(&self.scroll)
572 .children(rows);
573 v_flex()
574 .flex_1()
575 .min_h_0()
576 .child(self.header(cx))
577 .child(with_top_edge(list, &self.scroll, SIDEBAR_SCROLL_DIVIDER))
578 }
579}
580
581#[cfg(test)]
582mod tests {
583 use std::collections::HashMap;
584 use std::sync::Arc;
585
586 use chrono::{Local, Offset, TimeZone, Utc};
587 use gpui_kit::{AppContext as _, Modifiers, TestAppContext};
588 use store::{ChatRecord, Sidebar, Store};
589
590 use super::{ActivityPanel, detail, headline};
591 use crate::activity::{ActivityCenter, Actor, Entry, Filter, Kind};
592 use crate::app_state::{AppState, Mode};
593
594 fn entry(kind: Kind, count: u32) -> Entry {
595 Entry {
596 id: 1,
597 conversation_id: "chat".into(),
598 kind,
599 message_id: "m1".into(),
600 actors: vec![Actor {
601 user_id: Some("u1".into()),
602 name: "Anna".into(),
603 }],
604 preview: "hello".into(),
605 glyphs: vec!["A".into(), "B".into()],
606 count,
607 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
608 read: false,
609 }
610 }
611
612 #[test]
613 fn detail_follows_the_kind() {
614 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
615 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
616 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
617 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
618 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
619 }
620
621 #[test]
622 fn headline_names_the_actor_and_skips_direct_chat_context() {
623 let sidebar = Sidebar {
624 chats: vec![ChatRecord {
625 id: "chat".into(),
626 kind: "oneOnOne".into(),
627 ..Default::default()
628 }],
629 teams: Vec::new(),
630 };
631 assert_eq!(
632 headline(&entry(Kind::Messages, 1), &sidebar, &HashMap::new()),
633 "Anna"
634 );
635 assert_eq!(
636 headline(&entry(Kind::Reaction, 1), &sidebar, &HashMap::new()),
637 "Anna reacted"
638 );
639 assert_eq!(
640 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
641 "Anna mentioned you"
642 );
643 assert_eq!(
644 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
645 "Missed call from Anna"
646 );
647 }
648
649 #[test]
650 fn headline_resolves_a_persisted_unknown_actor() {
651 let mut stale = entry(Kind::Reaction, 1);
652 stale.actors[0].name = "Unknown".into();
653 let sidebar = Sidebar::default();
654 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
655 assert_eq!(headline(&stale, &sidebar, &resolved), "Anna reacted");
656 assert_eq!(
657 headline(&stale, &sidebar, &HashMap::new()),
658 "Unknown reacted"
659 );
660 }
661
662 #[gpui_kit::test]
663 fn row_sliding_under_a_resting_mouse_draws(cx: &mut TestAppContext) {
664 cx.update(gpui_kit::init);
665 let store = Arc::new(Store::open_in_memory().unwrap());
666 crate::demo::seed(&store);
667 let mode = Mode {
668 demo: true,
669 read_only: false,
670 demo_sync: None,
671 };
672 let app = cx.update(|cx| {
673 cx.new(|_| {
674 let mut state = AppState::new(store, mode);
675 crate::demo::seed_directory(&mut state);
676 state
677 })
678 });
679 let (panel, cx) = cx.add_window_view(|window, cx| {
680 let activity = cx.new(|cx| ActivityCenter::new(app.clone(), window, cx));
681 let mut panel = ActivityPanel::new(app.clone(), activity, cx);
682 panel.filter = Filter::Unread;
683 panel
684 });
685 cx.update(|window, cx| window.draw(cx).clear(cx));
686 let activity = cx.update(|_, cx| panel.read(cx).activity.clone());
687 let first_unread = cx.update(|_, cx| {
688 let now = Local::now();
689 activity
690 .read(cx)
691 .feed()
692 .sections(Filter::Unread, now.date_naive(), now.offset().fix())[0]
693 .entries[0]
694 .id
695 });
696 let selector: &'static str = format!("activity-row-{first_unread}").leak();
697 let first_row = cx.debug_bounds(selector).unwrap();
698 cx.simulate_mouse_move(first_row.center(), None, Modifiers::none());
699 cx.update(|window, cx| window.draw(cx).clear(cx));
700 cx.update(|_, cx| activity.update(cx, |activity, cx| activity.mark_read(first_unread, cx)));
701 cx.update(|window, cx| window.draw(cx).clear(cx));
702 }
703}