use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::pyops;
use crate::value::Value;
pub const DEFAULT_COLORS: [&str; 6] = ["#0A2F46", "#1B7A3D", "#B8860B", "#8B3A3A", "#4A6FA5", "#6B4A8B"];
fn escape_text(value: &str) -> String {
value.replace('&', "&").replace('<', "<").replace('>', ">")
}
fn escape_attr(value: &str) -> String {
escape_text(value).replace('"', """)
}
fn format_g(value: f64) -> String {
if value == 0.0 {
return "0".to_string();
}
if !value.is_finite() {
return pyops::py_float_str(value);
}
let abs = value.abs();
if abs >= 1e6 || abs < 1e-4 {
let raw = format!("{value:.5e}");
let (mantissa, exponent) = raw.split_once('e').unwrap_or((&raw, "0"));
let mantissa = trim_zeros(mantissa);
let exponent: i32 = exponent.parse().unwrap_or(0);
format!("{mantissa}e{}{:02}", if exponent < 0 { '-' } else { '+' }, exponent.abs())
} else {
let digits_before = if abs >= 1.0 { abs.log10().floor() as i32 + 1 } else { 1 };
let decimals = (6 - digits_before).max(0) as usize;
trim_zeros(&format!("{value:.decimals$}"))
}
}
fn trim_zeros(value: &str) -> String {
if value.contains('.') {
value.trim_end_matches('0').trim_end_matches('.').to_string()
} else {
value.to_string()
}
}
fn check_series(labels: &[Value], values: &[Value]) -> Result<(Vec<String>, Vec<f64>)> {
if labels.is_empty() || values.is_empty() {
return Err(Error::option("Chart needs non-empty labels and values."));
}
if labels.len() != values.len() {
return Err(Error::option(format!(
"Chart labels ({}) and values ({}) must match in length.",
labels.len(),
values.len()
)));
}
let mut numbers = Vec::with_capacity(values.len());
for value in values {
numbers.push(pyops::py_float(value).map_err(|_| Error::option("Chart values must be numeric"))?);
}
let labels = labels.iter().map(pyops::py_str).collect();
Ok((labels, numbers))
}
pub fn bar_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str, orientation: &str) -> Result<String> {
if !matches!(orientation, "vertical" | "horizontal") {
return Err(Error::option(format!(
"Unknown bar orientation: {orientation:?} (expected vertical|horizontal)"
)));
}
let color = escape_attr(color);
if orientation == "horizontal" {
return horizontal_bar_chart(labels, values, width, height, &color);
}
let (labels, numbers) = check_series(labels, values)?;
let top = 22.0;
let bottom = height as f64 - 30.0;
let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = if max > 0.0 { max } else { 1.0 };
let n = numbers.len() as f64;
let slot = width as f64 / n;
let bar_w = (slot * 0.6).min(60.0);
let mut parts = vec![format!(
r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
)];
for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
let bar_h = ((value / span) * (bottom - top)).max(if *value != 0.0 { 2.0 } else { 0.0 });
let x = slot * index as f64 + (slot - bar_w) / 2.0;
let y = bottom - bar_h;
parts.push(format!(
r#"<rect x="{x:.1}" y="{y:.1}" width="{bar_w:.1}" height="{bar_h:.1}" fill="{color}"/>"#
));
if *value != 0.0 {
parts.push(format!(
r#"<text x="{:.1}" y="{:.1}" text-anchor="middle" font-size="11">{}</text>"#,
x + bar_w / 2.0,
y - 4.0,
format_g(*value)
));
}
parts.push(format!(
r#"<text x="{:.1}" y="{}" text-anchor="middle" font-size="11">{}</text>"#,
slot * index as f64 + slot / 2.0,
height - 8,
escape_text(label)
));
}
parts.push(format!(
r##"<line x1="0" y1="{bottom}" x2="{width}" y2="{bottom}" stroke="#999"/>"##
));
parts.push("</svg>".to_string());
Ok(parts.concat())
}
pub fn horizontal_bar_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str) -> Result<String> {
let (labels, numbers) = check_series(labels, values)?;
let left = 120.0;
let right = 10.0;
let row_h = 26.0;
let gap = 10.0;
let plot_w = width as f64 - left - right;
let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = if max > 0.0 { max } else { 1.0 };
let plot_h = numbers.len() as f64 * (row_h + gap);
let total_h = (height as f64).max(plot_h + 20.0);
let mut parts = vec![format!(
r#"<svg width="{width}" height="{total_h}" viewBox="0 0 {width} {total_h}" xmlns="http://www.w3.org/2000/svg" role="img">"#
)];
for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
let y = 10.0 + index as f64 * (row_h + gap);
let bar_w = ((value / span) * plot_w).max(if *value != 0.0 { 2.0 } else { 0.0 });
parts.push(format!(
r#"<rect x="{left}" y="{y}" width="{bar_w:.1}" height="{row_h}" fill="{color}"/>"#
));
if *value != 0.0 {
parts.push(format!(
r#"<text x="{:.1}" y="{}" font-size="11">{}</text>"#,
left + bar_w + 4.0,
y + 17.0,
format_g(*value)
));
}
parts.push(format!(
r#"<text x="{}" y="{}" text-anchor="end" font-size="11">{}</text>"#,
left - 6.0,
y + 17.0,
escape_text(label)
));
}
parts.push("</svg>".to_string());
Ok(parts.concat())
}
pub fn line_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str) -> Result<String> {
let color = escape_attr(color);
let (labels, numbers) = check_series(labels, values)?;
let top = 22.0;
let bottom = height as f64 - 30.0;
let left = 40.0;
let right = width as f64 - 10.0;
let lo = 0.0f64.min(numbers.iter().copied().fold(f64::INFINITY, f64::min));
let hi = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = if (hi - lo) == 0.0 { 1.0 } else { hi - lo };
let n = numbers.len();
let step = if n > 1 { (right - left) / (n - 1) as f64 } else { 0.0 };
let x = |index: usize| left + step * index as f64;
let y = |value: f64| bottom - (value - lo) / span * (bottom - top);
let mut parts = vec![format!(
r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
)];
let points: Vec<String> = numbers
.iter()
.enumerate()
.map(|(index, value)| format!("{:.1},{:.1}", x(index), y(*value)))
.collect();
parts.push(format!(
r#"<polyline points="{}" fill="none" stroke="{color}" stroke-width="2"/>"#,
points.join(" ")
));
for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
parts.push(format!(
r#"<circle cx="{:.1}" cy="{:.1}" r="3" fill="{color}"/>"#,
x(index),
y(*value)
));
parts.push(format!(
r#"<text x="{:.1}" y="{:.1}" text-anchor="middle" font-size="11">{}</text>"#,
x(index),
y(*value) - 8.0,
format_g(*value)
));
parts.push(format!(
r#"<text x="{:.1}" y="{}" text-anchor="middle" font-size="11">{}</text>"#,
x(index),
height - 8,
escape_text(label)
));
}
parts.push(format!(
r##"<line x1="{left}" y1="{bottom}" x2="{right}" y2="{bottom}" stroke="#999"/>"##
));
parts.push("</svg>".to_string());
Ok(parts.concat())
}
pub(crate) fn spark_numbers(value: &Value) -> Vec<f64> {
let items: Vec<&Value> = match value {
Value::Array(values) => values.iter().collect(),
other => vec![other],
};
let mut numbers = Vec::new();
for item in items {
if item.is_null() || matches!(item, Value::Bool(_)) {
continue;
}
if let Ok(number) = pyops::py_float(item) {
numbers.push(number);
}
}
numbers
}
pub fn sparkline(values: &Value, kind: &str, width: u32, height: u32, color: &str) -> Result<String> {
if !matches!(kind, "line" | "bar") {
return Err(Error::option(format!("Unknown sparkline kind: {kind:?} (expected line|bar)")));
}
let color = escape_attr(color);
let numbers = spark_numbers(values);
if numbers.is_empty() {
return Ok(String::new());
}
let lo = numbers.iter().copied().fold(f64::INFINITY, f64::min);
let hi = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
let span = if (hi - lo) == 0.0 { 1.0 } else { hi - lo };
let pad = 2.0;
let n = numbers.len();
let mut parts = vec![format!(
r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
)];
if kind == "line" {
let step = if n > 1 { (width as f64 - 2.0 * pad) / (n - 1) as f64 } else { 0.0 };
let point = |index: usize, value: f64| -> (f64, f64) {
let x = if n == 1 { pad } else { pad + step * index as f64 };
let y = height as f64 - pad - (value - lo) / span * (height as f64 - 2.0 * pad);
(x, y)
};
if n == 1 {
parts.push(format!(
r#"<circle cx="{:.1}" cy="{:.1}" r="2.5" fill="{color}"/>"#,
width as f64 / 2.0,
height as f64 / 2.0
));
} else {
let points: Vec<String> = numbers
.iter()
.enumerate()
.map(|(index, value)| {
let (x, y) = point(index, *value);
format!("{x:.1},{y:.1}")
})
.collect();
parts.push(format!(
r#"<polyline points="{}" fill="none" stroke="{color}" stroke-width="1.5"/>"#,
points.join(" ")
));
let (x, y) = point(n - 1, numbers[n - 1]);
parts.push(format!(r#"<circle cx="{x:.1}" cy="{y:.1}" r="2" fill="{color}"/>"#));
}
} else {
let slot = (width as f64 - 2.0 * pad) / n as f64;
let bar_w = (slot * 0.7).max(1.0);
for (index, value) in numbers.iter().enumerate() {
let bar_h = (((value - lo) / span) * (height as f64 - 2.0 * pad)).max(if *value != lo || hi == lo { 1.0 } else { 0.0 });
let left = pad + slot * index as f64 + (slot - bar_w) / 2.0;
parts.push(format!(
r#"<rect x="{left:.1}" y="{:.1}" width="{bar_w:.1}" height="{bar_h:.1}" fill="{color}"/>"#,
height as f64 - pad - bar_h
));
}
}
parts.push("</svg>".to_string());
Ok(parts.concat())
}
pub fn pie_chart(labels: &[Value], values: &[Value], width: u32, height: u32, colors: Option<&[String]>, donut: bool) -> Result<String> {
let default_colors: Vec<String> = DEFAULT_COLORS.iter().map(|value| value.to_string()).collect();
let colors: Vec<String> = colors
.map(|colors| colors.iter().map(|color| escape_attr(color)).collect())
.unwrap_or_else(|| default_colors.iter().map(|color| escape_attr(color)).collect());
let (labels, numbers) = check_series(labels, values)?;
let total: f64 = numbers.iter().sum();
if total <= 0.0 {
return Err(Error::option("Pie chart needs a positive total."));
}
let cx = 150.0;
let cy = (height / 2) as f64;
let radius = 140.0f64.min((height / 2) as f64 - 10.0);
let legend_x = 320.0;
let mut parts = vec![format!(
r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
)];
let mut angle = -90.0f64;
for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
let frac = value / total;
let sweep = frac * 360.0;
let large = if sweep > 180.0 { 1 } else { 0 };
let x1 = cx + radius * angle.to_radians().cos();
let y1 = cy + radius * angle.to_radians().sin();
let x2 = cx + radius * (angle + sweep).to_radians().cos();
let y2 = cy + radius * (angle + sweep).to_radians().sin();
let color = &colors[index % colors.len()];
parts.push(format!(
r#"<path d="M {cx},{cy} L {x1:.1},{y1:.1} A {radius},{radius} 0 {large},1 {x2:.1},{y2:.1} Z" fill="{color}"/>"#
));
let ly = 30.0 + index as f64 * 24.0;
parts.push(format!(
r#"<rect x="{legend_x}" y="{:.1}" width="12" height="12" fill="{color}"/>"#,
ly - 12.0
));
parts.push(format!(
r#"<text x="{}" y="{ly}" font-size="12">{} ({:.0}%)</text>"#,
legend_x + 18.0,
escape_text(label),
frac * 100.0
));
angle += sweep;
}
if donut {
parts.push(format!(r#"<circle cx="{cx}" cy="{cy}" r="{}" fill="white"/>"#, radius / 2.0));
}
parts.push("</svg>".to_string());
Ok(parts.concat())
}
fn values_array(spec: &IndexMap<String, Value>, key: &str) -> Vec<Value> {
spec.get(key).and_then(Value::as_array).cloned().unwrap_or_default()
}
fn int_option(spec: &IndexMap<String, Value>, key: &str, default: i64) -> Result<u32> {
match spec.get(key) {
None | Some(Value::Null) => Ok(default as u32),
Some(value) => {
let value = pyops::py_int(value).map_err(|_| Error::option(format!("Invalid chart {key} (expected an integer)")))?;
u32::try_from(value).map_err(|_| Error::option(format!("Invalid chart {key} (expected a positive integer)")))
}
}
}
pub fn build_chart(spec: &IndexMap<String, Value>) -> Result<String> {
let kind = spec.get("kind").and_then(Value::as_str).unwrap_or("bar");
let labels = values_array(spec, "labels");
let values = values_array(spec, "values");
let width = int_option(spec, "width", 600)?;
let height = int_option(spec, "height", 300)?;
let color = spec.get("color").and_then(Value::as_str).unwrap_or("#0A2F46");
match kind {
"bar" => bar_chart(
&labels,
&values,
width,
height,
color,
spec.get("orientation").and_then(Value::as_str).unwrap_or("vertical"),
),
"line" => line_chart(&labels, &values, width, height, color),
"pie" | "donut" => {
let colors = spec.get("colors").and_then(Value::as_array).map(|colors| {
colors
.iter()
.filter_map(|color| color.as_str().map(str::to_string))
.collect::<Vec<_>>()
});
pie_chart(&labels, &values, width, height, colors.as_deref(), kind == "donut")
}
other => Err(Error::option(format!(
"Unknown chart kind: {other:?} (expected one of bar|line|pie|donut)"
))),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn labels(values: &[&str]) -> Vec<Value> {
values.iter().map(|value| Value::String((*value).to_string())).collect()
}
fn numbers(values: &[f64]) -> Vec<Value> {
values.iter().map(|value| Value::Float(*value)).collect()
}
fn array(values: &[f64]) -> Value {
Value::Array(numbers(values))
}
#[test]
fn bar_chart_structure() {
let svg = bar_chart(&labels(&["Jan", "Feb"]), &numbers(&[10.0, 20.0]), 600, 300, "#0A2F46", "vertical").unwrap();
assert!(svg.starts_with("<svg"));
assert_eq!(svg.matches("<rect").count(), 2);
assert!(svg.contains("Jan") && svg.contains("Feb"));
}
#[test]
fn bar_chart_scales_to_max() {
let svg = bar_chart(&labels(&["A", "B"]), &numbers(&[5.0, 10.0]), 200, 100, "#0A2F46", "vertical").unwrap();
assert!(svg.contains(r#"height="48.0""#));
}
#[test]
fn line_chart_structure() {
let svg = line_chart(&labels(&["Jan", "Feb", "Mar"]), &numbers(&[1.0, 3.0, 2.0]), 600, 300, "#0A2F46").unwrap();
assert!(svg.contains("<polyline"));
assert_eq!(svg.matches("<circle").count(), 3);
}
#[test]
fn charts_escape_labels() {
let svg = bar_chart(&labels(&["<b>&"]), &numbers(&[1.0]), 600, 300, "#0A2F46", "vertical").unwrap();
assert!(svg.contains("<b>&"));
assert!(!svg.replace("<svg", "").replace("</svg>", "").contains("<b>"));
}
#[test]
fn charts_reject_bad_series() {
assert!(bar_chart(&[], &[], 600, 300, "#000", "vertical").is_err());
assert!(line_chart(&labels(&["a", "b"]), &numbers(&[1.0]), 600, 300, "#000").is_err());
assert!(bar_chart(&labels(&["a"]), &[Value::String("x".into())], 600, 300, "#000", "vertical").is_err());
}
#[test]
fn pie_and_donut() {
let svg = pie_chart(&labels(&["A", "B"]), &numbers(&[30.0, 70.0]), 600, 300, None, false).unwrap();
assert_eq!(svg.matches("<path").count(), 2);
assert!(svg.contains("30%") && svg.contains("70%"));
let donut = pie_chart(&labels(&["A", "B"]), &numbers(&[1.0, 1.0]), 600, 300, None, true).unwrap();
assert!(donut.contains("<circle"));
}
#[test]
fn sparkline_line_and_bar() {
let line = sparkline(&array(&[1.0, 2.0, 3.0, 2.0, 1.0]), "line", 96, 28, "#0A2F46").unwrap();
assert!(line.starts_with("<svg") && line.contains("<polyline") && line.contains("<circle"));
let bar = sparkline(&array(&[1.0, 2.0, 3.0]), "bar", 96, 28, "#0A2F46").unwrap();
assert_eq!(bar.matches("<rect").count(), 3);
assert!(sparkline(&Value::Array(vec![]), "line", 96, 28, "#000").unwrap().is_empty());
}
}
#[cfg(test)]
mod extra_tests {
use super::*;
fn labels(values: &[&str]) -> Vec<Value> {
values.iter().map(|value| Value::String((*value).to_string())).collect()
}
fn numbers(values: &[f64]) -> Vec<Value> {
values.iter().map(|value| Value::Float(*value)).collect()
}
#[test]
fn build_chart_dispatch_and_options() {
let mut spec = indexmap::IndexMap::new();
spec.insert("kind".into(), Value::String("bar".into()));
spec.insert("labels".into(), Value::Array(labels(&["A"])));
spec.insert("values".into(), Value::Array(numbers(&[1.0])));
spec.insert("orientation".into(), Value::String("horizontal".into()));
spec.insert("width".into(), Value::Int(400));
spec.insert("height".into(), Value::Int(200));
spec.insert("color".into(), Value::String("#123456".into()));
assert!(build_chart(&spec).unwrap().contains("#123456"));
spec.insert("kind".into(), Value::String("line".into()));
assert!(build_chart(&spec).unwrap().contains("<polyline"));
spec.insert("kind".into(), Value::String("pie".into()));
assert!(build_chart(&spec).unwrap().contains("<path"));
spec.insert("kind".into(), Value::String("donut".into()));
assert!(build_chart(&spec).unwrap().contains("<circle"));
spec.insert("kind".into(), Value::String("area".into()));
assert!(build_chart(&spec).is_err());
spec.insert("kind".into(), Value::String("bar".into()));
spec.insert("orientation".into(), Value::String("sideways".into()));
assert!(build_chart(&spec).is_err());
spec.insert("orientation".into(), Value::String("vertical".into()));
spec.insert("width".into(), Value::Int(-1));
assert!(build_chart(&spec).is_err());
spec.insert("width".into(), Value::String("wide".into()));
assert!(build_chart(&spec).is_err());
}
#[test]
fn pie_and_sparkline_edges() {
assert!(pie_chart(&labels(&["A"]), &numbers(&[0.0]), 200, 100, None, false).is_err());
assert!(pie_chart(&[], &[], 200, 100, None, false).is_err());
let svg = pie_chart(
&labels(&["A", "B"]),
&numbers(&[1.0, 2.0]),
200,
100,
Some(&["#111111".into(), "#222222".into()]),
false,
)
.unwrap();
assert!(svg.contains("#111111") && svg.contains("#222222"));
let scalar = sparkline(&Value::Float(5.0), "line", 96, 28, "#000").unwrap();
assert_eq!(scalar.matches("<circle").count(), 1);
assert_eq!(sparkline(&Value::Array(vec![]), "bar", 96, 28, "#000").unwrap(), "");
assert!(sparkline(&Value::Array(vec![Value::Int(1)]), "area", 96, 28, "#000").is_err());
assert_eq!(
sparkline(&Value::Array(vec![Value::Int(1)]), "bar", 96, 28, "#000")
.unwrap()
.matches("<rect")
.count(),
1
);
}
#[test]
fn horizontal_bar_structure() {
let svg = horizontal_bar_chart(&labels(&["A", "B"]), &numbers(&[1.0, 2.0]), 400, 200, "#0A2F46").unwrap();
assert!(svg.contains("A") && svg.contains("B"));
assert_eq!(svg.matches("<rect").count(), 2);
assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "horizontal").is_ok());
assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "vertical").is_ok());
assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "diagonal").is_err());
}
}