use std::sync::Arc;
use super::{
names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{PaletteColor, Theme, TypographyStyle},
components::{Column, Row},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{Element, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MeterVariant {
#[default]
Neutral,
Info,
Success,
Warning,
Destructive,
}
names!(MeterVariant {
Neutral => "neutral",
Info => "info",
Success => "success",
Warning => "warning",
Destructive => "destructive",
});
impl MeterVariant {
pub fn named(name: Name) -> Option<Self> {
Self::all().iter().copied().find(|variant| Name::from(*variant) == name)
}
fn color(self) -> PaletteColor {
match self {
Self::Neutral => PaletteColor::Primary,
Self::Info => PaletteColor::Info,
Self::Success => PaletteColor::Success,
Self::Warning => PaletteColor::Warning,
Self::Destructive => PaletteColor::Destructive,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MeterPart {
Root,
Header,
Label,
Value,
Segments,
Segment,
Description,
}
names!(MeterPart {
Root => "root",
Header => "header",
Label => "label",
Value => "value",
Segments => "segments",
Segment => "segment",
Description => "description",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MeterState {
Filled,
}
names!(MeterState {
Filled => "filled",
});
pub type MeterRenderer = Arc<dyn Fn(MeterView) -> Element + Send + Sync>;
type ValueText = Arc<dyn Fn(f64) -> String + Send + Sync>;
pub struct Meter {
value: f64,
min: f64,
max: f64,
low: Option<f64>,
high: Option<f64>,
optimum: Option<f64>,
variant: Name,
segments: usize,
label: Option<Arc<str>>,
description: Option<Arc<str>>,
value_text: Option<ValueText>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Meter {
pub fn new(value: impl Into<f64>) -> Self {
Self {
value: value.into(),
min: 0.0,
max: 100.0,
low: None,
high: None,
optimum: None,
variant: MeterVariant::default().into(),
segments: 16,
label: None,
description: None,
value_text: None,
states: Vec::new(),
rules: Recipe::new(),
id: None,
key: None,
}
}
pub fn value(mut self, value: impl Into<f64>) -> Self {
self.value = value.into();
self
}
pub fn min(mut self, min: impl Into<f64>) -> Self {
self.min = min.into();
self
}
pub fn max(mut self, max: impl Into<f64>) -> Self {
self.max = max.into();
self
}
pub fn low(mut self, low: impl Into<f64>) -> Self {
self.low = Some(low.into());
self
}
pub fn high(mut self, high: impl Into<f64>) -> Self {
self.high = Some(high.into());
self
}
pub fn optimum(mut self, optimum: impl Into<f64>) -> Self {
self.optimum = Some(optimum.into());
self
}
pub fn variant(mut self, variant: impl Into<Name>) -> Self {
self.variant = variant.into();
self
}
pub fn segments(mut self, segments: usize) -> Self {
self.segments = segments.max(1);
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn description(mut self, description: &str) -> Self {
self.description = Some(Arc::from(description));
self
}
pub fn value_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
self.value_text = Some(Arc::new(text));
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
}
fn tone_at(&self, at: f64) -> Name {
if self.low.is_none() && self.high.is_none() {
return self.variant;
}
let low = self.low.unwrap_or(self.min);
let high = self.high.unwrap_or(self.max).max(low);
let part = |value: f64| -> i32 {
if value < low {
0
} else if value > high {
2
} else {
1
}
};
let best = part(self.optimum.unwrap_or(self.min));
match (part(at) - best).abs() {
0 => MeterVariant::Success,
1 => MeterVariant::Warning,
_ => MeterVariant::Destructive,
}
.into()
}
pub(crate) fn tone_of_value(&self) -> Name {
self.tone_at(self.value)
}
pub fn build(self, theme: &Theme) -> Element {
let view = self.view(theme);
match theme.renderer::<Meter>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn view(self, theme: &Theme) -> MeterView {
let case = |variant: Option<Name>, filled: bool| {
Case {
variant,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(MeterState::Filled, filled)
};
let span = self.max - self.min;
let fraction = if span > 0.0 {
((self.value - self.min) / span).clamp(0.0, 1.0)
} else {
0.0
};
let tone = self.tone_at(self.value);
let recipe = theme
.resolve::<Meter>(&case(Some(tone), false), Some(&self.rules))
.owned_by(self.id.as_ref());
let count = self.segments;
let filled = (fraction * count as f64).round() as usize;
let segments = (0..count)
.map(|index| {
let middle = self.min + span * (index as f64 + 0.5) / count as f64;
let tone = self.tone_at(middle);
let on = index < filled;
MeterSegment {
tone,
filled: on,
recipe: theme
.resolve::<Meter>(&case(Some(tone), on), Some(&self.rules))
.owned_like(&recipe),
}
})
.collect();
let max = self.max;
let text = match &self.value_text {
Some(text) => text(self.value),
None => crate::core::fill(
&super::current_locale().common.place_of,
&[("at", &number(self.value)), ("total", &number(max))],
),
};
MeterView {
segments,
value: self.value,
min: self.min,
max: self.max,
tone,
value_text: text,
label: self.label,
description: self.description,
recipe,
id: self.id,
key: self.key,
}
}
}
impl From<Meter> for Element {
fn from(meter: Meter) -> Self {
meter.build(¤t_theme())
}
}
pub(crate) fn number(value: f64) -> String {
let text = format!("{value:.2}");
let text = text.trim_end_matches('0').trim_end_matches('.');
if text == "-0" { "0".to_owned() } else { text.to_owned() }
}
pub struct MeterSegment {
pub tone: Name,
pub filled: bool,
recipe: ResolvedRecipe,
}
impl MeterSegment {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn render(&self) -> Element {
Row::new().flex(1.0).part(&self.part(MeterPart::Segment)).into()
}
}
pub struct MeterView {
pub segments: Vec<MeterSegment>,
pub value: f64,
pub min: f64,
pub max: f64,
pub tone: Name,
pub value_text: String,
pub label: Option<Arc<str>>,
pub description: Option<Arc<str>>,
recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl MeterView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
fn text(&self, part: MeterPart, content: &str) -> Row {
let part = self.part(part);
Row::new()
.min_width(Dimension::Px(0.0))
.part(&part)
.child(part.text(content))
}
pub fn header(&self) -> Row {
let mut header = Row::new()
.width(Dimension::Pct(100.0))
.justify(Justify::SpaceBetween)
.align_items(Alignment::Center)
.part(&self.part(MeterPart::Header));
if let Some(label) = &self.label {
header = header.child(self.text(MeterPart::Label, label));
}
header.child(self.text(MeterPart::Value, &self.value_text))
}
pub fn segments(&self) -> Row {
Row::new()
.width(Dimension::Pct(100.0))
.part(&self.part(MeterPart::Segments))
.with_children(self.segments.iter().map(MeterSegment::render))
}
pub fn description(&self) -> Option<Row> {
let description = self.description.as_ref()?;
let part = self.part(MeterPart::Description);
Some(
Row::new()
.width(Dimension::Pct(100.0))
.part(&part)
.child(part.text(description).width(Dimension::Pct(100.0))),
)
}
pub fn root(&self, content: Vec<Element>) -> Column {
let mut root = Column::new()
.align_items(Alignment::Stretch)
.part(&self.part(MeterPart::Root))
.describe("a11y_role", "meter")
.describe("a11y_valuenow", number(self.value))
.describe("a11y_valuemin", number(self.min))
.describe("a11y_valuemax", number(self.max))
.describe("a11y_valuetext", self.value_text.clone());
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.clone());
}
if let Some(description) = &self.description {
root = root.describe("a11y_description", description.clone());
}
if let Some(id) = &self.id {
root = root.id(id.clone());
}
if let Some(key) = &self.key {
root = root.key(key.clone());
}
root.with_children(content)
}
pub fn render(self) -> Element {
let mut content: Vec<Element> = vec![self.header().into(), self.segments().into()];
content.extend(self.description().map(Into::into));
self.root(content).into()
}
}
impl crate::ui::Styled for Meter {
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 Meter {
const NAME: &'static str = "meter";
type Renderer = MeterRenderer;
fn parts() -> crate::ui::Declared {
MeterPart::declared()
}
fn states() -> crate::ui::Declared {
MeterState::declared()
}
fn recipe() -> Recipe {
use MeterPart::{Description, Header, Label, Root, Segment, Segments, Value};
use MeterState::Filled;
use PaletteColor::{Foreground, MutedForeground, Secondary};
let mut recipe = Recipe::new()
.base(Root, |s| s.width(Length::Fill).gap(8.0))
.base(Header, |s| s.gap(8.0))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(13.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Value, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Segments, |s| s.gap(2.0))
.base(Segment, |s| s.height(8.0).radius(2.0).background(Secondary))
.base(Description, |s| {
s.typography(TypographyStyle::Body)
.font_size(12.0)
.foreground(MutedForeground)
});
for variant in MeterVariant::all().iter().copied() {
recipe = recipe.when(Selector::new().variant(variant).state(Filled), Segment, move |s| {
s.background(variant.color())
});
}
recipe
.variant(MeterVariant::Warning, Description, |s| {
s.foreground(PaletteColor::Warning)
})
.variant(MeterVariant::Destructive, Description, |s| {
s.foreground(PaletteColor::Destructive)
})
}
}