1use crate::{chat_panel::ChatPanel, NotificationPanelSettings};
2use anyhow::Result;
3use channel::ChannelStore;
4use client::{ChannelId, Client, Notification, User, UserStore};
5use collections::HashMap;
6use db::kvp::KEY_VALUE_STORE;
7use futures::StreamExt;
8use gpui::{
9 actions, div, img, list, px, AnyElement, AppContext, AsyncWindowContext, CursorStyle,
10 DismissEvent, Element, EventEmitter, FocusHandle, FocusableView, InteractiveElement,
11 IntoElement, ListAlignment, ListScrollEvent, ListState, Model, ParentElement, Render,
12 StatefulInteractiveElement, Styled, Task, View, ViewContext, VisualContext, WeakView,
13 WindowContext,
14};
15use notifications::{NotificationEntry, NotificationEvent, NotificationStore};
16use project::Fs;
17use rpc::proto;
18use serde::{Deserialize, Serialize};
19use settings::{Settings, SettingsStore};
20use std::{sync::Arc, time::Duration};
21use time::{OffsetDateTime, UtcOffset};
22use ui::{h_flex, prelude::*, v_flex, Avatar, Button, Icon, IconButton, IconName, Label, Tooltip};
23use util::{ResultExt, TryFutureExt};
24use workspace::{
25 dock::{DockPosition, Panel, PanelEvent},
26 Workspace,
27};
28
29const LOADING_THRESHOLD: usize = 30;
30const MARK_AS_READ_DELAY: Duration = Duration::from_secs(1);
31const TOAST_DURATION: Duration = Duration::from_secs(5);
32const NOTIFICATION_PANEL_KEY: &str = "NotificationPanel";
33
34pub struct NotificationPanel {
35 client: Arc<Client>,
36 user_store: Model<UserStore>,
37 channel_store: Model<ChannelStore>,
38 notification_store: Model<NotificationStore>,
39 fs: Arc<dyn Fs>,
40 width: Option<Pixels>,
41 active: bool,
42 notification_list: ListState,
43 pending_serialization: Task<Option<()>>,
44 subscriptions: Vec<gpui::Subscription>,
45 workspace: WeakView<Workspace>,
46 current_notification_toast: Option<(u64, Task<()>)>,
47 local_timezone: UtcOffset,
48 focus_handle: FocusHandle,
49 mark_as_read_tasks: HashMap<u64, Task<Result<()>>>,
50 unseen_notifications: Vec<NotificationEntry>,
51}
52
53#[derive(Serialize, Deserialize)]
54struct SerializedNotificationPanel {
55 width: Option<Pixels>,
56}
57
58#[derive(Debug)]
59pub enum Event {
60 DockPositionChanged,
61 Focus,
62 Dismissed,
63}
64
65pub struct NotificationPresenter {
66 pub actor: Option<Arc<client::User>>,
67 pub text: String,
68 pub icon: &'static str,
69 pub needs_response: bool,
70 pub can_navigate: bool,
71}
72
73actions!(notification_panel, [ToggleFocus]);
74
75pub fn init(cx: &mut AppContext) {
76 cx.observe_new_views(|workspace: &mut Workspace, _| {
77 workspace.register_action(|workspace, _: &ToggleFocus, cx| {
78 workspace.toggle_panel_focus::<NotificationPanel>(cx);
79 });
80 })
81 .detach();
82}
83
84impl NotificationPanel {
85 pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> View<Self> {
86 let fs = workspace.app_state().fs.clone();
87 let client = workspace.app_state().client.clone();
88 let user_store = workspace.app_state().user_store.clone();
89 let workspace_handle = workspace.weak_handle();
90
91 cx.new_view(|cx: &mut ViewContext<Self>| {
92 let mut status = client.status();
93 cx.spawn(|this, mut cx| async move {
94 while let Some(_) = status.next().await {
95 if this
96 .update(&mut cx, |_, cx| {
97 cx.notify();
98 })
99 .is_err()
100 {
101 break;
102 }
103 }
104 })
105 .detach();
106
107 let view = cx.view().downgrade();
108 let notification_list =
109 ListState::new(0, ListAlignment::Top, px(1000.), move |ix, cx| {
110 view.upgrade()
111 .and_then(|view| {
112 view.update(cx, |this, cx| this.render_notification(ix, cx))
113 })
114 .unwrap_or_else(|| div().into_any())
115 });
116 notification_list.set_scroll_handler(cx.listener(
117 |this, event: &ListScrollEvent, cx| {
118 if event.count.saturating_sub(event.visible_range.end) < LOADING_THRESHOLD {
119 if let Some(task) = this
120 .notification_store
121 .update(cx, |store, cx| store.load_more_notifications(false, cx))
122 {
123 task.detach();
124 }
125 }
126 },
127 ));
128
129 let mut this = Self {
130 fs,
131 client,
132 user_store,
133 local_timezone: cx.local_timezone(),
134 channel_store: ChannelStore::global(cx),
135 notification_store: NotificationStore::global(cx),
136 notification_list,
137 pending_serialization: Task::ready(None),
138 workspace: workspace_handle,
139 focus_handle: cx.focus_handle(),
140 current_notification_toast: None,
141 subscriptions: Vec::new(),
142 active: false,
143 mark_as_read_tasks: HashMap::default(),
144 width: None,
145 unseen_notifications: Vec::new(),
146 };
147
148 let mut old_dock_position = this.position(cx);
149 this.subscriptions.extend([
150 cx.observe(&this.notification_store, |_, _, cx| cx.notify()),
151 cx.subscribe(&this.notification_store, Self::on_notification_event),
152 cx.observe_global::<SettingsStore>(move |this: &mut Self, cx| {
153 let new_dock_position = this.position(cx);
154 if new_dock_position != old_dock_position {
155 old_dock_position = new_dock_position;
156 cx.emit(Event::DockPositionChanged);
157 }
158 cx.notify();
159 }),
160 ]);
161 this
162 })
163 }
164
165 pub fn load(
166 workspace: WeakView<Workspace>,
167 cx: AsyncWindowContext,
168 ) -> Task<Result<View<Self>>> {
169 cx.spawn(|mut cx| async move {
170 let serialized_panel = if let Some(panel) = cx
171 .background_executor()
172 .spawn(async move { KEY_VALUE_STORE.read_kvp(NOTIFICATION_PANEL_KEY) })
173 .await
174 .log_err()
175 .flatten()
176 {
177 Some(serde_json::from_str::<SerializedNotificationPanel>(&panel)?)
178 } else {
179 None
180 };
181
182 workspace.update(&mut cx, |workspace, cx| {
183 let panel = Self::new(workspace, cx);
184 if let Some(serialized_panel) = serialized_panel {
185 panel.update(cx, |panel, cx| {
186 panel.width = serialized_panel.width.map(|w| w.round());
187 cx.notify();
188 });
189 }
190 panel
191 })
192 })
193 }
194
195 fn serialize(&mut self, cx: &mut ViewContext<Self>) {
196 let width = self.width;
197 self.pending_serialization = cx.background_executor().spawn(
198 async move {
199 KEY_VALUE_STORE
200 .write_kvp(
201 NOTIFICATION_PANEL_KEY.into(),
202 serde_json::to_string(&SerializedNotificationPanel { width })?,
203 )
204 .await?;
205 anyhow::Ok(())
206 }
207 .log_err(),
208 );
209 }
210
211 fn render_notification(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> Option<AnyElement> {
212 let entry = self.notification_store.read(cx).notification_at(ix)?;
213 let notification_id = entry.id;
214 let now = OffsetDateTime::now_utc();
215 let timestamp = entry.timestamp;
216 let NotificationPresenter {
217 actor,
218 text,
219 needs_response,
220 can_navigate,
221 ..
222 } = self.present_notification(entry, cx)?;
223
224 let response = entry.response;
225 let notification = entry.notification.clone();
226
227 if self.active && !entry.is_read {
228 self.did_render_notification(notification_id, ¬ification, cx);
229 }
230
231 let relative_timestamp = time_format::format_localized_timestamp(
232 timestamp,
233 now,
234 self.local_timezone,
235 time_format::TimestampFormat::Relative,
236 );
237
238 let absolute_timestamp = time_format::format_localized_timestamp(
239 timestamp,
240 now,
241 self.local_timezone,
242 time_format::TimestampFormat::Absolute,
243 );
244
245 Some(
246 div()
247 .id(ix)
248 .flex()
249 .flex_row()
250 .size_full()
251 .px_2()
252 .py_1()
253 .gap_2()
254 .hover(|style| style.bg(cx.theme().colors().element_hover))
255 .when(can_navigate, |el| {
256 el.cursor(CursorStyle::PointingHand).on_click({
257 let notification = notification.clone();
258 cx.listener(move |this, _, cx| {
259 this.did_click_notification(¬ification, cx)
260 })
261 })
262 })
263 .children(actor.map(|actor| {
264 img(actor.avatar_uri.clone())
265 .flex_none()
266 .w_8()
267 .h_8()
268 .rounded_full()
269 }))
270 .child(
271 v_flex()
272 .gap_1()
273 .size_full()
274 .overflow_hidden()
275 .child(Label::new(text.clone()))
276 .child(
277 h_flex()
278 .child(
279 div()
280 .id("notification_timestamp")
281 .hover(|style| {
282 style
283 .bg(cx.theme().colors().element_selected)
284 .rounded_md()
285 })
286 .child(Label::new(relative_timestamp).color(Color::Muted))
287 .tooltip(move |cx| {
288 Tooltip::text(absolute_timestamp.clone(), cx)
289 }),
290 )
291 .children(if let Some(is_accepted) = response {
292 Some(div().flex().flex_grow().justify_end().child(Label::new(
293 if is_accepted {
294 "You accepted"
295 } else {
296 "You declined"
297 },
298 )))
299 } else if needs_response {
300 Some(
301 h_flex()
302 .flex_grow()
303 .justify_end()
304 .child(Button::new("decline", "Decline").on_click({
305 let notification = notification.clone();
306 let view = cx.view().clone();
307 move |_, cx| {
308 view.update(cx, |this, cx| {
309 this.respond_to_notification(
310 notification.clone(),
311 false,
312 cx,
313 )
314 });
315 }
316 }))
317 .child(Button::new("accept", "Accept").on_click({
318 let notification = notification.clone();
319 let view = cx.view().clone();
320 move |_, cx| {
321 view.update(cx, |this, cx| {
322 this.respond_to_notification(
323 notification.clone(),
324 true,
325 cx,
326 )
327 });
328 }
329 })),
330 )
331 } else {
332 None
333 }),
334 ),
335 )
336 .into_any(),
337 )
338 }
339
340 fn present_notification(
341 &self,
342 entry: &NotificationEntry,
343 cx: &AppContext,
344 ) -> Option<NotificationPresenter> {
345 let user_store = self.user_store.read(cx);
346 let channel_store = self.channel_store.read(cx);
347 match entry.notification {
348 Notification::ContactRequest { sender_id } => {
349 let requester = user_store.get_cached_user(sender_id)?;
350 Some(NotificationPresenter {
351 icon: "icons/plus.svg",
352 text: format!("{} wants to add you as a contact", requester.github_login),
353 needs_response: user_store.has_incoming_contact_request(requester.id),
354 actor: Some(requester),
355 can_navigate: false,
356 })
357 }
358 Notification::ContactRequestAccepted { responder_id } => {
359 let responder = user_store.get_cached_user(responder_id)?;
360 Some(NotificationPresenter {
361 icon: "icons/plus.svg",
362 text: format!("{} accepted your contact invite", responder.github_login),
363 needs_response: false,
364 actor: Some(responder),
365 can_navigate: false,
366 })
367 }
368 Notification::ChannelInvitation {
369 ref channel_name,
370 channel_id,
371 inviter_id,
372 } => {
373 let inviter = user_store.get_cached_user(inviter_id)?;
374 Some(NotificationPresenter {
375 icon: "icons/hash.svg",
376 text: format!(
377 "{} invited you to join the #{channel_name} channel",
378 inviter.github_login
379 ),
380 needs_response: channel_store.has_channel_invitation(ChannelId(channel_id)),
381 actor: Some(inviter),
382 can_navigate: false,
383 })
384 }
385 Notification::ChannelMessageMention {
386 sender_id,
387 channel_id,
388 message_id,
389 } => {
390 let sender = user_store.get_cached_user(sender_id)?;
391 let channel = channel_store.channel_for_id(ChannelId(channel_id))?;
392 let message = self
393 .notification_store
394 .read(cx)
395 .channel_message_for_id(message_id)?;
396 Some(NotificationPresenter {
397 icon: "icons/conversations.svg",
398 text: format!(
399 "{} mentioned you in #{}:\n{}",
400 sender.github_login, channel.name, message.body,
401 ),
402 needs_response: false,
403 actor: Some(sender),
404 can_navigate: true,
405 })
406 }
407 }
408 }
409
410 fn did_render_notification(
411 &mut self,
412 notification_id: u64,
413 notification: &Notification,
414 cx: &mut ViewContext<Self>,
415 ) {
416 let should_mark_as_read = match notification {
417 Notification::ContactRequestAccepted { .. } => true,
418 Notification::ContactRequest { .. }
419 | Notification::ChannelInvitation { .. }
420 | Notification::ChannelMessageMention { .. } => false,
421 };
422
423 if should_mark_as_read {
424 self.mark_as_read_tasks
425 .entry(notification_id)
426 .or_insert_with(|| {
427 let client = self.client.clone();
428 cx.spawn(|this, mut cx| async move {
429 cx.background_executor().timer(MARK_AS_READ_DELAY).await;
430 client
431 .request(proto::MarkNotificationRead { notification_id })
432 .await?;
433 this.update(&mut cx, |this, _| {
434 this.mark_as_read_tasks.remove(¬ification_id);
435 })?;
436 Ok(())
437 })
438 });
439 }
440 }
441
442 fn did_click_notification(&mut self, notification: &Notification, cx: &mut ViewContext<Self>) {
443 if let Notification::ChannelMessageMention {
444 message_id,
445 channel_id,
446 ..
447 } = notification.clone()
448 {
449 if let Some(workspace) = self.workspace.upgrade() {
450 cx.window_context().defer(move |cx| {
451 workspace.update(cx, |workspace, cx| {
452 if let Some(panel) = workspace.focus_panel::<ChatPanel>(cx) {
453 panel.update(cx, |panel, cx| {
454 panel
455 .select_channel(ChannelId(channel_id), Some(message_id), cx)
456 .detach_and_log_err(cx);
457 });
458 }
459 });
460 });
461 }
462 }
463 }
464
465 fn is_showing_notification(&self, notification: &Notification, cx: &ViewContext<Self>) -> bool {
466 if !self.active {
467 return false;
468 }
469
470 if let Notification::ChannelMessageMention { channel_id, .. } = ¬ification {
471 if let Some(workspace) = self.workspace.upgrade() {
472 return if let Some(panel) = workspace.read(cx).panel::<ChatPanel>(cx) {
473 let panel = panel.read(cx);
474 panel.is_scrolled_to_bottom()
475 && panel
476 .active_chat()
477 .map_or(false, |chat| chat.read(cx).channel_id.0 == *channel_id)
478 } else {
479 false
480 };
481 }
482 }
483
484 false
485 }
486
487 fn on_notification_event(
488 &mut self,
489 _: Model<NotificationStore>,
490 event: &NotificationEvent,
491 cx: &mut ViewContext<Self>,
492 ) {
493 match event {
494 NotificationEvent::NewNotification { entry } => {
495 if !self.is_showing_notification(&entry.notification, cx) {
496 self.unseen_notifications.push(entry.clone());
497 }
498 self.add_toast(entry, cx);
499 }
500 NotificationEvent::NotificationRemoved { entry }
501 | NotificationEvent::NotificationRead { entry } => {
502 self.unseen_notifications.retain(|n| n.id != entry.id);
503 self.remove_toast(entry.id, cx);
504 }
505 NotificationEvent::NotificationsUpdated {
506 old_range,
507 new_count,
508 } => {
509 self.notification_list.splice(old_range.clone(), *new_count);
510 cx.notify();
511 }
512 }
513 }
514
515 fn add_toast(&mut self, entry: &NotificationEntry, cx: &mut ViewContext<Self>) {
516 if self.is_showing_notification(&entry.notification, cx) {
517 return;
518 }
519
520 let Some(NotificationPresenter { actor, text, .. }) = self.present_notification(entry, cx)
521 else {
522 return;
523 };
524
525 let notification_id = entry.id;
526 self.current_notification_toast = Some((
527 notification_id,
528 cx.spawn(|this, mut cx| async move {
529 cx.background_executor().timer(TOAST_DURATION).await;
530 this.update(&mut cx, |this, cx| this.remove_toast(notification_id, cx))
531 .ok();
532 }),
533 ));
534
535 self.workspace
536 .update(cx, |workspace, cx| {
537 workspace.dismiss_notification::<NotificationToast>(0, cx);
538 workspace.show_notification(0, cx, |cx| {
539 let workspace = cx.view().downgrade();
540 cx.new_view(|_| NotificationToast {
541 notification_id,
542 actor,
543 text,
544 workspace,
545 })
546 })
547 })
548 .ok();
549 }
550
551 fn remove_toast(&mut self, notification_id: u64, cx: &mut ViewContext<Self>) {
552 if let Some((current_id, _)) = &self.current_notification_toast {
553 if *current_id == notification_id {
554 self.current_notification_toast.take();
555 self.workspace
556 .update(cx, |workspace, cx| {
557 workspace.dismiss_notification::<NotificationToast>(0, cx)
558 })
559 .ok();
560 }
561 }
562 }
563
564 fn respond_to_notification(
565 &mut self,
566 notification: Notification,
567 response: bool,
568 cx: &mut ViewContext<Self>,
569 ) {
570 self.notification_store.update(cx, |store, cx| {
571 store.respond_to_notification(notification, response, cx);
572 });
573 }
574}
575
576impl Render for NotificationPanel {
577 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
578 v_flex()
579 .size_full()
580 .child(
581 h_flex()
582 .justify_between()
583 .px_2()
584 .py_1()
585 // Match the height of the tab bar so they line up.
586 .h(rems(ui::Tab::CONTAINER_HEIGHT_IN_REMS))
587 .border_b_1()
588 .border_color(cx.theme().colors().border)
589 .child(Label::new("Notifications"))
590 .child(Icon::new(IconName::Envelope)),
591 )
592 .map(|this| {
593 if self.client.user_id().is_none() {
594 this.child(
595 v_flex()
596 .gap_2()
597 .p_4()
598 .child(
599 Button::new("sign_in_prompt_button", "Sign in")
600 .icon_color(Color::Muted)
601 .icon(IconName::Github)
602 .icon_position(IconPosition::Start)
603 .style(ButtonStyle::Filled)
604 .full_width()
605 .on_click({
606 let client = self.client.clone();
607 move |_, cx| {
608 let client = client.clone();
609 cx.spawn(move |cx| async move {
610 client
611 .authenticate_and_connect(true, &cx)
612 .log_err()
613 .await;
614 })
615 .detach()
616 }
617 }),
618 )
619 .child(
620 div().flex().w_full().items_center().child(
621 Label::new("Sign in to view notifications.")
622 .color(Color::Muted)
623 .size(LabelSize::Small),
624 ),
625 ),
626 )
627 } else if self.notification_list.item_count() == 0 {
628 this.child(
629 v_flex().p_4().child(
630 div().flex().w_full().items_center().child(
631 Label::new("You have no notifications.")
632 .color(Color::Muted)
633 .size(LabelSize::Small),
634 ),
635 ),
636 )
637 } else {
638 this.child(list(self.notification_list.clone()).size_full())
639 }
640 })
641 }
642}
643
644impl FocusableView for NotificationPanel {
645 fn focus_handle(&self, _: &AppContext) -> FocusHandle {
646 self.focus_handle.clone()
647 }
648}
649
650impl EventEmitter<Event> for NotificationPanel {}
651impl EventEmitter<PanelEvent> for NotificationPanel {}
652
653impl Panel for NotificationPanel {
654 fn persistent_name() -> &'static str {
655 "NotificationPanel"
656 }
657
658 fn position(&self, cx: &gpui::WindowContext) -> DockPosition {
659 NotificationPanelSettings::get_global(cx).dock
660 }
661
662 fn position_is_valid(&self, position: DockPosition) -> bool {
663 matches!(position, DockPosition::Left | DockPosition::Right)
664 }
665
666 fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {
667 settings::update_settings_file::<NotificationPanelSettings>(
668 self.fs.clone(),
669 cx,
670 move |settings| settings.dock = Some(position),
671 );
672 }
673
674 fn size(&self, cx: &gpui::WindowContext) -> Pixels {
675 self.width
676 .unwrap_or_else(|| NotificationPanelSettings::get_global(cx).default_width)
677 }
678
679 fn set_size(&mut self, size: Option<Pixels>, cx: &mut ViewContext<Self>) {
680 self.width = size;
681 self.serialize(cx);
682 cx.notify();
683 }
684
685 fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {
686 self.active = active;
687
688 if self.active {
689 self.unseen_notifications = Vec::new();
690 cx.notify();
691 }
692
693 if self.notification_store.read(cx).notification_count() == 0 {
694 cx.emit(Event::Dismissed);
695 }
696 }
697
698 fn icon(&self, cx: &gpui::WindowContext) -> Option<IconName> {
699 let show_button = NotificationPanelSettings::get_global(cx).button;
700 if !show_button {
701 return None;
702 }
703
704 if self.unseen_notifications.is_empty() {
705 return Some(IconName::Bell);
706 }
707
708 Some(IconName::BellDot)
709 }
710
711 fn icon_tooltip(&self, _cx: &WindowContext) -> Option<&'static str> {
712 Some("Notification Panel")
713 }
714
715 fn icon_label(&self, cx: &WindowContext) -> Option<String> {
716 let count = self.notification_store.read(cx).unread_notification_count();
717 if count == 0 {
718 None
719 } else {
720 Some(count.to_string())
721 }
722 }
723
724 fn toggle_action(&self) -> Box<dyn gpui::Action> {
725 Box::new(ToggleFocus)
726 }
727}
728
729pub struct NotificationToast {
730 notification_id: u64,
731 actor: Option<Arc<User>>,
732 text: String,
733 workspace: WeakView<Workspace>,
734}
735
736impl NotificationToast {
737 fn focus_notification_panel(&self, cx: &mut ViewContext<Self>) {
738 let workspace = self.workspace.clone();
739 let notification_id = self.notification_id;
740 cx.window_context().defer(move |cx| {
741 workspace
742 .update(cx, |workspace, cx| {
743 if let Some(panel) = workspace.focus_panel::<NotificationPanel>(cx) {
744 panel.update(cx, |panel, cx| {
745 let store = panel.notification_store.read(cx);
746 if let Some(entry) = store.notification_for_id(notification_id) {
747 panel.did_click_notification(&entry.clone().notification, cx);
748 }
749 });
750 }
751 })
752 .ok();
753 })
754 }
755}
756
757impl Render for NotificationToast {
758 fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
759 let user = self.actor.clone();
760
761 h_flex()
762 .id("notification_panel_toast")
763 .elevation_3(cx)
764 .p_2()
765 .gap_2()
766 .children(user.map(|user| Avatar::new(user.avatar_uri.clone())))
767 .child(Label::new(self.text.clone()))
768 .child(
769 IconButton::new("close", IconName::Close)
770 .on_click(cx.listener(|_, _, cx| cx.emit(DismissEvent))),
771 )
772 .on_click(cx.listener(|this, _, cx| {
773 this.focus_notification_panel(cx);
774 cx.emit(DismissEvent);
775 }))
776 }
777}
778
779impl EventEmitter<DismissEvent> for NotificationToast {}