BlueGit

ict rusty-teams

Files

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

activity_panel.rs

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