BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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