BlueGit

ict rusty-teams

Files

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

activity_panel.rs

activity_panel.rs 17.6 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::{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(
169 h_flex()
170 .px(px(16.))
171 .pb(px(12.))
172 .gap(px(6.))
173 .children(pills),
174 )
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 .group(group.clone())
201 .mx(px(6.))
202 .px(px(10.))
203 .py(px(8.))
204 .gap(px(12.))
205 .items_start()
206 .rounded(px(8.))
207 .cursor_pointer()
208 .hover(|row| row.bg(theme::row_hover()))
209 .child(
210 div()
211 .relative()
212 .flex_none()
213 .size(px(AVATAR_SIZE))
214 .child(avatar)
215 .child(kind_marker(entry, group.clone())),
216 )
217 .child(
218 v_flex()
219 .flex_1()
220 .min_w_0()
221 .gap(px(2.))
222 .child(
223 div()
224 .truncate()
225 .text_size(px(13.))
226 .font_weight(if unread {
227 FontWeight::SEMIBOLD
228 } else {
229 FontWeight::NORMAL
230 })
231 .text_color(if unread {
232 theme::text()
233 } else {
234 theme::text_soft()
235 })
236 .child(headline(entry, sidebar, resolved_names)),
237 )
238 .child(
239 div()
240 .truncate()
241 .text_size(px(12.))
242 .text_color(if unread {
243 theme::text_soft()
244 } else {
245 theme::text_muted()
246 })
247 .child(detail(entry)),
248 ),
249 )
250 .child(
251 v_flex()
252 .flex_none()
253 .items_end()
254 .child(
255 div()
256 .text_size(px(11.))
257 .text_color(theme::text_muted())
258 .child(format::list_time_label(entry.updated_at, today, offset)),
259 )
260 .child(status_slot(id, unread, group, activity)),
261 )
262 .on_click(move |_, _, cx| panel.update(cx, |this, cx| this.open(id, cx)))
263 .into_any_element()
264 }
265}
266
267fn status_slot(
268 id: i64,
269 unread: bool,
270 group: SharedString,
271 activity: Entity<ActivityCenter>,
272) -> Div {
273 let slot = div()
274 .h(px(MARK_READ_SIZE))
275 .flex()
276 .flex_none()
277 .items_center()
278 .justify_end();
279 if !unread {
280 return slot;
281 }
282 slot.child(
283 div()
284 .flex()
285 .group_hover(group.clone(), |wrapper| wrapper.hidden())
286 .mr(px(8.))
287 .child(dot(8.)),
288 )
289 .child(
290 div()
291 .id(ElementId::Name(format!("activity-mark-read-{id}").into()))
292 .hidden()
293 .group_hover(group, |button| button.flex())
294 .size(px(MARK_READ_SIZE))
295 .flex_none()
296 .items_center()
297 .justify_center()
298 .rounded(px(6.))
299 .bg(theme::surface_raised())
300 .cursor_pointer()
301 .child(icon(IconName::Check, 12., theme::text()))
302 .tooltip(|window, cx| Tooltip::new("Mark as read").build(window, cx))
303 .on_click(move |_, _, cx| {
304 cx.stop_propagation();
305 activity.update(cx, |activity, cx| activity.mark_read(id, cx));
306 }),
307 )
308}
309
310fn kind_marker(entry: &Entry, row_group: SharedString) -> Div {
311 let marker = div()
312 .absolute()
313 .right(px(-4.))
314 .bottom(px(-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 v_flex()
439 .flex_1()
440 .min_h_0()
441 .child(self.header(cx))
442 .child(
443 v_flex()
444 .id("activity-list")
445 .flex_1()
446 .min_h_0()
447 .pb(px(12.))
448 .overflow_y_scroll()
449 .track_scroll(&self.scroll)
450 .children(rows),
451 )
452 }
453}
454
455#[cfg(test)]
456mod tests {
457 use std::collections::HashMap;
458
459 use chrono::{TimeZone, Utc};
460 use store::{ChatRecord, Sidebar};
461
462 use super::{detail, headline};
463 use crate::activity::{Actor, Entry, Kind};
464
465 fn entry(kind: Kind, count: u32) -> Entry {
466 Entry {
467 id: 1,
468 conversation_id: "chat".into(),
469 kind,
470 message_id: "m1".into(),
471 actors: vec![Actor {
472 user_id: Some("u1".into()),
473 name: "Anna".into(),
474 }],
475 preview: "hello".into(),
476 glyphs: vec!["A".into(), "B".into()],
477 count,
478 updated_at: Utc.with_ymd_and_hms(2026, 10, 8, 9, 0, 0).unwrap(),
479 read: false,
480 }
481 }
482
483 #[test]
484 fn detail_follows_the_kind() {
485 assert_eq!(detail(&entry(Kind::Messages, 1)), "hello");
486 assert_eq!(detail(&entry(Kind::Messages, 3)), "3 new messages: hello");
487 assert_eq!(detail(&entry(Kind::Mention, 1)), "hello");
488 assert_eq!(detail(&entry(Kind::Reaction, 1)), "A B to: hello");
489 assert_eq!(detail(&entry(Kind::MissedCall, 3)), "3 missed calls");
490 }
491
492 #[test]
493 fn headline_names_the_actor_and_skips_direct_chat_context() {
494 let sidebar = Sidebar {
495 chats: vec![ChatRecord {
496 id: "chat".into(),
497 kind: "oneOnOne".into(),
498 ..Default::default()
499 }],
500 teams: Vec::new(),
501 };
502 assert_eq!(
503 headline(&entry(Kind::Messages, 1), &sidebar, &HashMap::new()),
504 "Anna"
505 );
506 assert_eq!(
507 headline(&entry(Kind::Reaction, 1), &sidebar, &HashMap::new()),
508 "Anna reacted"
509 );
510 assert_eq!(
511 headline(&entry(Kind::Mention, 1), &sidebar, &HashMap::new()),
512 "Anna mentioned you"
513 );
514 assert_eq!(
515 headline(&entry(Kind::MissedCall, 1), &sidebar, &HashMap::new()),
516 "Missed call from Anna"
517 );
518 }
519
520 #[test]
521 fn headline_resolves_a_persisted_unknown_actor() {
522 let mut stale = entry(Kind::Reaction, 1);
523 stale.actors[0].name = "Unknown".into();
524 let sidebar = Sidebar::default();
525 let resolved = HashMap::from([("u1".to_owned(), "Anna".to_owned())]);
526 assert_eq!(headline(&stale, &sidebar, &resolved), "Anna reacted");
527 assert_eq!(
528 headline(&stale, &sidebar, &HashMap::new()),
529 "Unknown reacted"
530 );
531 }
532}