use crate::style::Color;
use crate::widget::theme::DISABLED_FG;
#[derive(Clone, Debug)]
pub struct Axis {
pub title: Option<String>,
pub min: Option<f64>,
pub max: Option<f64>,
pub ticks: usize,
pub grid: bool,
pub color: Color,
pub format: AxisFormat,
}
#[derive(Clone, Debug, Default)]
pub enum AxisFormat {
#[default]
Auto,
Integer,
Fixed(usize),
Percent,
Custom(String),
}
impl Default for Axis {
fn default() -> Self {
Self {
title: None,
min: None,
max: None,
ticks: 5,
grid: true,
color: DISABLED_FG,
format: AxisFormat::Auto,
}
}
}
impl Axis {
pub fn new() -> Self {
Self::default()
}
pub fn title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
pub fn bounds(mut self, min: f64, max: f64) -> Self {
self.min = Some(min);
self.max = Some(max);
self
}
pub fn min(mut self, min: f64) -> Self {
self.min = Some(min);
self
}
pub fn max(mut self, max: f64) -> Self {
self.max = Some(max);
self
}
pub fn ticks(mut self, ticks: usize) -> Self {
self.ticks = ticks;
self
}
pub fn grid(mut self, show: bool) -> Self {
self.grid = show;
self
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn format(mut self, format: AxisFormat) -> Self {
self.format = format;
self
}
pub fn format_value(&self, value: f64) -> String {
match &self.format {
AxisFormat::Auto => {
if value.abs() >= 1000.0 {
format!("{:.0}", value)
} else if value.abs() >= 1.0 {
format!("{:.1}", value)
} else {
format!("{:.2}", value)
}
}
AxisFormat::Integer => format!("{:.0}", value),
AxisFormat::Fixed(n) => format!("{:.1$}", value, *n),
AxisFormat::Percent => format!("{:.0}%", value * 100.0),
AxisFormat::Custom(fmt) => fmt.replace("{}", &value.to_string()),
}
}
}