use std::{hash::Hasher, sync::Arc};
use super::{
meter::{MeterVariant, number},
names,
part_style::{FontFamily, PartStyle},
recipe::{Case, Name, Recipe, ResolvedPart, ResolvedRecipe, Selector},
sparkline::{color_of, paint_key, width_of},
theme::{Themed, current_theme},
};
use crate::{
app::theme::{PaletteColor, Theme, TypographyStyle},
canvas::{ArcDirection, CanvasItem, LineCap},
components::{Canvas, Column, Row, Stack},
layout::{Alignment, layout_kind::Justify, text_style::FontWeight},
node::{Element, dimension::Dimension},
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GaugePart {
Root,
Arc,
Track,
Value,
Reading,
Range,
Label,
Bound,
}
names!(GaugePart {
Root => "root",
Arc => "arc",
Track => "track",
Value => "value",
Reading => "reading",
Range => "range",
Label => "label",
Bound => "bound",
});
pub type GaugeRenderer = Arc<dyn Fn(GaugeView) -> Element + Send + Sync>;
type NumberText = Arc<dyn Fn(f64) -> String + Send + Sync>;
pub struct Gauge {
value: f64,
min: f64,
max: f64,
low: Option<f64>,
high: Option<f64>,
optimum: Option<f64>,
color: Option<crate::node::BackgroundColor>,
label: Option<Arc<str>>,
value_text: Option<NumberText>,
bound_text: Option<NumberText>,
states: Vec<Name>,
rules: Recipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl Gauge {
pub fn new(value: impl Into<f64>) -> Self {
Self {
value: value.into(),
min: 0.0,
max: 100.0,
low: None,
high: None,
optimum: None,
color: None,
label: None,
value_text: None,
bound_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 color(mut self, color: impl Into<crate::node::BackgroundColor>) -> Self {
self.color = Some(color.into());
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
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 bound_text(mut self, text: impl Fn(f64) -> String + Send + Sync + 'static) -> Self {
self.bound_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(&self) -> Option<Name> {
if self.low.is_none() && self.high.is_none() {
return None;
}
let mut meter = super::Meter::new(self.value).min(self.min).max(self.max);
if let Some(low) = self.low {
meter = meter.low(low);
}
if let Some(high) = self.high {
meter = meter.high(high);
}
if let Some(optimum) = self.optimum {
meter = meter.optimum(optimum);
}
Some(meter.tone_of_value())
}
pub fn build(self, theme: &Theme) -> Element {
let view = self.view(theme);
match theme.renderer::<Gauge>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
fn view(mut self, theme: &Theme) -> GaugeView {
if let Some(color) = self.color.take() {
self.rules = self.rules.base(GaugePart::Value, move |s| s.background(color));
}
let tone = self.tone();
let case = Case {
variant: tone,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
};
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 reading = match &self.value_text {
Some(text) => text(self.value),
None => {
let percent = if span > 0.0 {
(self.value - self.min) / span * 100.0
} else {
0.0
};
format!("{}%", number(percent.round()))
}
};
let bound = |value: f64| match &self.bound_text {
Some(text) => text(value),
None => number(value),
};
GaugeView {
value: self.value,
min: self.min,
max: self.max,
fraction: fraction as f32,
reading,
min_text: bound(self.min),
max_text: bound(self.max),
label: self.label.clone(),
recipe: theme
.resolve::<Gauge>(&case, Some(&self.rules))
.owned_by(self.id.as_ref()),
id: self.id,
key: self.key,
}
}
}
impl From<Gauge> for Element {
fn from(gauge: Gauge) -> Self {
gauge.build(¤t_theme())
}
}
pub struct GaugeView {
pub value: f64,
pub min: f64,
pub max: f64,
pub fraction: f32,
pub reading: String,
pub min_text: String,
pub max_text: String,
pub label: Option<Arc<str>>,
recipe: ResolvedRecipe,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl GaugeView {
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: ResolvedPart, content: &str) -> Row {
Row::new().part(&part).child(part.text(content).nowrap())
}
pub fn arc(&self) -> Stack {
let theme = self.theme();
let track = self.part(GaugePart::Track);
let share = self.part(GaugePart::Value);
let (rail, thickness) = (color_of(&track, theme), width_of(&track, theme, 15.4));
let fill = color_of(&share, theme);
let (fraction, reading) = (self.fraction, self.reading.clone());
let key = paint_key(|hash| {
hash.write_u32(fraction.to_bits());
hash.write_u32(thickness.to_bits());
for color in [rail, fill] {
hash.write(&[color.r(), color.g(), color.b(), color.a()]);
}
hash.write(reading.as_bytes());
});
let canvas = Canvas::new()
.part(&self.part(GaugePart::Arc))
.paint(key, move |canvas| {
let (draw, metrics) = (canvas.context_2d(), canvas.metrics());
draw.reset();
let (width, height) = (metrics.size.width, metrics.size.height);
let (cx, cy) = (width / 2.0, height.min(width / 2.0));
let radius = (width / 2.0 - thickness / 2.0).max(0.0);
let start = std::f32::consts::PI;
draw.set_line_width(thickness);
draw.set_line_cap(LineCap::Butt);
draw.set_stroke_style(rail);
draw.begin_path();
let _ = draw.arc(cx, cy, radius, start, start * 2.0, ArcDirection::Clockwise);
draw.stroke();
if fraction > 0.0 {
draw.set_stroke_style(fill);
draw.begin_path();
let _ = draw.arc(cx, cy, radius, start, start + start * fraction, ArcDirection::Clockwise);
draw.stroke();
}
let end = start + start * fraction;
draw.canvas().set_items([CanvasItem::point(
"value",
"value",
cx + radius * end.cos(),
cy + radius * end.sin(),
thickness / 2.0,
)
.value(reading.clone())]);
});
let reading = self.part(GaugePart::Reading);
let arc = self.part(GaugePart::Arc);
let side = |length: Option<super::part_style::Length>| match length.and_then(|length| length.resolve(theme)) {
Some(dimension) => dimension,
None => Dimension::Pct(100.0),
};
let (width, height) = (side(arc.rest().width), side(arc.rest().height));
Stack::new().child(canvas).child(
Column::new()
.size(width, height)
.align_items(Alignment::Center)
.justify(Justify::End)
.part(&reading)
.child(reading.text(&self.reading).nowrap()),
)
}
pub fn range(&self) -> Row {
let mut range = Row::new()
.width(Dimension::Pct(100.0))
.justify(Justify::SpaceBetween)
.align_items(Alignment::Center)
.part(&self.part(GaugePart::Range))
.child(self.text(self.part(GaugePart::Bound).keyed("min"), &self.min_text));
if let Some(label) = &self.label {
range = range.child(self.text(self.part(GaugePart::Label), label));
}
range.child(self.text(self.part(GaugePart::Bound).keyed("max"), &self.max_text))
}
pub fn root(&self, content: Vec<Element>) -> Column {
let mut root = Column::new()
.align_items(Alignment::Center)
.part(&self.part(GaugePart::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.reading.clone());
if let Some(label) = &self.label {
root = root.describe("a11y_name", label.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 content = vec![self.arc().into(), self.range().into()];
self.root(content).into()
}
}
impl crate::ui::Styled for Gauge {
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 Gauge {
const NAME: &'static str = "gauge";
type Renderer = GaugeRenderer;
fn parts() -> crate::ui::Declared {
GaugePart::declared()
}
fn recipe() -> Recipe {
use GaugePart::{Arc, Bound, Label, Range, Reading, Root, Track, Value};
use PaletteColor::{Foreground, MutedForeground, Secondary};
let mut recipe = Recipe::new()
.base(Root, |s| s.width(140.0).gap(4.0))
.base(Arc, |s| s.width(140.0).height(72.0))
.base(Track, |s| s.width(15.4).background(Secondary))
.base(Value, |s| s.background(PaletteColor::Chart1))
.base(Reading, |s| {
s.typography(TypographyStyle::Body)
.font_size(20.0)
.weight(FontWeight::SemiBold)
.foreground(Foreground)
.padding_bottom(10.0)
})
.base(Range, |s| s.gap(4.0))
.base(Label, |s| {
s.typography(TypographyStyle::Body)
.font_size(12.0)
.weight(FontWeight::Medium)
.foreground(Foreground)
})
.base(Bound, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
});
for variant in MeterVariant::all().iter().copied() {
if variant == MeterVariant::Neutral {
continue;
}
let role = match variant {
MeterVariant::Info => PaletteColor::Info,
MeterVariant::Success => PaletteColor::Success,
MeterVariant::Warning => PaletteColor::Warning,
_ => PaletteColor::Destructive,
};
recipe = recipe.when(Selector::new().variant(variant), Value, move |s| s.background(role));
}
recipe
}
}