use dioxus::prelude::*;
use super::format::js_number;
use super::geometry::{LineGeometryOptions, line_geometry};
use super::model::{ChartDatum, ChartTone};
use super::native_paints::paint_attributes;
use crate::class::compose;
#[derive(Props, Clone, PartialEq)]
pub struct SparklineProps {
#[props(default)]
pub values: Vec<f64>,
#[props(default)]
pub area: bool,
#[props(default = "Trend".to_string(), into)]
pub label: String,
#[props(default = true)]
pub show_endpoint: bool,
pub tone: Option<ChartTone>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = span)]
pub attributes: Vec<Attribute>,
}
#[component]
pub fn Sparkline(props: SparklineProps) -> Element {
let data: Vec<ChartDatum> = props
.values
.iter()
.enumerate()
.map(|(index, value)| ChartDatum::new(u32::try_from(index).unwrap_or(u32::MAX), *value))
.collect();
let geometry = line_geometry(&data, LineGeometryOptions::new(120.0, 40.0, 3.0));
let tone = ChartTone::resolve(props.tone, 0);
let native_paints = super::native_paints::use_native_chart_paints(tone);
let class = compose([
Some("ui-sparkline"),
Some(tone.class_name()),
props.class.as_deref(),
]);
let endpoint = geometry
.points
.last()
.filter(|_| props.show_endpoint)
.map(|point| {
format!(
"left:{}%;top:{}%",
js_number(point.x / 120.0 * 100.0),
js_number(point.y / 40.0 * 100.0)
)
});
let area_paths = if props.area {
geometry.area_paths.clone()
} else {
Vec::new()
};
rsx! {
span {
aria_label: "{props.label}",
class,
role: "img",
..props.attributes,
svg {
"aria-hidden": "true",
"preserveAspectRatio": "none",
"viewBox": "0 0 120 40",
width: native_paints.map(|_| "120"),
height: native_paints.map(|_| "40"),
for path in area_paths {
path {
key: "{path}", class: "ui-sparkline__area", d: "{path}",
..paint_attributes(native_paints, "sparkline-area", None),
}
}
path {
class: "ui-sparkline__line", d: "{geometry.path}",
..paint_attributes(native_paints, "sparkline-line", None),
}
}
if let Some(style) = endpoint {
span { aria_hidden: "true", class: "ui-sparkline__endpoint", style }
}
span { class: "ui-sr-only", "{props.label}" }
}
}
}