use dioxus::prelude::*;
use super::format::{js_number, json_number, json_string};
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ChartX {
Number(f64),
Text(String),
}
impl ChartX {
pub fn display(&self) -> String {
match self {
Self::Number(value) => js_number(*value),
Self::Text(text) => text.clone(),
}
}
pub(crate) fn key(&self) -> String {
match self {
Self::Number(value) => format!("number:{}", js_number(*value)),
Self::Text(text) => format!("string:{text}"),
}
}
pub(crate) fn json(&self) -> String {
match self {
Self::Number(value) => json_number(*value),
Self::Text(text) => json_string(text),
}
}
pub(crate) fn typed_json(&self) -> String {
match self {
Self::Number(value) => format!("[\"number\",{}]", json_number(*value)),
Self::Text(text) => format!("[\"string\",{}]", json_string(text)),
}
}
pub(crate) fn is_axis_value(&self) -> bool {
match self {
Self::Number(value) => value.is_finite(),
Self::Text(_) => true,
}
}
}
impl From<f64> for ChartX {
fn from(value: f64) -> Self {
Self::Number(value)
}
}
impl From<f32> for ChartX {
fn from(value: f32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<i32> for ChartX {
fn from(value: i32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<u32> for ChartX {
fn from(value: u32) -> Self {
Self::Number(f64::from(value))
}
}
impl From<&str> for ChartX {
fn from(value: &str) -> Self {
Self::Text(value.to_string())
}
}
impl From<String> for ChartX {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<&String> for ChartX {
fn from(value: &String) -> Self {
Self::Text(value.clone())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChartTone {
#[default]
Series1,
Series2,
Series3,
Series4,
Series5,
Series6,
Series7,
Series8,
Brand,
Accent,
Success,
Warning,
Danger,
Neutral,
}
const SERIES_TONES: [ChartTone; 8] = [
ChartTone::Series1,
ChartTone::Series2,
ChartTone::Series3,
ChartTone::Series4,
ChartTone::Series5,
ChartTone::Series6,
ChartTone::Series7,
ChartTone::Series8,
];
impl ChartTone {
pub fn as_str(self) -> &'static str {
match self {
Self::Series1 => "series-1",
Self::Series2 => "series-2",
Self::Series3 => "series-3",
Self::Series4 => "series-4",
Self::Series5 => "series-5",
Self::Series6 => "series-6",
Self::Series7 => "series-7",
Self::Series8 => "series-8",
Self::Brand => "brand",
Self::Accent => "accent",
Self::Success => "success",
Self::Warning => "warning",
Self::Danger => "danger",
Self::Neutral => "neutral",
}
}
pub fn class_name(self) -> &'static str {
match self {
Self::Series1 => "ui-chart-tone--series-1",
Self::Series2 => "ui-chart-tone--series-2",
Self::Series3 => "ui-chart-tone--series-3",
Self::Series4 => "ui-chart-tone--series-4",
Self::Series5 => "ui-chart-tone--series-5",
Self::Series6 => "ui-chart-tone--series-6",
Self::Series7 => "ui-chart-tone--series-7",
Self::Series8 => "ui-chart-tone--series-8",
Self::Brand => "ui-chart-tone--brand",
Self::Accent => "ui-chart-tone--accent",
Self::Success => "ui-chart-tone--success",
Self::Warning => "ui-chart-tone--warning",
Self::Danger => "ui-chart-tone--danger",
Self::Neutral => "ui-chart-tone--neutral",
}
}
pub fn resolve(tone: Option<Self>, index: usize) -> Self {
tone.unwrap_or(SERIES_TONES[index % SERIES_TONES.len()])
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChartDatum {
pub x: ChartX,
pub y: Option<f64>,
pub id: Option<String>,
pub label: Option<String>,
pub x_label: Option<String>,
pub size: Option<f64>,
pub tone: Option<ChartTone>,
pub tone_label: Option<String>,
}
impl ChartDatum {
pub fn new(x: impl Into<ChartX>, y: impl Into<Option<f64>>) -> Self {
Self {
x: x.into(),
y: y.into(),
id: None,
label: None,
x_label: None,
size: None,
tone: None,
tone_label: None,
}
}
pub fn missing(x: impl Into<ChartX>) -> Self {
Self::new(x, None)
}
#[must_use]
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
#[must_use]
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
#[must_use]
pub fn with_x_label(mut self, label: impl Into<String>) -> Self {
self.x_label = Some(label.into());
self
}
#[must_use]
pub fn with_size(mut self, size: f64) -> Self {
self.size = Some(size);
self
}
#[must_use]
pub fn with_tone(mut self, tone: ChartTone) -> Self {
self.tone = Some(tone);
self
}
pub(crate) fn value(&self) -> Option<f64> {
self.y.filter(|value| value.is_finite())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ChartSeriesDash {
#[default]
Solid,
Dashed,
Dotted,
}
impl ChartSeriesDash {
pub fn as_str(self) -> &'static str {
match self {
Self::Solid => "solid",
Self::Dashed => "dashed",
Self::Dotted => "dotted",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChartSeries {
pub id: String,
pub label: String,
pub data: Vec<ChartDatum>,
pub tone: Option<ChartTone>,
pub dash: Option<ChartSeriesDash>,
}
impl ChartSeries {
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
data: impl IntoIterator<Item = ChartDatum>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
data: data.into_iter().collect(),
tone: None,
dash: None,
}
}
#[must_use]
pub fn with_dash(mut self, dash: ChartSeriesDash) -> Self {
self.dash = Some(dash);
self
}
#[must_use]
pub fn with_tone(mut self, tone: ChartTone) -> Self {
self.tone = Some(tone);
self
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChartDomain {
pub min: f64,
pub max: f64,
}
impl ChartDomain {
pub fn new(min: f64, max: f64) -> Self {
Self { min, max }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ChartBounds {
pub min: Option<f64>,
pub max: Option<f64>,
}
impl ChartBounds {
pub fn new(min: f64, max: f64) -> Self {
Self {
min: Some(min),
max: Some(max),
}
}
pub fn min(min: f64) -> Self {
Self {
min: Some(min),
max: None,
}
}
pub fn max(max: f64) -> Self {
Self {
min: None,
max: Some(max),
}
}
}
impl From<ChartDomain> for ChartBounds {
fn from(domain: ChartDomain) -> Self {
Self::new(domain.min, domain.max)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ChartSummary {
pub available_point_count: usize,
pub maximum: Option<f64>,
pub minimum: Option<f64>,
pub missing_point_count: usize,
pub series_count: usize,
pub maximum_label: String,
pub minimum_label: String,
}
#[derive(Clone, PartialEq)]
#[allow(missing_docs)]
pub struct ChartLabels {
pub count: String,
pub density: String,
pub end: String,
pub invalid_data: String,
pub start: String,
pub category: String,
pub chart_data: String,
pub chart_legend: String,
pub column: String,
pub empty: String,
pub explore_data: String,
pub high: String,
pub low: String,
pub not_available: String,
pub row: String,
pub series: String,
pub size: String,
pub value: String,
pub view_data: String,
pub x: String,
pub format_datum_action: Option<Callback<String, String>>,
pub format_heatmap_summary: Option<Callback<usize, String>>,
pub format_range_summary: Option<Callback<usize, String>>,
pub format_summary: Option<Callback<ChartSummary, String>>,
}
impl Default for ChartLabels {
fn default() -> Self {
Self {
count: "Count".into(),
density: "Frequency density".into(),
end: "End".into(),
invalid_data: "Chart data is invalid. Check the supplied values.".into(),
start: "Start".into(),
category: "Category".into(),
chart_data: "Chart data".into(),
chart_legend: "Chart legend".into(),
column: "Column".into(),
empty: "No chart data available.".into(),
explore_data: "Explore chart data".into(),
high: "High".into(),
low: "Low".into(),
not_available: "Not available".into(),
row: "Row".into(),
series: "Series".into(),
size: "Size".into(),
value: "Value".into(),
view_data: "View chart data".into(),
x: "X".into(),
format_datum_action: None,
format_heatmap_summary: None,
format_range_summary: None,
format_summary: None,
}
}
}
impl ChartLabels {
pub fn datum_action(&self, context: &str) -> String {
match &self.format_datum_action {
Some(format) => format.call(context.to_string()),
None => format!("Open details: {context}"),
}
}
pub fn heatmap_summary(&self, count: usize) -> String {
match &self.format_heatmap_summary {
Some(format) => format.call(count),
None if count == 0 => "No chart data available.".to_string(),
None => format!(
"{count} available heatmap {}.",
if count == 1 { "cell" } else { "cells" }
),
}
}
pub fn range_summary(&self, count: usize) -> String {
match &self.format_range_summary {
Some(format) => format.call(count),
None if count == 0 => "No chart data available.".to_string(),
None => format!(
"{count} available {}.",
if count == 1 { "range" } else { "ranges" }
),
}
}
pub fn summary(&self, summary: ChartSummary) -> String {
if let Some(format) = &self.format_summary {
return format.call(summary);
}
if summary.available_point_count == 0 {
return "No chart data available.".to_string();
}
let points = if summary.available_point_count == 1 {
"point"
} else {
"points"
};
let missing = if summary.missing_point_count == 0 {
String::new()
} else {
format!(
" {} missing {}.",
summary.missing_point_count,
if summary.missing_point_count == 1 {
"value"
} else {
"values"
}
)
};
format!(
"{} series, {} {points}. Values range from {} to {}.{missing}",
summary.series_count,
summary.available_point_count,
summary.minimum_label,
summary.maximum_label
)
}
}
pub(crate) fn format_with(formatter: Option<&Callback<f64, String>>, value: f64) -> String {
match formatter {
Some(format) => format.call(value),
None => js_number(value),
}
}
pub(crate) fn format_category_with(
formatter: Option<&Callback<ChartX, String>>,
value: &ChartX,
) -> String {
match formatter {
Some(format) => format.call(value.clone()),
None => value.display(),
}
}
pub(crate) fn summarize(
series: &[ChartSeries],
format_value: Option<&Callback<f64, String>>,
) -> ChartSummary {
let mut available = 0;
let mut missing = 0;
let mut maximum = f64::NEG_INFINITY;
let mut minimum = f64::INFINITY;
for item in series {
for datum in &item.data {
match datum.value() {
Some(value) => {
available += 1;
maximum = maximum.max(value);
minimum = minimum.min(value);
}
None => missing += 1,
}
}
}
let maximum = maximum.is_finite().then_some(maximum);
let minimum = minimum.is_finite().then_some(minimum);
ChartSummary {
available_point_count: available,
maximum,
minimum,
missing_point_count: missing,
series_count: series.len(),
maximum_label: format_with(format_value, maximum.unwrap_or(0.0)),
minimum_label: format_with(format_value, minimum.unwrap_or(0.0)),
}
}
#[cfg(test)]
mod tests {
use super::{ChartDatum, ChartLabels, ChartSeries, ChartTone, ChartX, summarize};
#[test]
fn x_identity_follows_javascript() {
assert_eq!(ChartX::from(0.0), ChartX::from(-0.0));
assert_ne!(ChartX::Number(f64::NAN), ChartX::Number(f64::NAN));
assert_ne!(ChartX::from(1), ChartX::from("1"));
assert_eq!(ChartX::from(1.5).key(), "number:1.5");
assert_eq!(ChartX::from("Jan").key(), "string:Jan");
assert_eq!(ChartX::from(f64::NAN).json(), "null");
assert_eq!(ChartX::from("a\"b").typed_json(), "[\"string\",\"a\\\"b\"]");
assert!(!ChartX::from(f64::INFINITY).is_axis_value());
}
#[test]
fn tones_cycle_through_eight_series_colors() {
assert_eq!(ChartTone::resolve(None, 0), ChartTone::Series1);
assert_eq!(ChartTone::resolve(None, 9), ChartTone::Series2);
assert_eq!(
ChartTone::resolve(Some(ChartTone::Danger), 3),
ChartTone::Danger
);
assert_eq!(ChartTone::Series4.class_name(), "ui-chart-tone--series-4");
}
#[test]
fn summaries_count_available_and_missing_points() {
let series = vec![ChartSeries::new(
"a",
"A",
[
ChartDatum::new("x", 3.0),
ChartDatum::missing("y"),
ChartDatum::new("z", f64::NAN),
ChartDatum::new("w", -2.0),
],
)];
let summary = summarize(&series, None);
assert_eq!(summary.available_point_count, 2);
assert_eq!(summary.missing_point_count, 2);
assert_eq!(
ChartLabels::default().summary(summary),
"1 series, 2 points. Values range from -2 to 3. 2 missing values."
);
assert_eq!(
ChartLabels::default().summary(summarize(&[], None)),
"No chart data available."
);
}
}