notification: Add support for rendering custom content (#938)

## Break Change
You no longer need to pass a message when creating a new notification.
Instead, use the `message` method.

```diff 
- Notification::new("There was a problem with your request.");
+ Notification::new().message("There was a problem with your request.");
```

<img width="1023" alt="image"
src="https://github.com/user-attachments/assets/4b93f2bb-e130-45d6-974f-8b14efac58a4"
/>
This commit is contained in:
Floyd Wang 2025-06-10 12:06:02 +08:00 committed by GitHub
parent 0aceb02302
commit c333fd7106
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 80 additions and 22 deletions

View file

@ -550,7 +550,8 @@ impl StoryContainer {
cx: &mut Context<Self>, cx: &mut Context<Self>,
) { ) {
struct Info; struct Info;
let note = Notification::new(format!("You have clicked panel info on: {}", self.name)) let note = Notification::new()
.message(format!("You have clicked panel info on: {}", self.name))
.id::<Info>(); .id::<Info>();
window.push_notification(note, cx); window.push_notification(note, cx);
} }
@ -567,8 +568,9 @@ impl StoryContainer {
} }
struct Search; struct Search;
let note = let note = Notification::new()
Notification::new(format!("You have toggled search on: {}", self.name)).id::<Search>(); .message(format!("You have toggled search on: {}", self.name))
.id::<Search>();
window.push_notification(note, cx); window.push_notification(note, cx);
} }
} }

View file

@ -6,11 +6,19 @@ use gpui::{
use gpui_component::{ use gpui_component::{
button::{Button, ButtonVariants as _}, button::{Button, ButtonVariants as _},
notification::{Notification, NotificationType}, notification::{Notification, NotificationType},
text::TextView,
ContextModal as _, ContextModal as _,
}; };
use crate::section; use crate::section;
const NOTIFICATION_MARKDOWN: &str = r#"
This is a custom notification.
- List item 1
- List item 2
- [Click here](https://github.com/longbridge/gpui-component)
"#;
pub struct NotificationStory { pub struct NotificationStory {
focus_handle: FocusHandle, focus_handle: FocusHandle,
} }
@ -130,9 +138,10 @@ impl Render for NotificationStory {
struct TestNotification; struct TestNotification;
window.push_notification( window.push_notification(
Notification::new("There was a problem with your request.") Notification::new()
.id::<TestNotification>() .id::<TestNotification>()
.title("Uh oh! Something went wrong.") .title("Uh oh! Something went wrong.")
.message("There was a problem with your request.")
.autohide(false) .autohide(false)
.action(|_, cx| { .action(|_, cx| {
Button::new("try-again").label("Try again").on_click( Button::new("try-again").label("Try again").on_click(
@ -151,5 +160,23 @@ impl Render for NotificationStory {
})), })),
), ),
) )
.child(
section("Custom Notification").child(
Button::new("show-notify-custom")
.label("Show Custom Notification")
.on_click(cx.listener(|_, _, window, cx| {
window.push_notification(
Notification::new().content(|_, _| {
TextView::markdown(
"notification-markdown",
NOTIFICATION_MARKDOWN,
)
.into_any_element()
}),
cx,
)
})),
),
)
} }
} }

View file

@ -6,10 +6,10 @@ use std::{
}; };
use gpui::{ use gpui::{
div, prelude::FluentBuilder, px, Animation, AnimationExt, App, AppContext, ClickEvent, Context, div, prelude::FluentBuilder, px, Animation, AnimationExt, AnyElement, App, AppContext,
DismissEvent, ElementId, Entity, EventEmitter, InteractiveElement as _, IntoElement, ClickEvent, Context, DismissEvent, ElementId, Entity, EventEmitter, InteractiveElement as _,
ParentElement as _, Render, SharedString, StatefulInteractiveElement, Styled, Subscription, IntoElement, ParentElement as _, Render, SharedString, StatefulInteractiveElement, Styled,
Window, Subscription, Window,
}; };
use smol::Timer; use smol::Timer;
@ -66,41 +66,42 @@ pub struct Notification {
id: NotificationId, id: NotificationId,
type_: Option<NotificationType>, type_: Option<NotificationType>,
title: Option<SharedString>, title: Option<SharedString>,
message: SharedString, message: Option<SharedString>,
icon: Option<Icon>, icon: Option<Icon>,
autohide: bool, autohide: bool,
action_builder: Option<Rc<dyn Fn(&mut Window, &mut Context<Self>) -> Button>>, action_builder: Option<Rc<dyn Fn(&mut Window, &mut Context<Self>) -> Button>>,
content_builder: Option<Rc<dyn Fn(&mut Window, &mut Context<Self>) -> AnyElement>>,
on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>, on_click: Option<Rc<dyn Fn(&ClickEvent, &mut Window, &mut App)>>,
closing: bool, closing: bool,
} }
impl From<String> for Notification { impl From<String> for Notification {
fn from(s: String) -> Self { fn from(s: String) -> Self {
Self::new(s) Self::new().message(s)
} }
} }
impl From<SharedString> for Notification { impl From<SharedString> for Notification {
fn from(s: SharedString) -> Self { fn from(s: SharedString) -> Self {
Self::new(s) Self::new().message(s)
} }
} }
impl From<&'static str> for Notification { impl From<&'static str> for Notification {
fn from(s: &'static str) -> Self { fn from(s: &'static str) -> Self {
Self::new(s) Self::new().message(s)
} }
} }
impl From<(NotificationType, &'static str)> for Notification { impl From<(NotificationType, &'static str)> for Notification {
fn from((type_, content): (NotificationType, &'static str)) -> Self { fn from((type_, content): (NotificationType, &'static str)) -> Self {
Self::new(content).with_type(type_) Self::new().message(content).with_type(type_)
} }
} }
impl From<(NotificationType, SharedString)> for Notification { impl From<(NotificationType, SharedString)> for Notification {
fn from((type_, content): (NotificationType, SharedString)) -> Self { fn from((type_, content): (NotificationType, SharedString)) -> Self {
Self::new(content).with_type(type_) Self::new().message(content).with_type(type_)
} }
} }
@ -110,37 +111,51 @@ impl Notification {
/// Create a new notification with the given content. /// Create a new notification with the given content.
/// ///
/// default width is 320px. /// default width is 320px.
pub fn new(message: impl Into<SharedString>) -> Self { pub fn new() -> Self {
let id: SharedString = uuid::Uuid::new_v4().to_string().into(); let id: SharedString = uuid::Uuid::new_v4().to_string().into();
let id = (TypeId::of::<DefaultIdType>(), id.into()); let id = (TypeId::of::<DefaultIdType>(), id.into());
Self { Self {
id: id.into(), id: id.into(),
title: None, title: None,
message: message.into(), message: None,
type_: None, type_: None,
icon: None, icon: None,
autohide: true, autohide: true,
action_builder: None, action_builder: None,
content_builder: None,
on_click: None, on_click: None,
closing: false, closing: false,
} }
} }
pub fn message(mut self, message: impl Into<SharedString>) -> Self {
self.message = Some(message.into());
self
}
pub fn info(message: impl Into<SharedString>) -> Self { pub fn info(message: impl Into<SharedString>) -> Self {
Self::new(message).with_type(NotificationType::Info) Self::new()
.message(message)
.with_type(NotificationType::Info)
} }
pub fn success(message: impl Into<SharedString>) -> Self { pub fn success(message: impl Into<SharedString>) -> Self {
Self::new(message).with_type(NotificationType::Success) Self::new()
.message(message)
.with_type(NotificationType::Success)
} }
pub fn warning(message: impl Into<SharedString>) -> Self { pub fn warning(message: impl Into<SharedString>) -> Self {
Self::new(message).with_type(NotificationType::Warning) Self::new()
.message(message)
.with_type(NotificationType::Warning)
} }
pub fn error(message: impl Into<SharedString>) -> Self { pub fn error(message: impl Into<SharedString>) -> Self {
Self::new(message).with_type(NotificationType::Error) Self::new()
.message(message)
.with_type(NotificationType::Error)
} }
/// Set the type for unique identification of the notification. /// Set the type for unique identification of the notification.
@ -225,6 +240,15 @@ impl Notification {
}) })
.detach() .detach()
} }
/// Set the content of the notification.
pub fn content(
mut self,
content: impl Fn(&mut Window, &mut Context<Self>) -> AnyElement + 'static,
) -> Self {
self.content_builder = Some(Rc::new(content));
self
}
} }
impl EventEmitter<DismissEvent> for Notification {} impl EventEmitter<DismissEvent> for Notification {}
impl FluentBuilder for Notification {} impl FluentBuilder for Notification {}
@ -257,12 +281,17 @@ impl Render for Notification {
.child( .child(
v_flex() v_flex()
.flex_1() .flex_1()
.overflow_hidden()
.when(has_icon, |this| this.pl_6()) .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() .when_some(self.message.clone(), |this, message| {
.child(div().text_sm().child(self.message.clone())), this.child(div().text_sm().child(message))
})
.when_some(self.content_builder.clone(), |this, child_builder| {
this.child(child_builder(window, cx))
}),
) )
.when_some(self.action_builder.clone(), |this, action_builder| { .when_some(self.action_builder.clone(), |this, action_builder| {
this.child(action_builder(window, cx).small().outline().mr_1()) this.child(action_builder(window, cx).small().outline().mr_1())