BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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