use std::sync::Arc;
use super::{
badge::{Badge, BadgeVariant},
names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
shared::{fading, pressable},
theme::{Themed, current_theme},
};
use crate::{
app::{
events::MouseEvent,
theme::{BorderSize, PaletteColor, RadiusSize, ShadowStyle, Theme, TypographyStyle},
},
components::{Column, Row},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{
CursorIcon, Element, EventHandler, IntoMouseEventHandler, border::Border as Edge, dimension::Dimension,
outline::Outline,
},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StatCardVariant {
#[default]
Neutral,
Info,
Success,
Warning,
Destructive,
}
names!(StatCardVariant {
Neutral => "neutral",
Info => "info",
Success => "success",
Warning => "warning",
Destructive => "destructive",
});
impl StatCardVariant {
pub fn named(name: Name) -> Option<Self> {
Self::all().iter().copied().find(|variant| Name::from(*variant) == name)
}
fn badge(self) -> BadgeVariant {
match self {
Self::Neutral => BadgeVariant::Secondary,
Self::Info => BadgeVariant::Info,
Self::Success => BadgeVariant::Success,
Self::Warning => BadgeVariant::Warning,
Self::Destructive => BadgeVariant::Destructive,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum StatCardSize {
Sm,
#[default]
Md,
}
names!(StatCardSize {
Sm => "sm",
Md => "md",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StatCardPart {
Root,
Label,
Body,
Value,
Media,
Footer,
Description,
}
names!(StatCardPart {
Root => "root",
Label => "label",
Body => "body",
Value => "value",
Media => "media",
Footer => "footer",
Description => "description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum StatCardState {
Pressable,
Media,
}
names!(StatCardState {
Pressable => "pressable",
Media => "media",
});
pub type StatCardRenderer = Arc<dyn Fn(StatCardView) -> Element + Send + Sync>;
pub struct StatCard {
label: Arc<str>,
value: Arc<str>,
delta: Option<Arc<str>>,
description: Option<Arc<str>>,
media: Option<Element>,
variant: Name,
size: Name,
on_click: Vec<EventHandler<MouseEvent>>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl StatCard {
pub fn new(label: &str, value: &str) -> Self {
Self {
label: Arc::from(label),
value: Arc::from(value),
delta: None,
description: None,
media: None,
variant: StatCardVariant::default().into(),
size: StatCardSize::default().into(),
on_click: Vec::new(),
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn delta(mut self, delta: &str) -> Self {
self.delta = Some(Arc::from(delta));
self
}
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 variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn size(mut self, size: impl Into<Name>) -> Self {
self.size = size.into();
self
}
pub fn on_click(mut self, handler: impl IntoMouseEventHandler) -> Self {
self.on_click.push(handler.into_event_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 fn build(self, theme: &Theme) -> Element {
let pressable = !self.on_click.is_empty();
let case = Case {
variant: Some(self.variant),
size: Some(self.size),
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(StatCardState::Pressable, pressable)
.state(StatCardState::Media, self.media.is_some());
let view = StatCardView {
label: self.label,
value: self.value,
delta: self.delta,
description: self.description,
media: self.media,
tone: self.variant,
on_click: self.on_click,
forced: self.forced,
recipe: theme
.resolve::<StatCard>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
};
match theme.renderer::<StatCard>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
impl From<StatCard> for Element {
fn from(card: StatCard) -> Self {
card.build(¤t_theme())
}
}
pub struct StatCardView {
pub label: Arc<str>,
pub value: Arc<str>,
pub delta: Option<Arc<str>>,
pub description: Option<Arc<str>>,
media: Option<Element>,
pub tone: Name,
on_click: Vec<EventHandler<MouseEvent>>,
forced: Option<Interaction>,
recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl StatCardView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn text(&self, part: StatCardPart, content: &str) -> Column {
let part = self.part(part);
let fill = Dimension::Pct(100.0);
Column::new()
.width(fill)
.part(&part)
.child(part.text(content).width(fill))
}
pub fn label(&self) -> Column {
self.text(StatCardPart::Label, &self.label)
}
pub fn body(&mut self) -> Row {
let value = Column::new()
.flex(1.0)
.min_width(Dimension::Px(0.0))
.child(self.text(StatCardPart::Value, &self.value));
let mut body = Row::new()
.width(Dimension::Pct(100.0))
.justify(Justify::SpaceBetween)
.align_items(Alignment::End)
.part(&self.part(StatCardPart::Body))
.child(value);
if let Some(media) = self.media.take() {
body = body.child(Row::new().part(&self.part(StatCardPart::Media)).child(media));
}
body
}
pub fn footer(&self) -> Option<Row> {
if self.delta.is_none() && self.description.is_none() {
return None;
}
let mut footer = Row::new()
.align_items(Alignment::Center)
.part(&self.part(StatCardPart::Footer));
if let Some(delta) = &self.delta {
let variant = StatCardVariant::named(self.tone).unwrap_or_default().badge();
footer = footer.child(
Badge::new(delta)
.variant(variant)
.rules(&self.recipe.lend("badge"))
.build(self.theme()),
);
}
if let Some(description) = &self.description {
let part = self.part(StatCardPart::Description);
footer = footer.child(Row::new().part(&part).child(part.text(description)));
}
Some(footer)
}
pub fn root(&self, content: Vec<Element>) -> Element {
let part = self.part(StatCardPart::Root);
let mut said = self.value.to_string();
if let Some(delta) = &self.delta {
said.push_str(&format!(", {delta}"));
}
if let Some(description) = &self.description {
said.push_str(&format!(" {description}"));
}
if self.on_click.is_empty() {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&part)
.describe("a11y_role", "group")
.describe("a11y_name", self.label.clone())
.describe("a11y_description", said);
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
return root.with_children(content).into();
}
let handlers = self.on_click.clone();
let mut button = pressable(&part, false)
.justify(Justify::Start)
.align_items(Alignment::Stretch)
.describe("a11y_role", "button")
.describe("a11y_name", self.label.clone())
.describe("a11y_description", said)
.on_click(move |event: MouseEvent| {
for handler in &handlers {
handler.call(&event);
}
});
if let Some(id) = &self.id {
button = button.id(id.clone());
}
if let Some(key) = &self.key {
button = button.key(key.clone());
}
button
.child(
Column::new()
.width(Dimension::Pct(100.0))
.align_items(Alignment::Stretch)
.spacing(part.rest().gap.unwrap_or_default())
.with_children(content),
)
.into()
}
pub fn render(mut self) -> Element {
let mut content: Vec<Element> = vec![self.label().into(), self.body().into()];
content.extend(self.footer().map(Into::into));
self.root(content)
}
}
impl crate::ui::Styled for StatCard {
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 StatCard {
const NAME: &'static str = "stat_card";
type Renderer = StatCardRenderer;
fn parts() -> crate::ui::Declared {
StatCardPart::declared()
}
fn states() -> crate::ui::Declared {
StatCardState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Card, CardForeground, MutedForeground, Ring};
use StatCardPart::{Body, Description, Footer, Label, Root, Value};
use StatCardSize::Sm;
use StatCardState::Pressable;
let edge = |color: PaletteColor| Edge::inside(BorderSize::Sm, color);
Recipe::new()
.base(Root, |s| {
fading(
s.width(Length::Fill)
.background(Card)
.foreground(CardForeground)
.border(edge(PaletteColor::Border))
.radius(RadiusSize::Xl)
.shadow(ShadowStyle::Sm)
.padding_x(20.0)
.padding_y(20.0)
.gap(8.0),
)
})
.size(Sm, Root, |s| s.padding_x(16.0).padding_y(16.0))
.state(Pressable, Root, |s| s.cursor(CursorIcon::Pointer))
.when(Selector::new().state(Pressable).hovered(), Root, |s| {
s.border(edge(Ring)).shadow(ShadowStyle::Md)
})
.focus_visible(Root, |s| s.outline(Outline::new(BorderSize::Md, Ring).offset(2.0)))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.foreground(MutedForeground)
})
.size(Sm, Label, |s| s.font_size(12.0))
.base(Body, |s| s.gap(12.0))
.base(Value, |s| {
s.typography(TypographyStyle::Body)
.font_size(28.0)
.weight(FontWeight::SemiBold)
.letter_spacing(-0.5)
.foreground(CardForeground)
})
.size(Sm, Value, |s| s.font_size(24.0).letter_spacing(-0.4))
.base(Footer, |s| s.gap(8.0))
.base(Description, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
}
}