notification: Add action button to Notification. (#832)

- Fix `Icon` clone to keep text_color and other attributes.

<img width="1303" alt="image"
src="https://github.com/user-attachments/assets/abb35045-166e-450e-a200-1d4a1d2b6dd8"
/>
This commit is contained in:
Jason Lee 2025-05-06 16:58:07 +08:00 committed by GitHub
parent 9906a482ec
commit e530af9b51
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 105 additions and 62 deletions

View file

@ -6,7 +6,7 @@ use gpui::{
use gpui_component::{ use gpui_component::{
button::{Button, ButtonVariants as _}, button::{Button, ButtonVariants as _},
notification::{Notification, NotificationType}, notification::{Notification, NotificationType},
ContextModal as _, IconName, ContextModal as _,
}; };
use crate::section; use crate::section;
@ -54,14 +54,28 @@ impl Render for NotificationStory {
.track_focus(&self.focus_handle) .track_focus(&self.focus_handle)
.size_full() .size_full()
.child( .child(
section("Show Notification") section("Simple Notification").child(
Button::new("show-notify-0")
.label("Show Notification")
.on_click(cx.listener(|_, _, window, cx| {
window.push_notification("This is a notification.", cx)
})),
),
)
.child(
section("Notification with Type")
.child( .child(
Button::new("show-notify-info") Button::new("show-notify-info")
.info() .info()
.label("Info") .label("Info")
.on_click(cx.listener(|_, _, window, cx| { .on_click(cx.listener(|_, _, window, cx| {
window window.push_notification(
.push_notification("You have been saved file successfully.", cx) (
NotificationType::Info,
"You have been saved file successfully.",
),
cx,
)
})), })),
) )
.child( .child(
@ -106,31 +120,36 @@ impl Render for NotificationStory {
cx, cx,
) )
})), })),
)
.child(
Button::new("show-notify-with-title")
.label("Notification with Title")
.on_click(cx.listener(|_, _, window, cx| {
struct TestNotification;
window.push_notification(
Notification::new(
"你已经成功保存了文件,但是有一些警告信息需要你注意。",
)
.id::<TestNotification>()
.title("保存成功")
.icon(IconName::Inbox)
.autohide(false)
.on_click(cx.listener(
|_, _, _, cx| {
println!("Notification clicked");
cx.notify();
},
)),
cx,
)
})),
), ),
) )
.child(
section("With title and action").child(
Button::new("show-notify-with-title")
.label("Notification with Title")
.on_click(cx.listener(|_, _, window, cx| {
struct TestNotification;
window.push_notification(
Notification::new("There was a problem with your request.")
.id::<TestNotification>()
.title("Uh oh! Something went wrong.")
.autohide(false)
.action(|_, cx| {
Button::new("try-again").label("Try again").on_click(
cx.listener(|this, _, window, cx| {
println!("You have clicked the try again action.");
this.dismiss(window, cx);
}),
)
})
.on_click(cx.listener(|_, _, _, cx| {
println!("Notification clicked");
cx.notify();
})),
cx,
)
})),
),
)
} }
} }

View file

@ -212,9 +212,10 @@ impl Default for Icon {
impl Clone for Icon { impl Clone for Icon {
fn clone(&self) -> Self { fn clone(&self) -> Self {
let mut this = Self::default().path(self.path.clone()); let mut this = Self::default().path(self.path.clone());
if let Some(size) = self.size { this.style = self.style.clone();
this = this.with_size(size); this.rotation = self.rotation;
} this.size = self.size;
this.text_color = self.text_color;
this this
} }
} }

View file

@ -1,7 +1,7 @@
use std::{ use std::{
any::TypeId, any::TypeId,
collections::{HashMap, VecDeque}, collections::{HashMap, VecDeque},
sync::Arc, rc::Rc,
time::Duration, time::Duration,
}; };
@ -19,13 +19,26 @@ use crate::{
h_flex, v_flex, ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt, h_flex, v_flex, ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt,
}; };
#[derive(Debug, Clone, Copy, Default)]
pub enum NotificationType { pub enum NotificationType {
#[default]
Info, Info,
Success, Success,
Warning, Warning,
Error, Error,
} }
impl NotificationType {
fn icon(&self, cx: &App) -> Icon {
match self {
Self::Info => Icon::new(IconName::Info).text_color(cx.theme().info),
Self::Success => Icon::new(IconName::CircleCheck).text_color(cx.theme().success),
Self::Warning => Icon::new(IconName::TriangleAlert).text_color(cx.theme().warning),
Self::Error => Icon::new(IconName::CircleX).text_color(cx.theme().danger),
}
}
}
#[derive(Debug, PartialEq, Clone, Hash, Eq)] #[derive(Debug, PartialEq, Clone, Hash, Eq)]
pub(crate) enum NotificationId { pub(crate) enum NotificationId {
Id(TypeId), Id(TypeId),
@ -51,12 +64,13 @@ pub struct Notification {
/// ///
/// None means the notification will be added to the end of the list. /// None means the notification will be added to the end of the list.
id: NotificationId, id: NotificationId,
type_: NotificationType, type_: Option<NotificationType>,
title: Option<SharedString>, title: Option<SharedString>,
message: SharedString, message: SharedString,
icon: Option<Icon>, icon: Option<Icon>,
autohide: bool, autohide: bool,
on_click: Option<Arc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>, action_builder: Option<Rc<dyn Fn(&mut Window, &mut Context<Self>) -> Button>>,
on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
closing: bool, closing: bool,
} }
@ -91,6 +105,7 @@ impl From<(NotificationType, SharedString)> for Notification {
} }
struct DefaultIdType; struct DefaultIdType;
impl Notification { impl Notification {
/// Create a new notification with the given content. /// Create a new notification with the given content.
/// ///
@ -103,9 +118,10 @@ impl Notification {
id: id.into(), id: id.into(),
title: None, title: None,
message: message.into(), message: message.into(),
type_: NotificationType::Info, type_: None,
icon: None, icon: None,
autohide: true, autohide: true,
action_builder: None,
on_click: None, on_click: None,
closing: false, closing: false,
} }
@ -162,7 +178,7 @@ impl Notification {
/// Set the type of the notification, default is NotificationType::Info. /// Set the type of the notification, default is NotificationType::Info.
pub fn with_type(mut self, type_: NotificationType) -> Self { pub fn with_type(mut self, type_: NotificationType) -> Self {
self.type_ = type_; self.type_ = Some(type_);
self self
} }
@ -177,11 +193,21 @@ impl Notification {
mut self, mut self,
on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
) -> Self { ) -> Self {
self.on_click = Some(Arc::new(on_click)); self.on_click = Some(Rc::new(on_click));
self self
} }
fn dismiss(&mut self, _: &ClickEvent, _: &mut Window, cx: &mut Context<Self>) { /// Set the action button of the notification.
pub fn action<F>(mut self, action: F) -> Self
where
F: Fn(&mut Window, &mut Context<Self>) -> Button + 'static,
{
self.action_builder = Some(Rc::new(action));
self
}
/// Dismiss the notification.
pub fn dismiss(&mut self, _: &mut Window, cx: &mut Context<Self>) {
self.closing = true; self.closing = true;
cx.notify(); cx.notify();
@ -203,25 +229,15 @@ impl Notification {
impl EventEmitter<DismissEvent> for Notification {} impl EventEmitter<DismissEvent> for Notification {}
impl FluentBuilder for Notification {} impl FluentBuilder for Notification {}
impl Render for Notification { impl Render for Notification {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let closing = self.closing; let closing = self.closing;
let icon = match self.icon.clone() { let icon = match self.type_ {
Some(icon) => icon, None => self.icon.clone(),
None => match self.type_ { Some(type_) => Some(type_.icon(cx)),
NotificationType::Info => Icon::new(IconName::Info).text_color(crate::blue_500()),
NotificationType::Success => {
Icon::new(IconName::CircleCheck).text_color(crate::green_500())
}
NotificationType::Warning => {
Icon::new(IconName::TriangleAlert).text_color(crate::yellow_500())
}
NotificationType::Error => {
Icon::new(IconName::CircleX).text_color(crate::red_500())
}
},
}; };
let has_icon = icon.is_some();
div() h_flex()
.id("notification") .id("notification")
.group("") .group("")
.occlude() .occlude()
@ -235,20 +251,25 @@ impl Render for Notification {
.py_2() .py_2()
.px_4() .px_4()
.gap_3() .gap_3()
.child(div().absolute().top_3().left_4().child(icon)) .when_some(icon, |this, icon| {
this.child(div().absolute().top_3().left_4().child(icon))
})
.child( .child(
v_flex() v_flex()
.pl_6() .flex_1()
.gap_1() .when(has_icon, |this| this.pl_6())
.when_some(self.title.clone(), |this, title| { .when_some(self.title.clone(), |this, title| {
this.child(div().text_sm().font_semibold().child(title)) this.child(div().text_sm().font_semibold().child(title))
}) })
.overflow_hidden() .overflow_hidden()
.child(div().text_sm().child(self.message.clone())), .child(div().text_sm().child(self.message.clone())),
) )
.when_some(self.action_builder.clone(), |this, action_builder| {
this.child(action_builder(window, cx).small().outline().mr_1())
})
.when_some(self.on_click.clone(), |this, on_click| { .when_some(self.on_click.clone(), |this, on_click| {
this.on_click(cx.listener(move |view, event, window, cx| { this.on_click(cx.listener(move |view, event, window, cx| {
view.dismiss(event, window, cx); view.dismiss(window, cx);
on_click(event, window, cx); on_click(event, window, cx);
})) }))
}) })
@ -265,7 +286,9 @@ impl Render for Notification {
.icon(IconName::Close) .icon(IconName::Close)
.ghost() .ghost()
.xsmall() .xsmall()
.on_click(cx.listener(Self::dismiss)), .on_click(
cx.listener(|this, _, window, cx| this.dismiss(window, cx)),
),
), ),
) )
}) })
@ -332,9 +355,9 @@ impl NotificationList {
cx.spawn_in(window, async move |_, cx| { cx.spawn_in(window, async move |_, cx| {
Timer::after(Duration::from_secs(5)).await; Timer::after(Duration::from_secs(5)).await;
if let Err(err) = notification.update_in(cx, |note, window, cx| { if let Err(err) =
note.dismiss(&ClickEvent::default(), window, cx) notification.update_in(cx, |note, window, cx| note.dismiss(window, cx))
}) { {
println!("failed to auto hide notification: {:?}", err); println!("failed to auto hide notification: {:?}", err);
} }
}) })