Skip to main content

fc_ui/capabilities/overlays/
notification_center.rs

1use crate::capabilities::foundation::theme::use_theme;
2use crate::capabilities::primitives::button::{Button, ButtonVariant};
3use crate::capabilities::primitives::empty_state::EmptyState;
4use crate::capabilities::primitives::icon::Icon;
5use crate::capabilities::primitives::icon_source::IconSource;
6use crate::capabilities::scroll::scrollable::scrollable_vertical;
7use gpui::{prelude::FluentBuilder as _, *};
8use std::rc::Rc;
9
10#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
11pub enum NotificationVariant {
12    #[default]
13    Info,
14    Success,
15    Warning,
16    Error,
17}
18
19impl NotificationVariant {
20    fn icon_name(&self) -> &'static str {
21        match self {
22            NotificationVariant::Info => "info",
23            NotificationVariant::Success => "circle-check",
24            NotificationVariant::Warning => "triangle-alert",
25            NotificationVariant::Error => "x-circle",
26        }
27    }
28
29    fn color(&self, theme: &crate::capabilities::foundation::theme::Theme) -> Hsla {
30        match self {
31            NotificationVariant::Info => theme.tokens.primary,
32            NotificationVariant::Success => gpui::hsla(142.0 / 360.0, 0.71, 0.45, 1.0),
33            NotificationVariant::Warning => gpui::hsla(48.0 / 360.0, 0.96, 0.53, 1.0),
34            NotificationVariant::Error => theme.tokens.destructive,
35        }
36    }
37}
38
39#[derive(Clone)]
40pub struct NotificationAction {
41    pub label: SharedString,
42    pub handler: Rc<dyn Fn(&mut Window, &mut App)>,
43}
44
45#[derive(Clone)]
46pub struct NotificationItem {
47    pub id: ElementId,
48    pub title: SharedString,
49    pub message: Option<SharedString>,
50    pub timestamp: Option<SharedString>,
51    pub variant: NotificationVariant,
52    pub read: bool,
53    pub icon: Option<IconSource>,
54    pub action: Option<NotificationAction>,
55}
56
57impl NotificationItem {
58    pub fn new(id: impl Into<ElementId>, title: impl Into<SharedString>) -> Self {
59        Self {
60            id: id.into(),
61            title: title.into(),
62            message: None,
63            timestamp: None,
64            variant: NotificationVariant::default(),
65            read: false,
66            icon: None,
67            action: None,
68        }
69    }
70
71    pub fn message(mut self, message: impl Into<SharedString>) -> Self {
72        self.message = Some(message.into());
73        self
74    }
75
76    pub fn timestamp(mut self, timestamp: impl Into<SharedString>) -> Self {
77        self.timestamp = Some(timestamp.into());
78        self
79    }
80
81    pub fn variant(mut self, variant: NotificationVariant) -> Self {
82        self.variant = variant;
83        self
84    }
85
86    pub fn read(mut self, read: bool) -> Self {
87        self.read = read;
88        self
89    }
90
91    pub fn icon(mut self, icon: impl Into<IconSource>) -> Self {
92        self.icon = Some(icon.into());
93        self
94    }
95
96    pub fn action(
97        mut self,
98        label: impl Into<SharedString>,
99        handler: impl Fn(&mut Window, &mut App) + 'static,
100    ) -> Self {
101        self.action = Some(NotificationAction {
102            label: label.into(),
103            handler: Rc::new(handler),
104        });
105        self
106    }
107}
108
109pub struct NotificationCenterState {
110    notifications: Vec<NotificationItem>,
111    _focus_handle: FocusHandle,
112}
113
114impl NotificationCenterState {
115    pub fn new(cx: &mut Context<Self>) -> Self {
116        Self {
117            notifications: Vec::new(),
118            _focus_handle: cx.focus_handle(),
119        }
120    }
121
122    pub fn add(&mut self, notification: NotificationItem, cx: &mut Context<Self>) {
123        self.notifications.insert(0, notification);
124        cx.notify();
125    }
126
127    pub fn remove(&mut self, id: &ElementId, cx: &mut Context<Self>) {
128        self.notifications.retain(|n| &n.id != id);
129        cx.notify();
130    }
131
132    pub fn mark_read(&mut self, id: &ElementId, cx: &mut Context<Self>) {
133        if let Some(notification) = self.notifications.iter_mut().find(|n| &n.id == id) {
134            notification.read = true;
135            cx.notify();
136        }
137    }
138
139    pub fn mark_all_read(&mut self, cx: &mut Context<Self>) {
140        for notification in &mut self.notifications {
141            notification.read = true;
142        }
143        cx.notify();
144    }
145
146    pub fn clear_all(&mut self, cx: &mut Context<Self>) {
147        self.notifications.clear();
148        cx.notify();
149    }
150
151    pub fn unread_count(&self) -> usize {
152        self.notifications.iter().filter(|n| !n.read).count()
153    }
154
155    pub fn notifications(&self) -> &[NotificationItem] {
156        &self.notifications
157    }
158
159    pub fn is_empty(&self) -> bool {
160        self.notifications.is_empty()
161    }
162}
163
164impl EventEmitter<()> for NotificationCenterState {}
165
166#[derive(IntoElement)]
167pub struct NotificationCenter {
168    state: Entity<NotificationCenterState>,
169    max_visible: usize,
170    show_timestamps: bool,
171    group_by_date: bool,
172    on_notification_click: Option<Rc<dyn Fn(&NotificationItem, &mut Window, &mut App)>>,
173    style: StyleRefinement,
174}
175
176impl NotificationCenter {
177    pub fn new(state: Entity<NotificationCenterState>) -> Self {
178        Self {
179            state,
180            max_visible: 10,
181            show_timestamps: true,
182            group_by_date: false,
183            on_notification_click: None,
184            style: StyleRefinement::default(),
185        }
186    }
187
188    pub fn max_visible(mut self, max: usize) -> Self {
189        self.max_visible = max;
190        self
191    }
192
193    pub fn show_timestamps(mut self, show: bool) -> Self {
194        self.show_timestamps = show;
195        self
196    }
197
198    pub fn group_by_date(mut self, group: bool) -> Self {
199        self.group_by_date = group;
200        self
201    }
202
203    pub fn on_notification_click(
204        mut self,
205        handler: impl Fn(&NotificationItem, &mut Window, &mut App) + 'static,
206    ) -> Self {
207        self.on_notification_click = Some(Rc::new(handler));
208        self
209    }
210}
211
212impl Styled for NotificationCenter {
213    fn style(&mut self) -> &mut StyleRefinement {
214        &mut self.style
215    }
216}
217
218impl RenderOnce for NotificationCenter {
219    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
220        let theme = use_theme(cx);
221        let user_style = self.style;
222        let state = self.state.read(cx);
223        let notifications = state.notifications().to_vec();
224        let is_empty = notifications.is_empty();
225        let total_count = notifications.len();
226        let show_more = total_count > self.max_visible;
227        let visible_notifications: Vec<_> =
228            notifications.into_iter().take(self.max_visible).collect();
229
230        let state_entity = self.state.clone();
231        let on_click = self.on_notification_click.clone();
232        let show_timestamps = self.show_timestamps;
233
234        let shadow_lg = theme.tokens.shadow_lg.clone();
235
236        div()
237            .flex()
238            .flex_col()
239            .w(px(380.0))
240            .max_h(px(500.0))
241            .bg(theme.tokens.card)
242            .border_1()
243            .border_color(theme.tokens.border)
244            .rounded(theme.tokens.radius_lg)
245            .shadow(smallvec::smallvec![shadow_lg])
246            .overflow_hidden()
247            .map(|mut this| {
248                this.style().refine(&user_style);
249                this
250            })
251            .child(
252                div()
253                    .flex()
254                    .items_center()
255                    .justify_between()
256                    .px(px(16.0))
257                    .py(px(12.0))
258                    .border_b_1()
259                    .border_color(theme.tokens.border)
260                    .child(
261                        div()
262                            .text_size(px(14.0))
263                            .font_weight(FontWeight::SEMIBOLD)
264                            .text_color(theme.tokens.foreground)
265                            .font_family(theme.tokens.font_family.clone())
266                            .child("Notifications"),
267                    )
268                    .when(!is_empty, {
269                        let state_clone = state_entity.clone();
270                        |d| {
271                            d.child(
272                                Button::new("mark-all-read", "Mark all read")
273                                    .variant(ButtonVariant::Ghost)
274                                    .size(crate::capabilities::primitives::button::ButtonSize::Sm)
275                                    .on_click(move |_, _, cx| {
276                                        state_clone.update(cx, |state, cx| {
277                                            state.mark_all_read(cx);
278                                        });
279                                    }),
280                            )
281                        }
282                    }),
283            )
284            .when(is_empty, |d| {
285                d.child(
286                    EmptyState::new("notification-empty", "No notifications")
287                        .icon("bell-off")
288                        .description("You're all caught up!")
289                        .size(crate::capabilities::primitives::empty_state::EmptyStateSize::Sm)
290                        .py(px(32.0)),
291                )
292            })
293            .when(!is_empty, |d| {
294                d.child(
295                    scrollable_vertical(div().flex().flex_col().children(
296                        visible_notifications.into_iter().map(|notification| {
297                            let id = notification.id.clone();
298                            let state_for_click = state_entity.clone();
299                            let state_for_dismiss = state_entity.clone();
300                            let on_click_handler = on_click.clone();
301                            let notification_clone = notification.clone();
302                            let is_read = notification.read;
303                            let variant = notification.variant;
304                            let variant_color = variant.color(&theme);
305
306                            div()
307                                .id(id.clone())
308                                .flex()
309                                .gap(px(12.0))
310                                .px(px(16.0))
311                                .py(px(12.0))
312                                .border_b_1()
313                                .border_color(theme.tokens.border)
314                                .bg(if is_read {
315                                    gpui::transparent_black()
316                                } else {
317                                    theme.tokens.accent.opacity(0.3)
318                                })
319                                .cursor(CursorStyle::PointingHand)
320                                .hover(|style| style.bg(theme.tokens.accent))
321                                .on_mouse_down(MouseButton::Left, {
322                                    let id = id.clone();
323                                    move |_, window, cx| {
324                                        state_for_click.update(cx, |state, cx| {
325                                            state.mark_read(&id, cx);
326                                        });
327                                        if let Some(ref handler) = on_click_handler {
328                                            handler(&notification_clone, window, cx);
329                                        }
330                                    }
331                                })
332                                .child(
333                                    div().flex_shrink_0().mt(px(2.0)).child(
334                                        Icon::new(
335                                            notification
336                                                .icon
337                                                .clone()
338                                                .unwrap_or_else(|| variant.icon_name().into()),
339                                        )
340                                        .size(px(18.0))
341                                        .color(variant_color),
342                                    ),
343                                )
344                                .child(
345                                    div()
346                                        .flex()
347                                        .flex_col()
348                                        .flex_1()
349                                        .gap(px(4.0))
350                                        .overflow_hidden()
351                                        .child(
352                                            div()
353                                                .flex()
354                                                .items_center()
355                                                .justify_between()
356                                                .gap(px(8.0))
357                                                .child(
358                                                    div()
359                                                        .text_size(px(13.0))
360                                                        .font_weight(if is_read {
361                                                            FontWeight::NORMAL
362                                                        } else {
363                                                            FontWeight::SEMIBOLD
364                                                        })
365                                                        .text_color(theme.tokens.foreground)
366                                                        .font_family(
367                                                            theme.tokens.font_family.clone(),
368                                                        )
369                                                        .truncate()
370                                                        .child(notification.title.clone()),
371                                                )
372                                                .when(
373                                                    show_timestamps
374                                                        && notification.timestamp.is_some(),
375                                                    |d| {
376                                                        d.child(
377                                                            div()
378                                                                .flex_shrink_0()
379                                                                .text_size(px(11.0))
380                                                                .text_color(
381                                                                    theme.tokens.muted_foreground,
382                                                                )
383                                                                .font_family(
384                                                                    theme
385                                                                        .tokens
386                                                                        .font_family
387                                                                        .clone(),
388                                                                )
389                                                                .child(
390                                                                    notification
391                                                                        .timestamp
392                                                                        .clone()
393                                                                        .unwrap_or_default(),
394                                                                ),
395                                                        )
396                                                    },
397                                                ),
398                                        )
399                                        .when_some(notification.message.clone(), |d, msg| {
400                                            d.child(
401                                                div()
402                                                    .text_size(px(12.0))
403                                                    .text_color(theme.tokens.muted_foreground)
404                                                    .font_family(theme.tokens.font_family.clone())
405                                                    .line_height(relative(1.4))
406                                                    .child(msg),
407                                            )
408                                        })
409                                        .when_some(notification.action.clone(), |d, action| {
410                                            let handler = action.handler.clone();
411                                            d.child(
412                                                div().mt(px(4.0)).child(
413                                                    Button::new(
414                                                        ElementId::Name(
415                                                            format!("action-{:?}", id).into(),
416                                                        ),
417                                                        action.label.clone(),
418                                                    )
419                                                    .variant(ButtonVariant::Outline)
420                                                    .size(crate::capabilities::primitives::button::ButtonSize::Sm)
421                                                    .on_click(move |_, window, cx| {
422                                                        (handler)(window, cx);
423                                                    }),
424                                                ),
425                                            )
426                                        }),
427                                )
428                                .child(
429                                    div()
430                                        .flex_shrink_0()
431                                        .w(px(20.0))
432                                        .h(px(20.0))
433                                        .flex()
434                                        .items_center()
435                                        .justify_center()
436                                        .rounded(theme.tokens.radius_sm)
437                                        .text_color(theme.tokens.muted_foreground)
438                                        .text_size(px(14.0))
439                                        .font_family(theme.tokens.font_family.clone())
440                                        .hover(|style| style.bg(theme.tokens.accent))
441                                        .on_mouse_down(MouseButton::Left, {
442                                            let id = id.clone();
443                                            move |_, _, cx| {
444                                                cx.stop_propagation();
445                                                state_for_dismiss.update(cx, |state, cx| {
446                                                    state.remove(&id, cx);
447                                                });
448                                            }
449                                        })
450                                        .child(
451                                            Icon::new("x")
452                                                .size(px(14.0))
453                                                .color(theme.tokens.muted_foreground),
454                                        ),
455                                )
456                        }),
457                    ))
458                    .max_h(px(350.0)),
459                )
460            })
461            .when(show_more, |d| {
462                d.child(
463                    div()
464                        .px(px(16.0))
465                        .py(px(8.0))
466                        .border_t_1()
467                        .border_color(theme.tokens.border)
468                        .child(
469                            div()
470                                .text_size(px(12.0))
471                                .text_color(theme.tokens.muted_foreground)
472                                .font_family(theme.tokens.font_family.clone())
473                                .text_align(TextAlign::Center)
474                                .child(format!(
475                                    "+ {} more notifications",
476                                    total_count - self.max_visible
477                                )),
478                        ),
479                )
480            })
481            .when(!is_empty, {
482                let state_clone = state_entity.clone();
483                |d| {
484                    d.child(
485                        div()
486                            .flex()
487                            .justify_center()
488                            .px(px(16.0))
489                            .py(px(8.0))
490                            .border_t_1()
491                            .border_color(theme.tokens.border)
492                            .child(
493                                Button::new("clear-all", "Clear all")
494                                    .variant(ButtonVariant::Ghost)
495                                    .size(crate::capabilities::primitives::button::ButtonSize::Sm)
496                                    .on_click(move |_, _, cx| {
497                                        state_clone.update(cx, |state, cx| {
498                                            state.clear_all(cx);
499                                        });
500                                    }),
501                            ),
502                    )
503                }
504            })
505    }
506}
507
508#[derive(IntoElement)]
509pub struct NotificationBell {
510    id: ElementId,
511    state: Entity<NotificationCenterState>,
512    on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
513    style: StyleRefinement,
514}
515
516impl NotificationBell {
517    pub fn new(state: Entity<NotificationCenterState>) -> Self {
518        Self {
519            id: ElementId::Name("notification-bell".into()),
520            state,
521            on_click: None,
522            style: StyleRefinement::default(),
523        }
524    }
525
526    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
527        self.id = id.into();
528        self
529    }
530
531    pub fn on_click(
532        mut self,
533        handler: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
534    ) -> Self {
535        self.on_click = Some(Rc::new(handler));
536        self
537    }
538}
539
540impl Styled for NotificationBell {
541    fn style(&mut self) -> &mut StyleRefinement {
542        &mut self.style
543    }
544}
545
546impl RenderOnce for NotificationBell {
547    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
548        let theme = use_theme(cx);
549        let user_style = self.style;
550        let unread_count = self.state.read(cx).unread_count();
551        let on_click = self.on_click.clone();
552
553        div()
554            .id(self.id)
555            .relative()
556            .w(px(40.0))
557            .h(px(40.0))
558            .flex()
559            .items_center()
560            .justify_center()
561            .rounded(theme.tokens.radius_md)
562            .cursor(CursorStyle::PointingHand)
563            .hover(|style| style.bg(theme.tokens.accent))
564            .map(|mut this| {
565                this.style().refine(&user_style);
566                this
567            })
568            .when_some(on_click, |d, handler| {
569                d.on_click(move |event, window, cx| {
570                    (handler)(event, window, cx);
571                })
572            })
573            .child(
574                Icon::new("bell")
575                    .size(px(20.0))
576                    .color(theme.tokens.foreground),
577            )
578            .when(unread_count > 0, |d| {
579                d.child(
580                    div()
581                        .absolute()
582                        .top(px(4.0))
583                        .right(px(4.0))
584                        .min_w(px(18.0))
585                        .h(px(18.0))
586                        .px(px(5.0))
587                        .flex()
588                        .items_center()
589                        .justify_center()
590                        .rounded_full()
591                        .bg(theme.tokens.destructive)
592                        .text_size(px(10.0))
593                        .font_weight(FontWeight::BOLD)
594                        .text_color(theme.tokens.destructive_foreground)
595                        .font_family(theme.tokens.font_family.clone())
596                        .child(if unread_count > 99 {
597                            "99+".to_string()
598                        } else {
599                            unread_count.to_string()
600                        }),
601                )
602            })
603    }
604}