BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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