use std::sync::Arc;
use super::{
Link, LinkPart, Notification, NotificationVariant, icons, names,
part_style::{Length, PartAnimation, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{FADE_IN, FADE_OUT, fading, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
ctx::{CollisionStrategy, Placement},
theme::{
BorderSize, MotionDuration, MotionEasing, PaletteColor, RadiusSize, ShadowStyle, SpacingSize, Theme,
TypographyStyle,
},
},
components::{Column, Popup, Row, ScrollVertical},
core::{ElementRef, Signal},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{
CursorIcon, Element, FocusGroup, Node, NodeUpdate, SpacingValue, border::Border, dimension::Dimension,
outline::Outline,
},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotificationCenterPart {
Panel,
Header,
Title,
Actions,
Action,
ActionLabel,
List,
Item,
Empty,
EmptyIcon,
EmptyText,
Footer,
}
names!(NotificationCenterPart {
Panel => "panel",
Header => "header",
Title => "title",
Actions => "actions",
Action => "action",
ActionLabel => "action-label",
List => "list",
Item => "item",
Empty => "empty",
EmptyIcon => "empty-icon",
EmptyText => "empty-text",
Footer => "footer",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotificationCenterState {
Footer,
Empty,
}
names!(NotificationCenterState {
Footer => "footer",
Empty => "empty",
});
pub type NotificationCenterRenderer = Arc<dyn Fn(NotificationCenterView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
pub struct NotificationCenter {
open: Signal<bool>,
anchor: ElementRef,
trigger: Option<Element>,
title: Arc<str>,
items: Vec<Notification>,
empty: Option<Element>,
empty_text: Arc<str>,
mark_all_read_label: Arc<str>,
clear_label: Arc<str>,
view_all_label: Arc<str>,
on_mark_all_read: Vec<Handler>,
on_clear: Vec<Handler>,
on_view_all: Vec<Handler>,
on_dismiss: Vec<Handler>,
placement: Placement,
offset: SpacingValue,
collision: CollisionStrategy,
width: Option<Length>,
max_height: Option<Length>,
inline: bool,
dismiss_on_escape: bool,
dismiss_on_outside_press: bool,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl NotificationCenter {
pub fn new(open: Signal<bool>, anchor: impl Into<ElementRef>) -> Self {
Self {
open,
anchor: anchor.into(),
trigger: None,
title: super::current_locale().navigation.notifications.clone(),
items: Vec::new(),
empty: None,
empty_text: super::current_locale().navigation.no_notifications.clone(),
mark_all_read_label: super::current_locale().navigation.mark_all_read.clone(),
clear_label: super::current_locale().navigation.clear_all.clone(),
view_all_label: super::current_locale().navigation.view_all.clone(),
on_mark_all_read: Vec::new(),
on_clear: Vec::new(),
on_view_all: Vec::new(),
on_dismiss: Vec::new(),
placement: Placement::BottomEnd,
offset: SpacingSize::Xs.into(),
collision: CollisionStrategy::FlipThenClamp,
width: None,
max_height: None,
inline: false,
dismiss_on_escape: true,
dismiss_on_outside_press: true,
label: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn trigger(mut self, trigger: impl Into<Element>) -> Self {
self.trigger = Some(trigger.into());
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Arc::from(title);
self
}
pub fn item(mut self, item: Notification) -> Self {
self.items.push(item);
self
}
pub fn items(mut self, items: impl IntoIterator<Item = Notification>) -> Self {
self.items.extend(items);
self
}
pub fn empty(mut self, empty: impl Into<Element>) -> Self {
self.empty = Some(empty.into());
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.empty_text = Arc::from(text);
self
}
pub fn mark_all_read_label(mut self, label: &str) -> Self {
self.mark_all_read_label = Arc::from(label);
self
}
pub fn clear_label(mut self, label: &str) -> Self {
self.clear_label = Arc::from(label);
self
}
pub fn view_all_label(mut self, label: &str) -> Self {
self.view_all_label = Arc::from(label);
self
}
pub fn on_mark_all_read(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_mark_all_read.push(Arc::new(handler));
self
}
pub fn on_clear(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_clear.push(Arc::new(handler));
self
}
pub fn on_view_all(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_view_all.push(Arc::new(handler));
self
}
pub fn on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_dismiss.push(Arc::new(handler));
self
}
pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
self.dismiss_on_escape = dismiss;
self
}
pub fn dismiss_on_outside_press(mut self, dismiss: bool) -> Self {
self.dismiss_on_outside_press = dismiss;
self
}
pub fn placement(mut self, placement: Placement) -> Self {
self.placement = placement;
self
}
pub fn offset(mut self, offset: impl Into<SpacingValue>) -> Self {
self.offset = offset.into();
self
}
pub fn collision(mut self, collision: CollisionStrategy) -> Self {
self.collision = collision;
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = Some(width.into());
self
}
pub fn max_height(mut self, height: impl Into<Length>) -> Self {
self.max_height = Some(height.into());
self
}
pub fn inline(mut self, inline: bool) -> Self {
self.inline = inline;
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
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 fn build(self, theme: &Theme) -> Element {
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(NotificationCenterState::Footer, !self.on_view_all.is_empty())
.state(NotificationCenterState::Empty, self.items.is_empty());
let mut rules = Recipe::new();
if let Some(width) = self.width {
rules = rules.base(NotificationCenterPart::Panel, |s| s.width(width));
}
if let Some(height) = self.max_height {
rules = rules.base(NotificationCenterPart::List, |s| s.max_height(height));
}
let rules = rules.extend(&self.rules);
let all = |handlers: Vec<Handler>| -> Option<Handler> {
(!handlers.is_empty()).then(|| {
Arc::new(move || {
for handler in &handlers {
handler();
}
}) as Handler
})
};
let view_all = all(self.on_view_all).map(|told| {
let open = self.open.clone();
let inline = self.inline;
Arc::new(move || {
if !inline {
open.set(false);
}
told()
}) as Handler
});
let view = NotificationCenterView {
title: self.title,
unread: self.items.iter().filter(|item| item.is_unread()).count(),
items: self.items,
empty: self.empty,
empty_text: self.empty_text,
mark_all_read_label: self.mark_all_read_label,
clear_label: self.clear_label,
view_all_label: self.view_all_label,
recipe: theme
.resolve::<NotificationCenter>(&case, Some(&rules))
.owned_by(self.id.as_ref()),
mark_all_read: all(self.on_mark_all_read),
clear: all(self.on_clear),
view_all,
label: self.label,
forced: self.forced,
id: self.id,
key: self.key,
};
let panel = match theme.renderer::<NotificationCenter>() {
Some(renderer) => renderer(view),
None => view.render(),
};
if self.inline {
return panel;
}
let offset = self.offset.resolve(&theme.spacing(), 0.0);
let (x, y) = match self.placement {
Placement::LeftStart
| Placement::Left
| Placement::LeftEnd
| Placement::RightStart
| Placement::Right
| Placement::RightEnd => (offset, 0.0),
_ => (0.0, offset),
};
let mut popup = Popup::new(self.anchor.clone(), panel)
.open(self.open.clone())
.placement(self.placement)
.offset(x, y)
.collision(self.collision)
.dismiss_on_escape(self.dismiss_on_escape)
.dismiss_on_outside_click(self.dismiss_on_outside_press)
.takes_focus(true);
if !self.on_dismiss.is_empty() {
let handlers = self.on_dismiss;
popup = popup.on_dismiss(move || {
for handler in &handlers {
handler();
}
});
}
let Some(mut trigger) = self.trigger else {
return popup.into();
};
let node = &mut *trigger.node;
let (open, expanded) = (self.open.clone(), self.open.get());
NodeUpdate::ref_element(node, self.anchor);
let node = pressed(node);
NodeUpdate::on_click(node, move |_: crate::app::events::MouseEvent| {
open.update(|open| *open = !*open)
});
NodeUpdate::describe(node, Arc::from("a11y_haspopup"), Arc::from("dialog"));
NodeUpdate::describe(
node,
Arc::from("a11y_expanded"),
Arc::from(if expanded { "true" } else { "false" }),
);
Row::new().overflow_visible().child(trigger).child(popup).into()
}
}
fn pressed(node: &mut Node) -> &mut Node {
fn path(node: &Node, to: &mut Vec<usize>) -> bool {
if node.is_focusable() {
return true;
}
for (index, child) in node.children.iter().enumerate() {
to.push(index);
if path(child, to) {
return true;
}
to.pop();
}
false
}
let mut to = Vec::new();
if !path(node, &mut to) {
return node;
}
to.into_iter().fold(node, |node, index| &mut node.children[index])
}
impl From<NotificationCenter> for Element {
fn from(center: NotificationCenter) -> Self {
center.build(¤t_theme())
}
}
pub struct NotificationCenterView {
pub title: Arc<str>,
pub unread: usize,
pub items: Vec<Notification>,
pub empty: Option<Element>,
pub empty_text: Arc<str>,
pub mark_all_read_label: Arc<str>,
pub clear_label: Arc<str>,
pub view_all_label: Arc<str>,
pub recipe: ResolvedRecipe,
mark_all_read: Option<Handler>,
clear: Option<Handler>,
view_all: Option<Handler>,
label: Option<Arc<str>>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl NotificationCenterView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn action(&self, label: &str, name: &str, disabled: bool, handler: &Handler) -> Link {
let handler = handler.clone();
let link = Link::new(label)
.disabled(disabled)
.rules(&self.recipe.rules_for(NotificationCenterPart::Action, LinkPart::Root))
.rules(
&self
.recipe
.rules_for(NotificationCenterPart::ActionLabel, LinkPart::Label),
)
.on_click(move |_| handler());
match &self.id {
Some(id) => link.id(format!("{id}-{name}")),
None => link,
}
}
pub fn header(&self) -> Row {
let title = self.part(NotificationCenterPart::Title);
let mut header = Row::new()
.width(Dimension::Pct(100.0))
.flex_shrink(0.0)
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(NotificationCenterPart::Header))
.child(
Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.part(&title)
.child(super::shared::one_line(&title, &self.title)),
);
let mut actions = Row::new()
.flex_shrink(0.0)
.align_items(Alignment::Center)
.part(&self.part(NotificationCenterPart::Actions));
if let Some(handler) = &self.mark_all_read {
actions = actions.child(self.action(&self.mark_all_read_label, "mark-all-read", self.unread == 0, handler));
}
if let Some(handler) = &self.clear {
actions = actions.child(self.action(&self.clear_label, "clear", self.items.is_empty(), handler));
}
if self.mark_all_read.is_some() || self.clear.is_some() {
header = header.child(actions);
}
header
}
pub fn empty(&mut self) -> Element {
let held = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.justify(Justify::Center)
.part(&self.part(NotificationCenterPart::Empty))
.describe("a11y_role", "status");
match self.empty.take() {
Some(empty) => held.child(empty).into(),
None => {
let text = self.part(NotificationCenterPart::EmptyText);
held
.child(glyph(
&self.part(NotificationCenterPart::EmptyIcon),
Name::from(icons::INBOX),
false,
))
.child(
Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&text)
.child(text.text(&self.empty_text)),
)
.into()
}
}
}
pub fn list(&mut self) -> Element {
let items = std::mem::take(&mut self.items);
let mut rows = Column::new()
.width(Dimension::Pct(100.0))
.focus_group(FocusGroup::vertical().wrap(false).one_stop(true))
.describe("a11y_role", "list")
.describe("a11y_name", self.label.clone().unwrap_or_else(|| self.title.clone()));
let mut forced = self.forced;
let last = items.len().saturating_sub(1);
for (index, item) in items.into_iter().enumerate() {
let row = item
.variant(NotificationVariant::Row)
.force(forced.take())
.rules(&self.recipe.lend(NotificationCenterPart::Item))
.build(self.theme());
let mut held = Column::new().width(Dimension::Pct(100.0));
if index < last {
held = held.part(&self.part(NotificationCenterPart::Item).unnamed());
}
rows = rows.child(held.child(row));
}
ScrollVertical::new(rows)
.width(Dimension::Pct(100.0))
.flex_full(0.0, 1.0, None)
.part(&self.part(NotificationCenterPart::List))
.into()
}
pub fn footer(&self) -> Option<Element> {
let handler = self.view_all.clone()?;
let part = self.part(NotificationCenterPart::Footer);
let mut footer = pressable(&part, false)
.width(Dimension::Pct(100.0))
.flex_shrink(0.0)
.align_items(Alignment::Center)
.describe("a11y_role", "button")
.describe("a11y_name", self.view_all_label.clone())
.child(super::shared::one_line(&part, &self.view_all_label))
.on_click(move |_| handler());
if let Some(id) = &self.id {
footer = footer.id(format!("{id}-view-all"));
}
Some(footer.into())
}
pub fn panel(&self) -> Column {
let mut panel = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(NotificationCenterPart::Panel))
.describe("a11y_role", "dialog")
.describe("a11y_name", self.label.clone().unwrap_or_else(|| self.title.clone()));
if let Some(id) = &self.id {
panel = panel.id(id.clone());
}
if let Some(key) = &self.key {
panel = panel.key(key.clone());
}
panel
}
pub fn render(mut self) -> Element {
let panel = self.panel().child(self.header());
let panel = if self.items.is_empty() {
panel.child(self.empty())
} else {
panel.child(self.list())
};
panel.with_children(self.footer()).into()
}
}
impl crate::ui::Styled for NotificationCenter {
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 NotificationCenter {
const NAME: &'static str = "notification_center";
const ROOT: &'static str = "panel";
type Renderer = NotificationCenterRenderer;
fn parts() -> crate::ui::Declared {
NotificationCenterPart::declared()
}
fn states() -> crate::ui::Declared {
NotificationCenterState::declared()
}
fn recipe() -> Recipe {
use NotificationCenterPart as P;
use PaletteColor::{
Border as Edge, Foreground, Highlight, Info, MutedForeground, Popover, PopoverForeground, Ring,
};
let line = || Border::inside(BorderSize::Sm, Edge);
Recipe::new()
.base(P::Panel, |s| {
s.width(360.0)
.max_width(Length::Fill)
.radius(RadiusSize::Xl)
.background(Popover)
.foreground(PopoverForeground)
.border(line())
.shadow(ShadowStyle::Lg)
.enter(PartAnimation::new(FADE_IN, MotionDuration::Base, MotionEasing::Enter))
.exit(PartAnimation::new(FADE_OUT, MotionDuration::Fast, MotionEasing::Exit))
})
.base(P::Header, |s| s.height(48.0).padding_x(16.0).gap(12.0).underline(line()))
.base(P::Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(15.0)
.weight(FontWeight::SemiBold)
.foreground(Foreground)
})
.base(P::Actions, |s| s.gap(12.0))
.base(P::Action, |s| s.foreground(Info))
.base(P::ActionLabel, |s| s.font_size(13.0).weight(FontWeight::Medium))
.within(P::ActionLabel, |s| s.underline(Border::inside(1.0, Info)))
.base(P::List, |s| {
s.max_height(360.0).corners(0.0, 0.0, RadiusSize::Xl, RadiusSize::Xl)
})
.state(NotificationCenterState::Footer, P::List, |s| s.radius(0.0).underline(line()))
.base(P::Item, |s| s.underline(line()))
.base(P::Empty, |s| s.padding_x(16.0).padding_y(32.0).gap(8.0))
.state(NotificationCenterState::Footer, P::Empty, |s| s.underline(line()))
.base(P::EmptyIcon, |s| s.square(24.0).foreground(MutedForeground))
.base(P::EmptyText, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.base(P::Footer, |s| {
fading(
s.height(40.0)
.padding_x(16.0)
.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
.corners(0.0, 0.0, RadiusSize::Xl, RadiusSize::Xl)
.cursor(CursorIcon::Pointer),
)
})
.hovered(P::Footer, |s| s.background(Highlight))
.focus_visible(P::Footer, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
}
}