use std::sync::Arc;
use super::{
Button, ButtonPart, ButtonSize, ButtonVariant,
alert::close_style,
icon::Icon,
icons, names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{IconChoice, fading, glyph, pressable, shown_icon},
theme::{Themed, current_breakpoint, current_theme},
};
use crate::{
app::{
events::MouseEvent,
theme::{BorderSize, IconSize, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
},
components::{Column, Row},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{
CursorIcon, Element, EventHandler, FocusGroup, IntoMouseEventHandler, border::Border, dimension::Dimension,
outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotificationPart {
Root,
Unread,
Media,
Icon,
Content,
Text,
Header,
Title,
Time,
Description,
Body,
Actions,
Action,
Close,
}
names!(NotificationPart {
Root => "root",
Unread => "unread",
Media => "media",
Icon => "icon",
Content => "content",
Text => "text",
Header => "header",
Title => "title",
Time => "time",
Description => "description",
Body => "body",
Actions => "actions",
Action => "action",
Close => "close",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum NotificationVariant {
#[default]
Card,
Row,
}
names!(NotificationVariant {
Card => "card",
Row => "row",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotificationState {
Unread,
Pressable,
}
names!(NotificationState {
Unread => "unread",
Pressable => "pressable",
});
pub type NotificationRenderer = Arc<dyn Fn(NotificationView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
enum Act {
Button(Arc<str>, Handler),
Element(Element),
}
pub struct Notification {
title: Arc<str>,
description: Option<Arc<str>>,
media: Option<Element>,
icon: Option<IconChoice>,
time: Option<Arc<str>>,
unread: bool,
actions: Vec<Act>,
body: Vec<Element>,
variant: Name,
label: Option<Arc<str>>,
close_label: Arc<str>,
unread_label: Arc<str>,
on_click: Vec<EventHandler<MouseEvent>>,
on_close: Vec<Handler>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Notification {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
description: None,
media: None,
icon: None,
time: None,
unread: false,
actions: Vec::new(),
body: Vec::new(),
variant: NotificationVariant::Card.into(),
label: None,
close_label: super::current_locale().common.dismiss.clone(),
unread_label: super::current_locale().navigation.unread.clone(),
on_click: Vec::new(),
on_close: Vec::new(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn media(mut self, media: impl Into<Element>) -> Self {
self.media = Some(media.into());
self
}
pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn time(mut self, time: &str) -> Self {
self.time = Some(Arc::from(time));
self
}
pub fn unread(mut self, unread: bool) -> Self {
self.unread = unread;
self
}
pub fn button(mut self, label: &str, on_click: impl Fn() + Send + Sync + 'static) -> Self {
self.actions.push(Act::Button(Arc::from(label), Arc::new(on_click)));
self
}
pub fn action(mut self, action: impl Into<Element>) -> Self {
self.actions.push(Act::Element(action.into()));
self
}
pub fn child(mut self, child: impl Into<Element>) -> Self {
self.body.push(child.into());
self
}
pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Element>>) -> Self {
self.body.extend(children.into_iter().map(Into::into));
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn close_label(mut self, label: &str) -> Self {
self.close_label = Arc::from(label);
self
}
pub fn unread_label(mut self, label: &str) -> Self {
self.unread_label = Arc::from(label);
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_handler());
self
}
pub fn on_close(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_close.push(Arc::new(handler));
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub(crate) fn is_unread(&self) -> bool {
self.unread
}
pub fn build(self, theme: &Theme) -> Element {
let pressable = !self.on_click.is_empty();
let case = Case {
variant: Some(self.variant),
size: None,
density: None,
breakpoint: current_breakpoint(),
states: self.states.clone(),
}
.state(NotificationState::Unread, self.unread)
.state(NotificationState::Pressable, pressable);
let view = NotificationView {
title: self.title,
description: self.description,
icon: match self.media {
Some(_) => None,
None => shown_icon(self.icon, icons::BELL),
},
time: self.time,
unread: self.unread,
row: self.variant == Name::from(NotificationVariant::Row),
variant: self.variant,
label: self.label,
close_label: self.close_label,
unread_label: self.unread_label,
close_button: !self.on_close.is_empty(),
recipe: theme
.resolve::<Notification>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
media: self.media,
actions: self.actions,
body: self.body,
forced: self.forced,
on_click: self.on_click,
on_close: self.on_close,
id: self.id,
key: self.key,
};
match theme.renderer::<Notification>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<Notification> for Element {
fn from(notification: Notification) -> Self {
notification.build(¤t_theme())
}
}
pub struct NotificationView {
pub title: Arc<str>,
pub description: Option<Arc<str>>,
pub icon: Option<Name>,
pub time: Option<Arc<str>>,
pub unread: bool,
pub row: bool,
pub variant: Name,
pub label: Option<Arc<str>>,
pub close_label: Arc<str>,
pub unread_label: Arc<str>,
pub close_button: bool,
pub recipe: ResolvedRecipe,
media: Option<Element>,
actions: Vec<Act>,
body: Vec<Element>,
forced: Option<Interaction>,
on_click: Vec<EventHandler<MouseEvent>>,
on_close: Vec<Handler>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl NotificationView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn pressable(&self) -> bool {
!self.on_click.is_empty()
}
fn wrapping(&self, part: NotificationPart, content: &str) -> Column {
let part = self.part(part);
let fill = Dimension::Pct(100.0);
Column::new()
.width(fill)
.min_width(Dimension::Px(0.0))
.part(&part)
.child(part.text(content).width(fill))
}
pub fn unread_dot(&self) -> Option<Element> {
if !self.unread && !self.row {
return None;
}
let part = self.part(NotificationPart::Unread);
let mut dot = Row::new().flex_shrink(0.0).part(&part);
if self.unread {
dot = dot
.describe("a11y_role", "status")
.describe("a11y_name", self.unread_label.clone());
}
Some(dot.into())
}
pub fn media(&mut self) -> Option<Element> {
let shown: Element = match self.media.take() {
Some(media) => media,
None => glyph(&self.part(NotificationPart::Icon), self.icon?, false),
};
Some(
Row::new()
.flex_shrink(0.0)
.justify(Justify::Center)
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(NotificationPart::Media))
.child(shown)
.into(),
)
}
pub fn time(&self) -> Option<Element> {
let time = self.time.as_ref()?;
let part = self.part(NotificationPart::Time);
Some(
Row::new()
.flex_shrink(0.0)
.part(&part)
.child(part.text(time).nowrap())
.into(),
)
}
pub fn text(&self) -> Column {
let mut header = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&self.part(NotificationPart::Header))
.child(self.wrapping(NotificationPart::Title, &self.title).flex(1.0));
if !self.row {
header = header.with_children(self.time()).with_children(self.unread_dot());
}
let mut text = Column::new()
.width(Dimension::Pct(100.0))
.part(&self.part(NotificationPart::Text))
.child(header);
if let Some(description) = &self.description {
text = text.child(self.wrapping(NotificationPart::Description, description));
}
text
}
fn button(&self, label: &str, variant: ButtonVariant, id: Option<String>, handler: Handler) -> Button {
let button = Button::new(label)
.variant(variant)
.size(ButtonSize::Sm)
.rules(&self.recipe.rules_for(NotificationPart::Action, ButtonPart::Root))
.on_click(move |_| handler());
match id {
Some(id) => button.id(id),
None => button,
}
}
fn closer(&self) -> Handler {
let handlers = self.on_close.clone();
Arc::new(move || {
for handler in &handlers {
handler();
}
})
}
pub fn actions(&mut self) -> Option<Row> {
let dismiss = self.close_button && !self.row;
if self.actions.is_empty() && !dismiss {
return None;
}
let mut row = Row::new()
.width(Dimension::Pct(100.0))
.wrap()
.align_items(Alignment::Center)
.part(&self.part(NotificationPart::Actions));
let mut buttons = 0;
for (index, act) in std::mem::take(&mut self.actions).into_iter().enumerate() {
row = match act {
Act::Button(label, handler) => {
let variant = if buttons == 0 {
ButtonVariant::Primary
} else {
ButtonVariant::Ghost
};
buttons += 1;
let id = self.id.as_ref().map(|id| format!("{id}-action-{index}"));
row.child(self.button(&label, variant, id, handler))
}
Act::Element(element) => row.child(element),
};
}
if dismiss {
let id = self.id.as_ref().map(|id| format!("{id}-close"));
row = row.child(self.button(&self.close_label, ButtonVariant::Ghost, id, self.closer()));
}
Some(self.own_presses(row))
}
pub fn close(&self) -> Element {
let part = self.part(NotificationPart::Close).forced(match self.pressable() {
true => None,
false => self.forced,
});
let side = part.rest().width.unwrap_or(Length::Icon(IconSize::Md));
let close = self.closer();
let mut control = pressable(&part, false)
.flex_shrink(0.0)
.describe("a11y_role", "button")
.describe("a11y_name", self.close_label.clone())
.child(Icon::new(icons::CLOSE).size(side).build(part.theme()))
.on_click(move |event: MouseEvent| {
event.stop_propagation();
close()
});
if let Some(id) = &self.id {
control = control.id(format!("{id}-close"));
}
Row::new()
.flex_shrink(0.0)
.focus_group(FocusGroup::none())
.child(control)
.into()
}
fn own_presses(&self, row: Row) -> Row {
if self.pressable() {
row.on_click(|event: MouseEvent| event.stop_propagation())
} else {
row
}
}
pub fn content(&mut self) -> Column {
let mut content = Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.part(&self.part(NotificationPart::Content))
.child(self.text());
if !self.body.is_empty() {
content = content.child(
Column::new()
.width(Dimension::Pct(100.0))
.part(&self.part(NotificationPart::Body))
.with_children(std::mem::take(&mut self.body)),
);
}
content.with_children(self.actions())
}
pub fn root(&self, children: Vec<Element>) -> Element {
let name = self.label.clone().unwrap_or_else(|| self.title.clone());
let align = if self.row { Alignment::Center } else { Alignment::Start };
let description = self.description.clone();
let mut root: Element = if self.pressable() {
let part = self.part(NotificationPart::Root).forced(self.forced);
let mut root = pressable(&part, false)
.justify(Justify::Start)
.align_items(align)
.interaction_group(true)
.stops_inside(true)
.focus_label(name.clone())
.describe("a11y_role", "button")
.describe("a11y_name", name);
if let Some(description) = description {
root = root.describe("a11y_description", description);
}
for handler in &self.on_click {
root = root.on_click(handler.clone());
}
root.with_children(children).into()
} else {
let mut root = Row::new()
.align_items(align)
.part(&self.part(NotificationPart::Root))
.describe("a11y_role", "article")
.describe("a11y_name", name);
if let Some(description) = description {
root = root.describe("a11y_description", description);
}
root.with_children(children).into()
};
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root
}
pub fn render(mut self) -> Element {
let mut children: Vec<Element> = Vec::new();
if self.row {
children.extend(self.unread_dot());
}
children.extend(self.media());
children.push(self.content().into());
if self.row {
children.extend(self.time());
if self.close_button {
children.push(self.close());
}
}
self.root(children)
}
}
impl crate::ui::Styled for Notification {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for Notification {
const NAME: &'static str = "notification";
type Renderer = NotificationRenderer;
fn parts() -> crate::ui::Declared {
NotificationPart::declared()
}
fn states() -> crate::ui::Declared {
NotificationState::declared()
}
fn recipe() -> Recipe {
use NotificationPart as P;
use NotificationState::{Pressable, Unread};
use NotificationVariant::Row as Listed;
use PaletteColor::{
Foreground, Highlight, Info, MutedForeground, Popover, PopoverForeground, Ring, StateHover, StatePressed,
};
let listed = || Selector::new().variant(Listed);
let recipe = Recipe::new()
.base(P::Root, |s| fading(s.foreground(PopoverForeground).gap(12.0)))
.variant(NotificationVariant::Card, P::Root, |s| {
s.width(340.0)
.max_width(Length::Fill)
.background(Popover)
.border(Border::inside(BorderSize::Sm, PaletteColor::Border))
.radius(RadiusSize::Lg)
.shadow(ShadowStyle::Md)
.padding_x(16.0)
.padding_y(16.0)
})
.state(Pressable, P::Root, |s| s.cursor(CursorIcon::Pointer))
.when(Selector::new().state(Pressable).hovered(), P::Root, |s| s.veil(StateHover))
.when(Selector::new().state(Pressable).pressed(), P::Root, |s| s.veil(StatePressed))
.focus_visible(P::Root, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
.base(P::Unread, |s| s.square(7.0).radius(RadiusSize::Full))
.state(Unread, P::Unread, |s| s.background(Info))
.base(P::Icon, |s| s.square(Length::Icon(IconSize::Md)).foreground(Foreground))
.base(P::Content, |s| s.gap(10.0))
.base(P::Text, |s| s.gap(4.0))
.base(P::Header, |s| s.gap(8.0))
.base(P::Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(14.0)
.line_height(1.2)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(P::Time, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(P::Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.line_height(1.4)
.foreground(MutedForeground)
})
.base(P::Body, |s| s.gap(8.0))
.base(P::Actions, |s| s.gap(8.0))
.base(P::Action, |s| s.height(28.0).padding_x(10.0))
.variant(Listed, P::Root, |s| {
s.width(Length::Fill)
.min_height(56.0)
.padding_start(12.0)
.padding_end(16.0)
.padding_y(12.0)
.gap(10.0)
})
.by_density(listed(), P::Root, |s, step| {
s.min_height(56.0 + step).padding_y(12.0 + step / 2.0)
})
.when(listed().state(Pressable).hovered(), P::Root, |s| s.background(Highlight))
.variant(Listed, P::Text, |s| s.gap(1.0))
.variant(Listed, P::Title, |s| s.font_size(13.0).weight(FontWeight::Normal))
.when(listed().state(Unread), P::Title, |s| s.weight(FontWeight::Medium))
.variant(Listed, P::Description, |s| s.font_size(12.0).line_height(1.2));
close_style(recipe, P::Close)
}
}