use std::sync::Arc;
use super::{
button::{Button, ButtonPart, ButtonSize, ButtonVariant},
checkbox::{Checkbox, CheckboxPart},
collapsible::opening,
dialog::{Dialog, DialogPart},
icons, names,
part_style::{Length, PartStyle},
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{IconChoice, glyph, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
events::KeyboardEvent,
theme::{PaletteColor, RadiusSize, Theme, TypographyStyle},
},
components::{Column, Row},
core::Signal,
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{Element, NodeUpdate, dimension::Dimension, node::Node},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MessageBoxVariant {
#[default]
Info,
Question,
Warning,
Destructive,
}
names!(MessageBoxVariant {
Info => "info",
Question => "question",
Warning => "warning",
Destructive => "destructive",
});
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MessageBoxRole {
Default,
Cancel,
Destructive,
#[default]
Plain,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MessageBoxPart {
Veil,
Panel,
Content,
Header,
Mark,
Icon,
Text,
Title,
Description,
DetailTrigger,
DetailChevron,
DetailLabel,
DetailPanel,
Detail,
Footer,
Option,
Checkbox,
CheckboxLabel,
Actions,
DefaultButton,
DefaultLabel,
CancelButton,
CancelLabel,
DestructiveButton,
DestructiveLabel,
PlainButton,
PlainLabel,
}
names!(MessageBoxPart {
Veil => "veil",
Panel => "panel",
Content => "content",
Header => "header",
Mark => "mark",
Icon => "icon",
Text => "text",
Title => "title",
Description => "description",
DetailTrigger => "detail_trigger",
DetailChevron => "detail_chevron",
DetailLabel => "detail_label",
DetailPanel => "detail_panel",
Detail => "detail",
Footer => "footer",
Option => "option",
Checkbox => "checkbox",
CheckboxLabel => "checkbox_label",
Actions => "actions",
DefaultButton => "default_button",
DefaultLabel => "default_label",
CancelButton => "cancel_button",
CancelLabel => "cancel_label",
DestructiveButton => "destructive_button",
DestructiveLabel => "destructive_label",
PlainButton => "plain_button",
PlainLabel => "plain_label",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MessageBoxState {
Destructive,
DetailOpen,
}
names!(MessageBoxState {
Destructive => "destructive",
DetailOpen => "detail_open",
});
pub type MessageBoxRenderer = Arc<dyn Fn(MessageBoxView) -> Element + Send + Sync>;
type Handler = Arc<dyn Fn() + Send + Sync>;
#[derive(Clone)]
pub struct MessageBoxAnswer {
pub label: Arc<str>,
pub role: MessageBoxRole,
handler: Handler,
}
pub struct MessageBox {
open: Signal<bool>,
variant: Name,
icon: Option<IconChoice>,
title: Option<Arc<str>>,
description: Option<Arc<str>>,
label: Option<Arc<str>>,
detail: Option<(Arc<str>, Signal<bool>)>,
detail_label: Arc<str>,
checkbox: Option<(Arc<str>, Signal<bool>)>,
answers: Vec<MessageBoxAnswer>,
dismiss_on_escape: bool,
dismiss_on_veil: bool,
inline: bool,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MessageBox {
pub fn new(open: Signal<bool>) -> Self {
Self {
open,
variant: MessageBoxVariant::default().into(),
icon: None,
title: None,
description: None,
label: None,
detail: None,
detail_label: super::current_locale().common.details.clone(),
checkbox: None,
answers: Vec::new(),
dismiss_on_escape: true,
dismiss_on_veil: true,
inline: false,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn icon(mut self, icon: impl Into<IconChoice>) -> Self {
self.icon = Some(icon.into());
self
}
pub fn title(mut self, title: &str) -> Self {
self.title = Some(Arc::from(title));
self
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn detail(mut self, detail: &str, open: Signal<bool>) -> Self {
self.detail = Some((Arc::from(detail), open));
self
}
pub fn detail_label(mut self, label: &str) -> Self {
self.detail_label = Arc::from(label);
self
}
pub fn checkbox(mut self, label: &str, checked: Signal<bool>) -> Self {
self.checkbox = Some((Arc::from(label), checked));
self
}
pub fn answer(mut self, label: &str, role: MessageBoxRole, handler: impl Fn() + Send + Sync + 'static) -> Self {
self.answers.push(MessageBoxAnswer {
label: Arc::from(label),
role,
handler: Arc::new(handler),
});
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
let width = width.into();
self.rules = self.rules.base(MessageBoxPart::Panel, |s| s.width(width));
self
}
pub fn dismiss_on_escape(mut self, dismiss: bool) -> Self {
self.dismiss_on_escape = dismiss;
self
}
pub fn dismiss_on_veil(mut self, dismiss: bool) -> Self {
self.dismiss_on_veil = dismiss;
self
}
pub fn inline(mut self, inline: bool) -> Self {
self.inline = inline;
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 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 destructive = self
.answers
.iter()
.any(|answer| answer.role == MessageBoxRole::Destructive);
let detail_open = self.detail.as_ref().is_some_and(|(_, open)| open.get());
let case = Case {
variant: Some(self.variant),
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states,
}
.state(MessageBoxState::Destructive, destructive)
.state(MessageBoxState::DetailOpen, detail_open);
let view = MessageBoxView {
variant: self.variant,
icon: match self.icon {
Some(IconChoice(icon)) => icon,
None => Some(variant_icon(self.variant)),
},
title: self.title,
description: self.description,
label: self.label,
detail: self.detail.as_ref().map(|(detail, _)| detail.clone()),
detail_label: self.detail_label,
detail_open,
checkbox_label: self.checkbox.as_ref().map(|(label, _)| label.clone()),
checked: self.checkbox.as_ref().is_some_and(|(_, checked)| checked.get()),
answers: self.answers,
dismiss_on_escape: self.dismiss_on_escape,
dismiss_on_veil: self.dismiss_on_veil,
inline: self.inline,
recipe: theme
.resolve::<MessageBox>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
open: self.open,
detail_signal: self.detail.map(|(_, open)| open),
checkbox_signal: self.checkbox.map(|(_, checked)| checked),
id: self.id,
key: self.key,
};
match theme.renderer::<MessageBox>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<MessageBox> for Element {
fn from(message_box: MessageBox) -> Self {
message_box.build(¤t_theme())
}
}
fn variant_icon(variant: Name) -> Name {
if variant == Name::from(MessageBoxVariant::Warning) {
icons::WARNING.into()
} else if variant == Name::from(MessageBoxVariant::Destructive) {
icons::ALERT_CIRCLE.into()
} else if variant == Name::from(MessageBoxVariant::Question) {
icons::HELP_CIRCLE.into()
} else {
icons::INFO.into()
}
}
pub struct MessageBoxView {
pub variant: Name,
pub icon: Option<Name>,
pub title: Option<Arc<str>>,
pub description: Option<Arc<str>>,
pub label: Option<Arc<str>>,
pub detail: Option<Arc<str>>,
pub detail_label: Arc<str>,
pub detail_open: bool,
pub checkbox_label: Option<Arc<str>>,
pub checked: bool,
pub answers: Vec<MessageBoxAnswer>,
pub dismiss_on_escape: bool,
pub dismiss_on_veil: bool,
pub inline: bool,
pub recipe: ResolvedRecipe,
open: Signal<bool>,
detail_signal: Option<Signal<bool>>,
checkbox_signal: Option<Signal<bool>>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MessageBoxView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn press(&self, index: usize) -> impl Fn() + Send + Sync + Clone + 'static {
let open = self.open.clone();
let handler = self.answers.get(index).map(|answer| answer.handler.clone());
move || {
open.set(false);
if let Some(handler) = &handler {
handler();
}
}
}
pub fn find(&self, role: MessageBoxRole) -> Option<usize> {
self.answers.iter().position(|answer| answer.role == role)
}
pub fn focused_first(&self) -> Option<usize> {
match self.find(MessageBoxRole::Default) {
Some(default) => Some(default),
None if self.find(MessageBoxRole::Destructive).is_some() => self.find(MessageBoxRole::Cancel),
None => None,
}
}
pub fn button_parts(role: MessageBoxRole) -> (MessageBoxPart, MessageBoxPart) {
match role {
MessageBoxRole::Default => (MessageBoxPart::DefaultButton, MessageBoxPart::DefaultLabel),
MessageBoxRole::Cancel => (MessageBoxPart::CancelButton, MessageBoxPart::CancelLabel),
MessageBoxRole::Destructive => (MessageBoxPart::DestructiveButton, MessageBoxPart::DestructiveLabel),
MessageBoxRole::Plain => (MessageBoxPart::PlainButton, MessageBoxPart::PlainLabel),
}
}
pub fn button(&self, index: usize) -> Element {
let answer = &self.answers[index];
let variant = match answer.role {
MessageBoxRole::Default => ButtonVariant::Primary,
MessageBoxRole::Destructive => ButtonVariant::Destructive,
MessageBoxRole::Cancel | MessageBoxRole::Plain => ButtonVariant::Outline,
};
let (root, label) = Self::button_parts(answer.role);
let rules = self
.recipe
.rules_for(root, ButtonPart::Root)
.extend(&self.recipe.rules_for(label, ButtonPart::Label));
let press = self.press(index);
let button = Button::new(&answer.label)
.variant(variant)
.size(ButtonSize::Sm)
.rules(&rules)
.on_click(move |_| press())
.build(self.theme());
if self.focused_first() == Some(index) {
autofocus(button)
} else {
button
}
}
pub fn mark(&self) -> Option<Row> {
let icon = self.icon?;
Some(
Row::new()
.justify(Justify::Center)
.align_items(Alignment::Center)
.flex_shrink(0.0)
.part(&self.part(MessageBoxPart::Mark))
.child(glyph(&self.part(MessageBoxPart::Icon), icon, false)),
)
}
pub fn title(&self) -> Option<Element> {
let title = self.title.as_ref()?;
Some(wrapping(&self.part(MessageBoxPart::Title), title).into())
}
pub fn description(&self) -> Option<Element> {
let description = self.description.as_ref()?;
Some(wrapping(&self.part(MessageBoxPart::Description), description).into())
}
pub fn detail(&self) -> Option<Element> {
let (detail, open) = (self.detail.as_ref()?, self.detail_signal.as_ref()?);
let (trigger, panel) = disclosure(
&self.recipe,
DisclosureParts {
trigger: MessageBoxPart::DetailTrigger.into(),
icon: MessageBoxPart::DetailChevron.into(),
label: MessageBoxPart::DetailLabel.into(),
panel: MessageBoxPart::DetailPanel.into(),
content: MessageBoxPart::Detail.into(),
},
&self.detail_label,
detail,
open,
);
Some(
Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start)
.overflow_visible()
.child(trigger)
.child(panel)
.into(),
)
}
pub fn text(&self) -> Column {
let mut text = Column::new()
.flex(1.0)
.align_items(Alignment::Stretch)
.overflow_visible()
.part(&self.part(MessageBoxPart::Text));
for element in [self.title(), self.description(), self.detail()].into_iter().flatten() {
text = text.child(element);
}
text
}
pub fn header(&self) -> Row {
let mut header = Row::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Start)
.overflow_visible()
.part(&self.part(MessageBoxPart::Header));
if let Some(mark) = self.mark() {
header = header.child(mark);
}
header.child(self.text())
}
pub fn checkbox(&self) -> Option<Element> {
let (label, checked) = (self.checkbox_label.as_ref()?, self.checkbox_signal.clone()?);
let rules = self
.recipe
.rules_for(MessageBoxPart::Checkbox, CheckboxPart::Root)
.extend(
&self
.recipe
.rules_for(MessageBoxPart::CheckboxLabel, CheckboxPart::Label),
);
let checkbox = Checkbox::new(label)
.checked(self.checked)
.rules(&rules)
.on_change(move |on| checked.set(on))
.build(self.theme());
let mut row = Row::new().overflow_visible().child(checkbox);
if let Some(default) = self.find(MessageBoxRole::Default) {
let press = self.press(default);
row = row.on_key_down(move |event: KeyboardEvent| {
if event.focus_within && enter(&event) {
event.prevent_default();
press();
}
});
}
Some(row.into())
}
pub fn option(&self) -> Option<Row> {
let plain: Vec<usize> = (0..self.answers.len())
.filter(|index| self.answers[*index].role == MessageBoxRole::Plain)
.collect();
let checkbox = self.checkbox();
if checkbox.is_none() && plain.is_empty() {
return None;
}
let mut option = Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(MessageBoxPart::Option));
if let Some(checkbox) = checkbox {
option = option.child(checkbox);
}
for index in plain {
option = option.child(self.button(index));
}
Some(option)
}
pub fn actions(&self) -> Row {
let cancel = self.find(MessageBoxRole::Cancel);
let order = cancel.into_iter().chain(
(0..self.answers.len())
.filter(|index| Some(*index) != cancel && self.answers[*index].role != MessageBoxRole::Plain),
);
let mut actions = Row::new()
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(MessageBoxPart::Actions));
for index in order {
actions = actions.child(self.button(index));
}
actions
}
pub fn footer(&self) -> Row {
let mut footer = Row::new()
.width(Dimension::Pct(100.0))
.wrap()
.align_items(Alignment::Center)
.overflow_visible()
.part(&self.part(MessageBoxPart::Footer));
match self.option() {
Some(option) => {
footer = footer.justify(Justify::SpaceBetween).child(option);
}
None => footer = footer.justify(Justify::End),
}
footer.child(self.actions())
}
pub fn content(&self) -> Column {
let mut content = Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Stretch)
.overflow_visible()
.part(&self.part(MessageBoxPart::Content));
if !self.inline
&& let Some(default) = self.find(MessageBoxRole::Default)
{
let press = self.press(default);
content = content.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within && enter(&event) {
event.prevent_default();
press();
}
});
}
content
}
pub fn dialog(&self, content: impl Into<Element>) -> Element {
let rules = self
.recipe
.rules_for(MessageBoxPart::Panel, DialogPart::Panel)
.extend(&self.recipe.rules_for(MessageBoxPart::Veil, DialogPart::Veil));
let cancel = self.find(MessageBoxRole::Cancel);
let mut dialog = Dialog::new(self.open.clone())
.alert(true)
.rules(&rules)
.inline(self.inline)
.dismiss_on_escape(cancel.is_some() && self.dismiss_on_escape)
.dismiss_on_veil(cancel.is_some() && self.dismiss_on_veil)
.child(content);
if let Some(cancel) = cancel
&& let Some(answer) = self.answers.get(cancel)
{
let handler = answer.handler.clone();
dialog = dialog.on_dismiss(move || handler());
}
if let Some(label) = self.label.as_ref().or(self.title.as_ref()) {
dialog = dialog.label(label);
}
if let Some(description) = &self.description {
dialog = dialog.described(description);
}
if let Some(id) = &self.id {
dialog = dialog.id(id.clone());
}
if let Some(key) = &self.key {
dialog = dialog.key(key.clone());
}
dialog.build(self.theme())
}
pub fn render(self) -> Element {
let content = self.content().child(self.header()).child(self.footer());
self.dialog(content)
}
}
pub(crate) fn wrapping(part: &ResolvedPart, content: &str) -> Column {
let fill = Dimension::Pct(100.0);
Column::new()
.width(fill)
.part(part)
.child(part.text(content).width(fill))
}
pub(crate) fn enter(event: &KeyboardEvent) -> bool {
event.key == "Enter" && !event.composing && !event.default_prevented() && !(event.ctrl || event.alt || event.meta)
}
pub(crate) fn autofocus(element: Element) -> Element {
fn mark(node: &mut Node) -> bool {
if node.is_focusable() {
NodeUpdate::autofocus(node, true);
return true;
}
node.children.iter_mut().any(mark)
}
element.decorate_root(|mut node| {
mark(&mut node);
node
})
}
pub(crate) struct DisclosureParts {
pub trigger: Name,
pub icon: Name,
pub label: Name,
pub panel: Name,
pub content: Name,
}
pub(crate) fn disclosure(
recipe: &ResolvedRecipe,
parts: DisclosureParts,
label: &str,
text: &str,
open: &Signal<bool>,
) -> (crate::components::Button, Column) {
let is_open = open.get();
let turn = open.clone();
let label_part = recipe.part(parts.label);
let trigger = pressable(&recipe.part(parts.trigger), false)
.justify(Justify::Start)
.align_items(Alignment::Center)
.describe("a11y_role", "button")
.describe("a11y_name", label)
.describe("a11y_expanded", if is_open { "true" } else { "false" })
.on_click(move |_| turn.update(|open| *open = !*open))
.child(glyph(
&recipe.part(parts.icon),
if is_open {
icons::CHEVRON_DOWN
} else {
icons::CHEVRON_RIGHT
}
.into(),
false,
))
.child(Row::new().part(&label_part).child(label_part.text(label)));
let mut panel = Column::new()
.align_items(Alignment::Stretch)
.clip()
.presence()
.part(&recipe.part(parts.panel));
if is_open {
let part = recipe.part(parts.content);
panel = panel.child(wrapping(&part, text).key("detail"));
}
(trigger, panel.width(Dimension::Pct(100.0)))
}
pub(crate) fn disclosure_recipe(recipe: Recipe, parts: &DisclosureParts, open: Name) -> Recipe {
use PaletteColor::*;
let recipe = recipe
.base(parts.trigger, |s| {
super::shared::fading(s.gap(4.0).radius(RadiusSize::Sm).cursor(crate::node::CursorIcon::Pointer))
})
.focus_visible(parts.trigger, |s| s.focus_ring())
.base(parts.icon, |s| s.square(14.0).foreground(MutedForeground))
.base(parts.label, |s| {
s.typography(TypographyStyle::Body).font_size(13.0).foreground(Foreground)
})
.base(parts.content, |s| {
s.typography(TypographyStyle::Mono)
.font_size(11.0)
.line_height(1.5)
.foreground(MutedForeground)
.background(Muted)
.radius(RadiusSize::Md)
.padding_x(10.0)
.padding_y(8.0)
})
.state(open, parts.panel, |s| s.padding_top(8.0));
opening(recipe, open, parts.panel, parts.content)
}
impl crate::ui::Styled for MessageBox {
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 MessageBox {
const NAME: &'static str = "message_box";
const ROOT: &'static str = "panel";
type Renderer = MessageBoxRenderer;
fn parts() -> crate::ui::Declared {
MessageBoxPart::declared()
}
fn states() -> crate::ui::Declared {
MessageBoxState::declared()
}
fn recipe() -> Recipe {
use MessageBoxPart::*;
use PaletteColor::{
Destructive as Danger, DestructiveMuted, Foreground, Info, InfoMuted, MutedForeground, Secondary,
Warning as Caution, WarningMuted,
};
let variant = |recipe: Recipe, variant: MessageBoxVariant, well: PaletteColor, ink: PaletteColor| {
recipe
.variant(variant, Mark, |s| s.background(well))
.variant(variant, Icon, |s| s.foreground(ink))
};
let recipe = Recipe::new()
.base(Panel, |s| {
s.width(400.0).max_width(Length::Fill).padding_x(16.0).padding_y(16.0)
})
.base(Content, |s| s.gap(16.0))
.base(Header, |s| s.gap(14.0))
.base(Mark, |s| s.square(36.0).radius(RadiusSize::Full).background(InfoMuted))
.base(Icon, |s| s.square(18.0).foreground(Info))
.base(Text, |s| s.gap(4.0))
.base(Title, |s| {
s.typography(TypographyStyle::Body)
.font_size(15.0)
.weight(FontWeight::SemiBold)
.foreground(Foreground)
})
.base(Description, |s| {
s.typography(TypographyStyle::Description)
.font_size(13.0)
.line_height(1.5)
.foreground(MutedForeground)
})
.base(Footer, |s| s.gap(8.0))
.base(Option, |s| s.gap(8.0))
.base(CheckboxLabel, |s| s.font_size(13.0))
.base(Actions, |s| s.gap(8.0))
.base(DefaultButton, |s| s.padding_x(14.0))
.base(CancelButton, |s| s.padding_x(14.0))
.base(DestructiveButton, |s| s.padding_x(14.0))
.base(PlainButton, |s| s.padding_x(14.0));
let recipe = variant(recipe, MessageBoxVariant::Question, Secondary, Foreground);
let recipe = variant(recipe, MessageBoxVariant::Warning, WarningMuted, Caution);
let recipe = variant(recipe, MessageBoxVariant::Destructive, DestructiveMuted, Danger);
let recipe = recipe
.state(MessageBoxState::Destructive, Mark, |s| s.background(DestructiveMuted))
.state(MessageBoxState::Destructive, Icon, |s| s.foreground(Danger));
disclosure_recipe(
recipe,
&DisclosureParts {
trigger: DetailTrigger.into(),
icon: DetailChevron.into(),
label: DetailLabel.into(),
panel: DetailPanel.into(),
content: Detail.into(),
},
MessageBoxState::DetailOpen.into(),
)
}
}