notification_panel.rs

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