use std::sync::Arc;
use super::{
Switch, names,
part_style::{Length, PartAnimation, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{FADE_IN, FADE_OUT, fading, glyph, one_line, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
ctx::{CollisionStrategy, Placement},
events::MouseEvent,
theme::{
BorderSize, IconSize, MotionDuration, MotionEasing, OpacityLevel, PaletteColor, RadiusSize, ShadowStyle, Theme,
TypographyStyle,
},
},
components::{Column, Popup, Row},
core::{ElementRef, Signal},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{CursorIcon, Element, FocusGroup, SpacingValue, border::Border, dimension::Dimension, outline::Outline},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TrayPopoverPart {
Panel,
Header,
Media,
Icon,
Text,
Title,
Status,
StatusDot,
Description,
Separator,
Line,
Toggle,
ToggleLabel,
Item,
Body,
}
names!(TrayPopoverPart {
Panel => "panel",
Header => "header",
Media => "media",
Icon => "icon",
Text => "text",
Title => "title",
Status => "status",
StatusDot => "status-dot",
Description => "description",
Separator => "separator",
Line => "line",
Toggle => "toggle",
ToggleLabel => "toggle-label",
Item => "item",
Body => "body",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum TrayStatusVariant {
Neutral,
Info,
#[default]
Success,
Warning,
Destructive,
}
names!(TrayStatusVariant {
Neutral => "neutral",
Info => "info",
Success => "success",
Warning => "warning",
Destructive => "destructive",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TrayPopoverState {
Disabled,
}
names!(TrayPopoverState {
Disabled => "disabled",
});
pub type TrayPopoverRenderer = Arc<dyn Fn(TrayPopoverView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
type Changed = Arc<dyn Fn(bool) + Send + Sync>;
#[derive(Clone)]
pub struct TrayAction {
label: Arc<str>,
disabled: bool,
on_select: Vec<Handler>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TrayAction {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
disabled: false,
on_select: Vec::new(),
id: None,
key: None,
}
}
pub fn on_select(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_select.push(Arc::new(handler));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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
}
}
#[derive(Clone)]
pub struct TrayToggle {
label: Arc<str>,
on: bool,
bound: Option<Signal<bool>>,
disabled: bool,
on_change: Vec<Changed>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TrayToggle {
pub fn new(label: &str) -> Self {
Self {
label: Arc::from(label),
on: false,
bound: None,
disabled: false,
on_change: Vec::new(),
id: None,
key: None,
}
}
pub fn on(mut self, on: bool) -> Self {
self.on = on;
self
}
pub fn bind(mut self, on: Signal<bool>) -> Self {
self.on = on.get();
self.bound = Some(on);
self
}
pub fn on_change(mut self, handler: impl Fn(bool) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
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
}
}
#[derive(Clone)]
pub enum TrayItem {
Action(TrayAction),
Toggle(TrayToggle),
Separator,
Element(Element),
}
impl From<TrayAction> for TrayItem {
fn from(action: TrayAction) -> Self {
Self::Action(action)
}
}
impl From<TrayToggle> for TrayItem {
fn from(toggle: TrayToggle) -> Self {
Self::Toggle(toggle)
}
}
struct Anchored {
open: Signal<bool>,
anchor: ElementRef,
}
pub struct TrayPopover {
title: Arc<str>,
media: Option<Element>,
icon: Option<Name>,
status: Option<Arc<str>>,
status_variant: Name,
items: Vec<TrayItem>,
anchored: Option<Anchored>,
placement: Placement,
offset: SpacingValue,
collision: CollisionStrategy,
dismiss_on_escape: bool,
dismiss_on_outside_press: bool,
on_dismiss: Vec<Handler>,
width: Option<Length>,
label: Option<Arc<str>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TrayPopover {
pub fn new(title: &str) -> Self {
Self {
title: Arc::from(title),
media: None,
icon: None,
status: None,
status_variant: TrayStatusVariant::Success.into(),
items: Vec::new(),
anchored: None,
placement: Placement::BottomEnd,
offset: 6.0.into(),
collision: CollisionStrategy::FlipThenClamp,
dismiss_on_escape: true,
dismiss_on_outside_press: true,
on_dismiss: Vec::new(),
width: None,
label: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn media(mut self, media: impl Into<Element>) -> Self {
self.media = Some(media.into());
self
}
pub fn icon(mut self, icon: impl Into<Name>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn status(mut self, status: &str) -> Self {
self.status = Some(Arc::from(status));
self
}
pub fn status_variant(mut self, variant: impl Into<Name>) -> Self {
self.status_variant = variant.into();
self
}
pub fn item(mut self, item: impl Into<TrayItem>) -> Self {
self.items.push(item.into());
self
}
pub fn items(mut self, items: impl IntoIterator<Item = impl Into<TrayItem>>) -> Self {
self.items.extend(items.into_iter().map(Into::into));
self
}
pub fn separator(mut self) -> Self {
self.items.push(TrayItem::Separator);
self
}
pub fn child(mut self, child: impl Into<Element>) -> Self {
self.items.push(TrayItem::Element(child.into()));
self
}
pub fn children(mut self, children: impl IntoIterator<Item = impl Into<Element>>) -> Self {
self
.items
.extend(children.into_iter().map(|child| TrayItem::Element(child.into())));
self
}
pub fn anchored(mut self, open: Signal<bool>, anchor: impl Into<ElementRef>) -> Self {
self.anchored = Some(Anchored {
open,
anchor: anchor.into(),
});
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 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 on_dismiss(mut self, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.on_dismiss.push(Arc::new(handler));
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = Some(width.into());
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: Some(self.status_variant),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
};
let mut rules = Recipe::new();
if let Some(width) = self.width {
rules = rules.base(TrayPopoverPart::Panel, |s| s.width(width));
}
let rules = rules.extend(&self.rules);
let recipe = theme
.resolve::<TrayPopover>(&case, Some(&rules))
.owned_by(self.id.as_ref());
let disabled = theme
.resolve::<TrayPopover>(&case.clone().state(TrayPopoverState::Disabled, true), Some(&rules))
.owned_like(&recipe);
let view = TrayPopoverView {
title: self.title,
icon: self.icon,
status: self.status,
status_variant: self.status_variant,
anchored: self.anchored.is_some(),
recipe,
disabled,
media: self.media,
items: self.items,
close: self.anchored.as_ref().map(|anchored| anchored.open.clone()),
label: self.label,
forced: self.forced,
id: self.id,
key: self.key,
};
let panel = match theme.renderer::<TrayPopover>() {
Some(renderer) => renderer(view),
None => view.render(),
};
let Some(Anchored { open, anchor }) = self.anchored else {
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(anchor, panel)
.open(open)
.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();
}
});
}
popup.into()
}
}
impl From<TrayPopover> for Element {
fn from(popover: TrayPopover) -> Self {
popover.build(¤t_theme())
}
}
pub struct TrayPopoverView {
pub title: Arc<str>,
pub icon: Option<Name>,
pub status: Option<Arc<str>>,
pub status_variant: Name,
pub anchored: bool,
pub recipe: ResolvedRecipe,
disabled: ResolvedRecipe,
media: Option<Element>,
items: Vec<TrayItem>,
close: Option<Signal<bool>>,
label: Option<Arc<str>>,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl TrayPopoverView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn row_part(&self, part: TrayPopoverPart, disabled: bool) -> ResolvedPart {
if disabled {
self.disabled.part(part)
} else {
self.recipe.part(part)
}
}
pub fn header(&mut self) -> Row {
let mut header = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&self.part(TrayPopoverPart::Header));
let tile = Row::new()
.flex_shrink(0.0)
.justify(Justify::Center)
.align_items(Alignment::Center);
match (self.media.take(), self.icon) {
(Some(media), _) => header = header.child(tile.clip().child(media)),
(None, Some(icon)) => {
header = header.child(tile.part(&self.part(TrayPopoverPart::Media)).child(glyph(
&self.part(TrayPopoverPart::Icon),
icon,
false,
)));
}
(None, None) => {}
}
let title = self.part(TrayPopoverPart::Title);
let mut text = Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.part(&self.part(TrayPopoverPart::Text))
.child(one_line(&title, &self.title));
if let Some(status) = &self.status {
let description = self.part(TrayPopoverPart::Description);
text = text.child(
Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&self.part(TrayPopoverPart::Status))
.describe("a11y_role", "status")
.describe("a11y_name", status.clone())
.child(Row::new().flex_shrink(0.0).part(&self.part(TrayPopoverPart::StatusDot)))
.child(one_line(&description, status)),
);
}
header.child(text)
}
pub fn separator(&self) -> Element {
Row::new()
.width(Dimension::Pct(100.0))
.part(&self.part(TrayPopoverPart::Separator))
.describe("a11y_role", "separator")
.child(
Row::new()
.width(Dimension::Pct(100.0))
.part(&self.part(TrayPopoverPart::Line)),
)
.into()
}
pub fn toggle(&self, toggle: TrayToggle) -> Element {
let part = self.part(TrayPopoverPart::Toggle);
let says = self.row_part(TrayPopoverPart::ToggleLabel, toggle.disabled);
let TrayToggle {
label,
on,
bound,
disabled,
on_change,
id,
key,
} = toggle;
let turn = {
let (bound, on_change) = (bound.clone(), on_change.clone());
move || {
let asked = match &bound {
Some(signal) => {
let asked = !signal.get_untracked();
signal.set(asked);
asked
}
None => !on,
};
for handler in &on_change {
handler(asked);
}
}
};
let mut switch = Switch::new(&label).label_hidden(true).on(on).disabled(disabled);
if let Some(signal) = bound {
switch = switch.bind(signal);
}
for handler in on_change {
switch = switch.on_change(move |on| handler(on));
}
if let Some(id) = id {
switch = switch.id(id);
}
let mut row = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Center)
.part(&part)
.child(
Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.part(&says)
.child(one_line(&part.clone().unnamed(), &label)),
)
.child(
Row::new()
.flex_shrink(0.0)
.on_click(|event: MouseEvent| event.stop_propagation())
.child(switch),
);
if !disabled {
row = row.on_click(move |_: MouseEvent| turn());
}
match key {
Some(key) => row.key(key).into(),
None => row.into(),
}
}
pub fn action(&self, action: TrayAction, forced: Option<Interaction>) -> Element {
let row = if action.disabled { &self.disabled } else { &self.recipe };
let row = match (&action.id, &action.key) {
(None, Some(key)) => row.keyed_item(key, TrayPopoverPart::Item),
(id, _) => row.item(id.as_ref(), TrayPopoverPart::Item),
};
let part = row.part(TrayPopoverPart::Item).forced(forced);
let (close, handlers) = (self.close.clone(), action.on_select);
let mut row = pressable(&part, action.disabled)
.width(Dimension::Pct(100.0))
.justify(Justify::Start)
.align_items(Alignment::Center)
.focus_label(action.label.clone())
.describe("a11y_role", "menuitem")
.describe("a11y_name", action.label.clone())
.child(one_line(&part.clone().unnamed(), &action.label))
.on_click(move |_: MouseEvent| {
if let Some(open) = &close {
open.set(false);
}
for handler in &handlers {
handler();
}
});
if action.disabled {
row = row.describe("a11y_disabled", "true");
}
if let Some(id) = action.id {
row = row.id(id);
}
if let Some(key) = action.key {
row = row.key(key);
}
row.into()
}
pub fn panel(&self) -> Column {
let mut panel = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(TrayPopoverPart::Panel))
.focus_group(FocusGroup::vertical().wrap(false))
.describe("a11y_role", if self.anchored { "dialog" } else { "group" })
.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 items = std::mem::take(&mut self.items);
let mut panel = self.panel().child(self.header());
if !items.is_empty() {
panel = panel.child(self.separator());
}
let mut forced = self.forced;
for item in items {
panel = panel.child(match item {
TrayItem::Action(action) => self.action(action, forced.take()),
TrayItem::Toggle(toggle) => self.toggle(toggle),
TrayItem::Separator => self.separator(),
TrayItem::Element(element) => Row::new()
.width(Dimension::Pct(100.0))
.part(&self.part(TrayPopoverPart::Body))
.child(element)
.into(),
});
}
panel.into()
}
}
impl crate::ui::Styled for TrayPopover {
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 TrayPopover {
const NAME: &'static str = "tray_popover";
const ROOT: &'static str = "panel";
type Renderer = TrayPopoverRenderer;
fn parts() -> crate::ui::Declared {
TrayPopoverPart::declared()
}
fn states() -> crate::ui::Declared {
TrayPopoverState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{
Border as Edge, Destructive, Foreground, Highlight, Info, MutedForeground, Popover, PopoverForeground, Primary,
PrimaryForeground, Ring, Success, Warning,
};
use TrayPopoverPart as P;
use TrayStatusVariant as Tone;
let words = |s: PartStyle| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(Foreground)
};
Recipe::new()
.base(P::Panel, |s| {
s.width(280.0)
.max_width(Length::Fill)
.padding_x(10.0)
.padding_y(10.0)
.gap(8.0)
.radius(RadiusSize::Xl)
.background(Popover)
.foreground(PopoverForeground)
.border(Border::inside(BorderSize::Sm, Edge))
.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.padding_x(4.0).padding_y(2.0).gap(10.0))
.base(P::Media, |s| s.square(28.0).radius(RadiusSize::Md).background(Primary))
.base(P::Icon, |s| {
s.square(Length::Icon(IconSize::Md)).foreground(PrimaryForeground)
})
.base(P::Text, |s| s.gap(1.0))
.base(P::Title, |s| words(s).line_height(16.0 / 13.0).weight(FontWeight::SemiBold))
.base(P::Status, |s| s.gap(5.0))
.base(P::StatusDot, |s| {
s.square(6.0).radius(RadiusSize::Full).background(MutedForeground)
})
.variant(Tone::Info, P::StatusDot, |s| s.background(Info))
.variant(Tone::Success, P::StatusDot, |s| s.background(Success))
.variant(Tone::Warning, P::StatusDot, |s| s.background(Warning))
.variant(Tone::Destructive, P::StatusDot, |s| s.background(Destructive))
.base(P::Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(11.0)
.line_height(13.0 / 11.0)
.foreground(MutedForeground)
})
.base(P::Separator, |s| s.padding_y(4.0))
.base(P::Line, |s| s.height(1.0).background(Edge))
.base(P::Toggle, |s| words(s).height(30.0).padding_x(4.0).gap(8.0))
.row_density(Selector::new(), P::Toggle, 30.0)
.base(P::Item, |s| {
fading(
words(s)
.height(28.0)
.padding_x(4.0)
.radius(RadiusSize::Sm)
.cursor(CursorIcon::Pointer),
)
})
.row_density(Selector::new(), P::Item, 28.0)
.hovered(P::Item, |s| s.background(Highlight))
.focus_visible(P::Item, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(-2.0)))
.state(TrayPopoverState::Disabled, P::Item, |s| {
s.opacity(OpacityLevel::Disabled).cursor(CursorIcon::Default)
})
.state(TrayPopoverState::Disabled, P::ToggleLabel, |s| s.opacity(OpacityLevel::Disabled))
}
}