use std::collections::{HashMap, HashSet};
use dioxus::prelude::*;
use super::format::{js_equals, js_number, js_to_fixed};
use super::model::{
ChartBounds, ChartDatum, ChartDomain, ChartSeries, ChartTone, ChartX, format_with,
};
use super::scale::{
CategoryTick, CategoryTickOptions, LabelContext, align_series, axis_domain, axis_padding,
category_label, category_ticks, chart_categories, chart_domain, chart_ticks,
estimate_chart_label_width, fitted_label, format_ticks, nice_domain, resolve_domain,
scale_value, value_ratio,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineChartScale {
#[default]
Categorical,
Linear,
Time,
}
fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
let year = if month <= 2 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let month_index = (month + 9) % 12;
let day_of_year = (153 * month_index + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
fn is_leap_year(year: i64) -> bool {
(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}
fn days_in_month(year: i64, month: i64) -> i64 {
match month {
2 if is_leap_year(year) => 29,
2 => 28,
4 | 6 | 9 | 11 => 30,
_ => 31,
}
}
fn read_digits(bytes: &[u8], index: usize, count: usize) -> Option<i64> {
let slice = bytes.get(index..index + count)?;
slice.iter().try_fold(0_i64, |total, byte| {
byte.is_ascii_digit()
.then(|| total * 10 + i64::from(byte - b'0'))
})
}
pub(crate) fn parse_iso_timestamp(text: &str) -> Option<f64> {
let bytes = text.as_bytes();
if bytes.len() > 40 {
return None;
}
let year = read_digits(bytes, 0, 4)?;
let mut index = 4;
let mut month = 1;
let mut day = 1;
if bytes.get(index) == Some(&b'-') {
month = read_digits(bytes, index + 1, 2)?;
index += 3;
if bytes.get(index) == Some(&b'-') {
day = read_digits(bytes, index + 1, 2)?;
index += 3;
}
}
if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
return None;
}
let mut milliseconds = 0_i64;
if index < bytes.len() {
if bytes[index] != b'T' || index != 10 {
return None;
}
let hours = read_digits(bytes, index + 1, 2)?;
let minutes = (bytes.get(index + 3) == Some(&b':'))
.then(|| read_digits(bytes, index + 4, 2))
.flatten()?;
index += 6;
let mut seconds = 0;
let mut fraction = 0;
if bytes.get(index) == Some(&b':') {
seconds = read_digits(bytes, index + 1, 2)?;
index += 3;
if bytes.get(index) == Some(&b'.') {
fraction = read_digits(bytes, index + 1, 3)?;
index += 4;
}
}
if hours > 24
|| minutes > 59
|| seconds > 59
|| (hours == 24 && (minutes, seconds, fraction) != (0, 0, 0))
{
return None;
}
let mut offset = 0;
match bytes.get(index) {
None => {}
Some(b'Z') if index + 1 == bytes.len() => {}
Some(sign @ (b'+' | b'-')) if index + 6 == bytes.len() && bytes[index + 3] == b':' => {
let offset_hours = read_digits(bytes, index + 1, 2)?;
let offset_minutes = read_digits(bytes, index + 4, 2)?;
if offset_hours > 23 || offset_minutes > 59 {
return None;
}
let total = (offset_hours * 60 + offset_minutes) * 60_000;
offset = if *sign == b'+' { total } else { -total };
}
Some(_) => return None,
}
milliseconds = ((hours * 60 + minutes) * 60 + seconds) * 1000 + fraction - offset;
}
let days = days_from_civil(year, month, day);
#[allow(clippy::cast_precision_loss)]
let timestamp = (days * 86_400_000 + milliseconds) as f64;
Some(timestamp)
}
pub(crate) fn numeric_x(value: &ChartX, scale: LineChartScale) -> Option<f64> {
match value {
ChartX::Number(number) => number.is_finite().then_some(*number),
ChartX::Text(text) => match scale {
LineChartScale::Categorical | LineChartScale::Linear => {
let trimmed = text.trim();
if trimmed.is_empty() {
return None;
}
parse_js_number(trimmed).filter(|number| number.is_finite())
}
LineChartScale::Time => parse_iso_timestamp(text),
},
}
}
fn parse_js_number(text: &str) -> Option<f64> {
let lower = text.to_ascii_lowercase();
for (prefix, radix) in [("0x", 16), ("0o", 8), ("0b", 2)] {
if let Some(digits) = lower.strip_prefix(prefix) {
#[allow(clippy::cast_precision_loss)]
return u64::from_str_radix(digits, radix)
.ok()
.map(|value| value as f64);
}
}
if lower.contains("inf") || lower.contains("nan") {
return None;
}
text.parse::<f64>().ok()
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct GeometryPoint {
pub(crate) datum: ChartDatum,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LineGeometry {
pub(crate) area_paths: Vec<String>,
pub(crate) domain: ChartDomain,
pub(crate) path: String,
pub(crate) points: Vec<GeometryPoint>,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct LineGeometryOptions {
pub(crate) domain: Option<ChartBounds>,
pub(crate) height: f64,
pub(crate) include_zero: bool,
pub(crate) inset: Option<f64>,
pub(crate) padding_bottom: f64,
pub(crate) padding_left: f64,
pub(crate) padding_right: f64,
pub(crate) padding_top: f64,
pub(crate) width: f64,
pub(crate) x_domain: Option<ChartBounds>,
pub(crate) x_scale: LineChartScale,
}
impl LineGeometryOptions {
pub(crate) fn new(width: f64, height: f64, padding: f64) -> Self {
Self {
domain: None,
height,
include_zero: false,
inset: None,
padding_bottom: padding,
padding_left: padding,
padding_right: padding,
padding_top: padding,
width,
x_domain: None,
x_scale: LineChartScale::Categorical,
}
}
}
fn segment_path(points: &[GeometryPoint]) -> String {
points
.iter()
.enumerate()
.map(|(index, point)| {
format!(
"{} {} {}",
if index == 0 { "M" } else { "L" },
js_to_fixed(point.x, 3),
js_to_fixed(point.y, 3)
)
})
.collect::<Vec<_>>()
.join(" ")
}
fn area_path(points: &[GeometryPoint], baseline: f64) -> String {
let (Some(first), Some(last)) = (points.first(), points.last()) else {
return String::new();
};
[
segment_path(points),
"L".to_string(),
js_to_fixed(last.x, 3),
js_to_fixed(baseline, 3),
"L".to_string(),
js_to_fixed(first.x, 3),
js_to_fixed(baseline, 3),
"Z".to_string(),
]
.join(" ")
}
fn resolve_inset(inset: Option<f64>, plot_width: f64) -> f64 {
match inset {
Some(inset) if inset.is_finite() && inset > 0.0 => inset.min(plot_width.max(0.0) / 4.0),
_ => 0.0,
}
}
pub(crate) fn line_geometry(data: &[ChartDatum], options: LineGeometryOptions) -> LineGeometry {
let inset = resolve_inset(
options.inset,
options.width - options.padding_left - options.padding_right,
);
let options = LineGeometryOptions {
padding_left: options.padding_left + inset,
padding_right: options.padding_right + inset,
..options
};
let scale = options.x_scale;
let domain_values: Vec<Option<f64>> = data
.iter()
.filter(|datum| {
scale == LineChartScale::Categorical || numeric_x(&datum.x, scale).is_some()
})
.map(|datum| datum.y)
.collect();
let domain = resolve_domain(domain_values, options.domain, options.include_zero);
let x_domain = (scale != LineChartScale::Categorical).then(|| {
resolve_domain(
data.iter().map(|datum| numeric_x(&datum.x, scale)),
options.x_domain,
false,
)
});
let drawable_width = (options.width - options.padding_left - options.padding_right).max(0.0);
let drawable_height = (options.height - options.padding_top - options.padding_bottom).max(0.0);
let mut segments: Vec<Vec<GeometryPoint>> = Vec::new();
let mut current: Vec<GeometryPoint> = Vec::new();
for (index, datum) in data.iter().enumerate() {
let x = match (scale, x_domain) {
(LineChartScale::Categorical, _) => {
#[allow(clippy::cast_precision_loss)]
let ratio = if data.len() == 1 {
0.5
} else {
index as f64 / (data.len().max(2) - 1) as f64
};
Some(options.padding_left + ratio * drawable_width)
}
(_, Some(x_domain)) => numeric_x(&datum.x, scale).map(|value| {
scale_value(
value,
x_domain,
options.padding_left,
options.padding_left + drawable_width,
)
}),
(_, None) => None,
};
match (datum.value(), x) {
(Some(value), Some(x)) => current.push(GeometryPoint {
datum: datum.clone(),
x,
y: scale_value(
value,
domain,
options.padding_top + drawable_height,
options.padding_top,
),
}),
_ => {
if !current.is_empty() {
segments.push(std::mem::take(&mut current));
}
}
}
}
if !current.is_empty() {
segments.push(current);
}
let baseline = scale_value(
domain.min.max(domain.max.min(0.0)),
domain,
options.height - options.padding_bottom,
options.padding_top,
);
LineGeometry {
area_paths: segments
.iter()
.map(|points| area_path(points, baseline))
.filter(|path| !path.is_empty())
.collect(),
domain,
path: segments
.iter()
.map(|points| segment_path(points))
.collect::<Vec<_>>()
.join(" "),
points: segments.into_iter().flatten().collect(),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum BarChartLayout {
#[default]
Grouped,
Stacked,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum BarChartOrientation {
#[default]
Vertical,
Horizontal,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BarMark {
pub(crate) category: ChartX,
pub(crate) datum_id: Option<String>,
pub(crate) height: f64,
pub(crate) series_id: String,
pub(crate) series_label: String,
pub(crate) tone: ChartTone,
pub(crate) value: f64,
pub(crate) width: f64,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BarCategory {
pub(crate) category: ChartX,
pub(crate) label: String,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Margin {
pub(crate) bottom: f64,
pub(crate) left: f64,
pub(crate) right: f64,
pub(crate) top: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BarGeometry {
pub(crate) categories: Vec<BarCategory>,
pub(crate) domain: ChartDomain,
pub(crate) height: f64,
pub(crate) marks: Vec<BarMark>,
pub(crate) margin: Margin,
pub(crate) tick_labels: Vec<String>,
pub(crate) ticks: Vec<f64>,
pub(crate) width: f64,
}
#[derive(Clone)]
pub(crate) struct BarGeometryOptions<'a> {
pub(crate) axis_font_size: Option<f64>,
pub(crate) category_width: Option<f64>,
pub(crate) domain: Option<ChartBounds>,
pub(crate) format_category: Option<&'a Callback<ChartX, String>>,
pub(crate) format_value: Option<&'a Callback<f64, String>>,
pub(crate) height: f64,
pub(crate) layout: BarChartLayout,
pub(crate) orientation: BarChartOrientation,
pub(crate) width: f64,
}
impl Default for BarGeometryOptions<'_> {
fn default() -> Self {
Self {
axis_font_size: None,
category_width: None,
domain: None,
format_category: None,
format_value: None,
height: 320.0,
layout: BarChartLayout::Grouped,
orientation: BarChartOrientation::Vertical,
width: 640.0,
}
}
}
fn index_series(series: &ChartSeries) -> HashMap<String, &ChartDatum> {
let mut indexed = HashMap::new();
for datum in &series.data {
indexed.insert(datum.x.key(), datum);
}
indexed
}
fn indexed_values(series: &ChartSeries) -> Vec<Option<f64>> {
let mut order: Vec<String> = Vec::new();
let mut values: HashMap<String, Option<f64>> = HashMap::new();
for datum in &series.data {
let key = datum.x.key();
if !values.contains_key(&key) {
order.push(key.clone());
}
values.insert(key, datum.y);
}
order
.into_iter()
.map(|key| values.get(&key).copied().flatten())
.collect()
}
fn stacked_totals(series: &[ChartSeries], categories: &[ChartX]) -> Vec<Option<f64>> {
let indexed: Vec<HashMap<String, &ChartDatum>> = series.iter().map(index_series).collect();
let mut totals = Vec::new();
for category in categories {
let key = category.key();
let mut positive = 0.0;
let mut negative = 0.0;
for item in &indexed {
let value = item
.get(&key)
.and_then(|datum| datum.value())
.unwrap_or(0.0);
if value >= 0.0 {
positive += value;
} else {
negative += value;
}
}
totals.push(Some(negative));
totals.push(Some(positive));
}
totals
}
#[allow(clippy::too_many_lines)]
pub(crate) fn bar_geometry(
series: &[ChartSeries],
options: &BarGeometryOptions<'_>,
) -> BarGeometry {
let width = options.width;
let height = options.height;
let horizontal = options.orientation == BarChartOrientation::Horizontal;
let stacked = options.layout == BarChartLayout::Stacked;
let categories = chart_categories(series);
let indexed: Vec<HashMap<String, &ChartDatum>> = series.iter().map(index_series).collect();
let values: Vec<Option<f64>> = if stacked {
stacked_totals(series, &categories)
} else {
series.iter().flat_map(indexed_values).collect()
};
let domain = axis_domain(&values, options.domain, true);
let ticks = chart_ticks(domain);
let tick_labels = format_ticks(&ticks, options.format_value);
let margin = if horizontal {
let labels: Vec<String> = categories
.iter()
.map(|category| {
category_label(
series,
category,
options.format_category,
LabelContext::Axis,
)
})
.collect();
Margin {
bottom: 24.0,
left: options
.category_width
.unwrap_or_else(|| axis_padding(&labels, 112.0, None))
.clamp(64.0, 240.0)
.max(64.0),
right: 20.0,
top: 16.0,
}
} else {
Margin {
bottom: 52.0,
left: (width - 56.0).min(axis_padding(&tick_labels, 52.0, options.axis_font_size)),
right: 16.0,
top: 16.0,
}
};
let plot_width = (width - margin.left - margin.right).max(1.0);
let plot_height = (height - margin.top - margin.bottom).max(1.0);
#[allow(clippy::cast_precision_loss)]
let category_size =
if horizontal { plot_height } else { plot_width } / categories.len().max(1) as f64;
let category_gap = (category_size * 0.24).min(16.0);
let usable = (category_size - category_gap).max(1.0);
#[allow(clippy::cast_precision_loss)]
let series_size = usable / series.len().max(1) as f64;
let mut marks = Vec::new();
let mut positions = Vec::new();
for (category_index, category) in categories.iter().enumerate() {
#[allow(clippy::cast_precision_loss)]
let category_start = if horizontal { margin.top } else { margin.left }
+ category_index as f64 * category_size
+ category_gap / 2.0;
let mut positive_offset = 0.0;
let mut negative_offset = 0.0;
positions.push(BarCategory {
category: category.clone(),
label: category_label(
series,
category,
options.format_category,
LabelContext::Axis,
),
x: if horizontal {
margin.left - 8.0
} else {
category_start + usable / 2.0
},
y: if horizontal {
category_start + usable / 2.0
} else {
height - 20.0
},
});
let key = category.key();
for (series_index, item) in series.iter().enumerate() {
let Some(datum) = indexed[series_index].get(&key) else {
continue;
};
let Some(value) = datum.value() else {
continue;
};
let datum_id = datum.id.clone();
let tone = ChartTone::resolve(item.tone, series_index);
let start_value = if !stacked {
0.0
} else if value >= 0.0 {
positive_offset
} else {
negative_offset
};
let end_value = start_value + value;
#[allow(clippy::cast_precision_loss)]
let offset = if stacked {
0.0
} else {
series_index as f64 * series_size + 1.0
};
let thickness = if stacked {
usable
} else {
(series_size - 2.0).max(1.0)
};
if horizontal {
let start = scale_value(start_value, domain, margin.left, margin.left + plot_width);
let end = scale_value(end_value, domain, margin.left, margin.left + plot_width);
marks.push(BarMark {
category: category.clone(),
datum_id: datum_id.clone(),
height: thickness,
series_id: item.id.clone(),
series_label: item.label.clone(),
tone,
value,
width: (end - start).abs(),
x: start.min(end),
y: category_start + offset,
});
} else {
let start = scale_value(start_value, domain, margin.top + plot_height, margin.top);
let end = scale_value(end_value, domain, margin.top + plot_height, margin.top);
marks.push(BarMark {
category: category.clone(),
datum_id,
height: (end - start).abs(),
series_id: item.id.clone(),
series_label: item.label.clone(),
tone,
value,
width: thickness,
x: category_start + offset,
y: start.min(end),
});
}
if stacked {
if value >= 0.0 {
positive_offset += value;
} else {
negative_offset += value;
}
}
}
}
BarGeometry {
categories: positions,
domain,
height,
marks,
margin,
tick_labels,
ticks,
width,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PieChartVariant {
#[default]
Donut,
Pie,
}
impl PieChartVariant {
pub fn class_name(self) -> &'static str {
match self {
Self::Donut => "ui-pie-chart--donut",
Self::Pie => "ui-pie-chart--pie",
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PieSlice {
pub(crate) datum: ChartDatum,
pub(crate) label: String,
pub(crate) path: String,
pub(crate) percentage: f64,
pub(crate) tone: ChartTone,
pub(crate) value: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct PieGeometry {
pub(crate) size: f64,
pub(crate) slices: Vec<PieSlice>,
pub(crate) total: f64,
}
fn polar(center: f64, radius: f64, angle: f64) -> (f64, f64) {
let radians = (angle * std::f64::consts::PI) / 180.0;
(
center + radians.cos() * radius,
center + radians.sin() * radius,
)
}
fn pie_arc(radius: f64, large: bool, sweep: u8, point: (f64, f64)) -> String {
format!(
"A {} {} 0 {} {sweep} {} {}",
js_to_fixed(radius, 3),
js_to_fixed(radius, 3),
u8::from(large),
js_to_fixed(point.0, 3),
js_to_fixed(point.1, 3)
)
}
fn move_to(command: &str, point: (f64, f64)) -> String {
format!(
"{command} {} {}",
js_to_fixed(point.0, 3),
js_to_fixed(point.1, 3)
)
}
fn full_pie_path(center: f64, outer: f64, inner: f64) -> String {
let top = polar(center, outer, -90.0);
let bottom = polar(center, outer, 90.0);
let mut parts = vec![
move_to("M", top),
pie_arc(outer, true, 1, bottom),
pie_arc(outer, true, 1, top),
"Z".to_string(),
];
if inner != 0.0 {
let inner_top = polar(center, inner, -90.0);
let inner_bottom = polar(center, inner, 90.0);
parts.extend([
move_to("M", inner_top),
pie_arc(inner, true, 0, inner_bottom),
pie_arc(inner, true, 0, inner_top),
"Z".to_string(),
]);
}
parts.join(" ")
}
fn pie_slice_path(center: f64, outer: f64, inner: f64, start: f64, end: f64) -> String {
if end - start >= 359.999 {
return full_pie_path(center, outer, inner);
}
let outer_start = polar(center, outer, start);
let outer_end = polar(center, outer, end);
let large = end - start > 180.0;
if inner == 0.0 {
return [
move_to("M", (center, center)),
move_to("L", outer_start),
pie_arc(outer, large, 1, outer_end),
"Z".to_string(),
]
.join(" ");
}
let inner_start = polar(center, inner, start);
let inner_end = polar(center, inner, end);
[
move_to("M", outer_start),
pie_arc(outer, large, 1, outer_end),
move_to("L", inner_end),
pie_arc(inner, large, 0, inner_start),
"Z".to_string(),
]
.join(" ")
}
pub(crate) fn pie_values(data: &[ChartDatum]) -> Vec<ChartDatum> {
data.iter()
.filter(|datum| datum.value().is_some_and(|value| value > 0.0))
.cloned()
.collect()
}
pub(crate) fn pie_geometry(data: &[ChartDatum], variant: PieChartVariant) -> PieGeometry {
let size: f64 = 320.0;
let padding = 12.0;
let center = size / 2.0;
let outer = (center - padding).max(0.0);
let inner = if variant == PieChartVariant::Pie {
0.0
} else {
outer * 0.58
};
let available = pie_values(data);
let total: f64 = available.iter().filter_map(ChartDatum::value).sum();
let mut angle = -90.0;
let count = available.len();
let slices = available
.into_iter()
.enumerate()
.map(|(index, datum)| {
let value = datum.value().unwrap_or(0.0);
let percentage = if total == 0.0 { 0.0 } else { value / total };
let start = angle;
let end = if index == count - 1 {
270.0
} else {
start + percentage * 360.0
};
angle = end;
PieSlice {
label: datum
.label
.clone()
.or_else(|| datum.x_label.clone())
.unwrap_or_else(|| datum.x.display()),
path: pie_slice_path(center, outer, inner, start, end),
percentage,
tone: ChartTone::resolve(datum.tone, index),
value,
datum,
}
})
.collect();
PieGeometry {
size,
slices,
total,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScatterChartScale {
#[default]
Linear,
Log,
Time,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ScatterChartReference {
pub id: String,
pub label: String,
pub x: Option<f64>,
pub y: Option<f64>,
pub x_end: Option<f64>,
pub y_end: Option<f64>,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ScatterPoint {
pub(crate) datum: ChartDatum,
pub(crate) radius: f64,
pub(crate) series_id: String,
pub(crate) series_label: String,
pub(crate) tone: ChartTone,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct PlotFrame {
pub(crate) bottom: f64,
pub(crate) left: f64,
pub(crate) right: f64,
pub(crate) top: f64,
}
impl PlotFrame {
pub(crate) fn new(width: f64, height: f64, padding: Margin) -> Self {
Self {
bottom: height - padding.bottom,
left: padding.left,
right: width - padding.right,
top: padding.top,
}
}
pub(crate) fn contains(&self, x: f64, y: f64) -> bool {
x >= self.left && x <= self.right && y >= self.top && y <= self.bottom
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ScatterGeometry {
pub(crate) domain: ChartDomain,
pub(crate) height: f64,
pub(crate) plot: PlotFrame,
pub(crate) points: Vec<ScatterPoint>,
pub(crate) width: f64,
pub(crate) x_domain: ChartDomain,
}
fn scatter_numeric_x(value: &ChartX, scale: ScatterChartScale) -> Option<f64> {
let line_scale = match scale {
ScatterChartScale::Time => LineChartScale::Time,
ScatterChartScale::Linear | ScatterChartScale::Log => LineChartScale::Linear,
};
let numeric = numeric_x(value, line_scale)?;
(scale != ScatterChartScale::Log || numeric > 0.0).then_some(numeric)
}
fn valid_scatter_domain(domain: ChartDomain, scale: ScatterChartScale) -> bool {
domain.min.is_finite()
&& domain.max.is_finite()
&& domain.max > domain.min
&& (scale != ScatterChartScale::Log || domain.min > 0.0)
}
pub(crate) fn scale_scatter_x(
value: f64,
domain: ChartDomain,
start: f64,
end: f64,
scale: ScatterChartScale,
) -> f64 {
if scale != ScatterChartScale::Log {
return scale_value(value, domain, start, end);
}
if value <= 0.0 || !value.is_finite() {
return f64::NAN;
}
scale_value(
value.log10(),
ChartDomain::new(domain.min.log10(), domain.max.log10()),
start,
end,
)
}
fn pad_scatter_domain(
domain: ChartDomain,
values: &[f64],
requested: Option<ChartBounds>,
extent: f64,
radius: f64,
scale: ScatterChartScale,
) -> ChartDomain {
if values.is_empty() || extent <= 0.0 {
return domain;
}
let log = scale == ScatterChartScale::Log;
let project = |value: f64| if log { value.log10() } else { value };
let from_scale = |value: f64| if log { 10f64.powf(value) } else { value };
let min = project(domain.min);
let max = project(domain.max);
let inset = (radius + 2.0).min(extent / 4.0);
let extra = (max - min) * inset / (extent - 2.0 * inset);
let (bound_min, bound_max) = values
.iter()
.map(|value| project(*value))
.fold((f64::INFINITY, f64::NEG_INFINITY), |(low, high), value| {
(low.min(value), high.max(value))
});
let padded_min = from_scale(min.min(bound_min - extra));
let padded_max = from_scale(max.max(bound_max + extra));
let finite = |value: f64, fallback: f64| {
if value.is_finite() && (!log || value > 0.0) {
value
} else {
fallback
}
};
let requested = requested.unwrap_or_default();
ChartDomain::new(
requested
.min
.unwrap_or_else(|| finite(padded_min, domain.min)),
requested
.max
.unwrap_or_else(|| finite(padded_max, domain.max)),
)
}
fn nice_scatter_domain(
domain: ChartDomain,
requested: Option<ChartBounds>,
scale: ScatterChartScale,
) -> ChartDomain {
if scale != ScatterChartScale::Linear {
return domain;
}
let nice = nice_domain(domain);
let requested = requested.unwrap_or_default();
let finite = |value: Option<f64>| value.is_some_and(f64::is_finite);
ChartDomain::new(
if finite(requested.min) {
domain.min
} else {
nice.min
},
if finite(requested.max) {
domain.max
} else {
nice.max
},
)
}
fn requested_scatter_x_domain(
x_values: &[f64],
scale: ScatterChartScale,
bounds: Option<ChartBounds>,
) -> ChartDomain {
let automatic = if scale == ScatterChartScale::Log && x_values.is_empty() {
ChartDomain::new(1.0, 10.0)
} else {
chart_domain(x_values.iter().copied().map(Some), false)
};
let requested = bounds.unwrap_or_default();
ChartDomain::new(
requested.min.unwrap_or(automatic.min),
requested.max.unwrap_or(automatic.max),
)
}
pub(crate) fn scatter_geometry(
series: &[ChartSeries],
scale: ScatterChartScale,
x_bounds: Option<ChartBounds>,
y_bounds: Option<ChartBounds>,
padding: Margin,
axis_font_size: Option<f64>,
format_value: Option<&Callback<f64, String>>,
) -> Option<ScatterGeometry> {
let (width, height) = (640.0, 320.0);
let mut plot = PlotFrame::new(width, height, padding);
let (minimum_radius, maximum_radius): (f64, f64) = (4.0, 18.0);
let projected: Vec<&ChartDatum> = series
.iter()
.flat_map(|item| item.data.iter())
.filter(|datum| scatter_numeric_x(&datum.x, scale).is_some() && datum.value().is_some())
.collect();
let calculated = resolve_domain(projected.iter().map(|datum| datum.y), y_bounds, false);
if !valid_scatter_domain(calculated, ScatterChartScale::Linear) {
return None;
}
let x_values: Vec<f64> = projected
.iter()
.filter_map(|datum| scatter_numeric_x(&datum.x, scale))
.collect();
let calculated_x = requested_scatter_x_domain(&x_values, scale, x_bounds);
if !valid_scatter_domain(calculated_x, scale) {
return None;
}
let size_domain = chart_domain(
projected
.iter()
.map(|datum| datum.size.filter(|size| *size >= 0.0)),
false,
);
let minimum_radius = minimum_radius.max(1.0);
let maximum_radius = maximum_radius.max(minimum_radius);
let y_values: Vec<f64> = projected.iter().filter_map(|datum| datum.y).collect();
let domain = nice_scatter_domain(
pad_scatter_domain(
calculated,
&y_values,
y_bounds,
plot.bottom - plot.top,
maximum_radius,
ScatterChartScale::Linear,
),
y_bounds,
ScatterChartScale::Linear,
);
if axis_font_size.is_some() {
let tick_labels: Vec<String> = chart_ticks(domain)
.into_iter()
.map(|tick| format_with(format_value, tick))
.collect();
plot.left = (plot.right - 40.0).min(axis_padding(&tick_labels, plot.left, axis_font_size));
}
let x_domain = nice_scatter_domain(
pad_scatter_domain(
calculated_x,
&x_values,
x_bounds,
plot.right - plot.left,
maximum_radius,
scale,
),
x_bounds,
scale,
);
let mut points = Vec::new();
for (series_index, item) in series.iter().enumerate() {
for datum in &item.data {
let (Some(numeric), Some(value)) = (scatter_numeric_x(&datum.x, scale), datum.value())
else {
continue;
};
let radius = match datum.size {
Some(size) if size.is_finite() && size >= 0.0 => {
scale_value(size, size_domain, minimum_radius, maximum_radius)
}
_ => minimum_radius,
};
points.push(ScatterPoint {
datum: datum.clone(),
radius,
series_id: item.id.clone(),
series_label: item.label.clone(),
tone: ChartTone::resolve(datum.tone.or(item.tone), series_index),
x: scale_scatter_x(numeric, x_domain, plot.left, plot.right, scale),
y: scale_value(value, domain, plot.bottom, plot.top),
});
}
}
Some(ScatterGeometry {
domain,
height,
plot,
points,
width,
x_domain,
})
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct ScatterReferenceGeometry {
pub(crate) id: String,
pub(crate) label: String,
pub(crate) region: bool,
pub(crate) x1: f64,
pub(crate) x2: f64,
pub(crate) y1: f64,
pub(crate) y2: f64,
}
pub(crate) fn scatter_references(
references: &[ScatterChartReference],
geometry: &ScatterGeometry,
scale: ScatterChartScale,
) -> Vec<ScatterReferenceGeometry> {
let frame = geometry.plot;
let x = |value: f64| scale_scatter_x(value, geometry.x_domain, frame.left, frame.right, scale);
let y = |value: f64| scale_value(value, geometry.domain, frame.bottom, frame.top);
let finite = |value: Option<f64>| value.is_none_or(f64::is_finite);
references
.iter()
.filter(|reference| {
finite(reference.x)
&& finite(reference.y)
&& finite(reference.x_end)
&& finite(reference.y_end)
})
.filter_map(|reference| {
let x1 = reference.x.map_or(frame.left, x);
let y1 = reference.y.map_or(frame.top, y);
let x2 = reference.x_end.map_or(
if reference.x.is_none() {
frame.right
} else {
x1
},
x,
);
let y2 = reference.y_end.map_or(
if reference.y.is_none() {
frame.bottom
} else {
y1
},
y,
);
[x1, x2, y1, y2]
.iter()
.all(|value| value.is_finite())
.then(|| ScatterReferenceGeometry {
id: reference.id.clone(),
label: reference.label.clone(),
region: reference.x_end.is_some() && reference.y_end.is_some(),
x1,
x2,
y1,
y2,
})
})
.collect()
}
#[derive(Clone, Debug, PartialEq)]
pub struct HeatmapDatum {
pub x: ChartX,
pub y: ChartX,
pub value: Option<f64>,
pub id: Option<String>,
pub label: Option<String>,
pub x_label: Option<String>,
pub y_label: Option<String>,
pub tone: Option<ChartTone>,
}
impl HeatmapDatum {
pub fn new(x: impl Into<ChartX>, y: impl Into<ChartX>, value: impl Into<Option<f64>>) -> Self {
Self {
x: x.into(),
y: y.into(),
value: value.into(),
id: None,
label: None,
x_label: None,
y_label: None,
tone: 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_axis_labels(
mut self,
x_label: impl Into<String>,
y_label: impl Into<String>,
) -> Self {
self.x_label = Some(x_label.into());
self.y_label = Some(y_label.into());
self
}
pub(crate) fn finite_value(&self) -> Option<f64> {
self.value.filter(|value| value.is_finite())
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeatmapColorScale {
#[default]
Sequential,
Diverging,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct HeatmapCell {
pub(crate) datum: HeatmapDatum,
pub(crate) height: f64,
pub(crate) width: f64,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct HeatmapRowTick {
pub(crate) label: String,
pub(crate) position: f64,
pub(crate) value: ChartX,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct HeatmapModel {
pub(crate) cells: Vec<HeatmapCell>,
pub(crate) domain: ChartDomain,
pub(crate) legend_background: String,
pub(crate) midpoint: f64,
pub(crate) midpoint_percent: f64,
pub(crate) x_ticks: Vec<CategoryTick>,
pub(crate) y_ticks: Vec<HeatmapRowTick>,
}
fn resolve_ordered_domain(automatic: ChartDomain, requested: Option<ChartBounds>) -> ChartDomain {
let requested = requested.unwrap_or_default();
let min = requested
.min
.filter(|value| value.is_finite())
.unwrap_or(automatic.min);
let max = requested
.max
.filter(|value| value.is_finite())
.unwrap_or(automatic.max);
if min < max {
ChartDomain::new(min, max)
} else {
automatic
}
}
fn heatmap_scale(
automatic: ChartDomain,
color_scale: HeatmapColorScale,
midpoint: f64,
requested: Option<ChartBounds>,
) -> (ChartDomain, f64) {
let midpoint = if midpoint.is_finite() { midpoint } else { 0.0 };
if color_scale != HeatmapColorScale::Diverging {
return (resolve_ordered_domain(automatic, requested), midpoint);
}
let radius = (automatic.min - midpoint)
.abs()
.max((automatic.max - midpoint).abs())
.max(1.0);
let symmetric = ChartDomain::new(midpoint - radius, midpoint + radius);
let resolved = resolve_ordered_domain(symmetric, requested);
let finite = |domain: ChartDomain| domain.min.is_finite() && domain.max.is_finite();
if finite(resolved) && resolved.min < midpoint && resolved.max > midpoint {
return (resolved, midpoint);
}
if finite(symmetric) {
return (symmetric, midpoint);
}
let fallback = automatic.min.abs().max(automatic.max.abs()).max(1.0);
(ChartDomain::new(-fallback, fallback), 0.0)
}
fn unique_categories<'a>(values: impl Iterator<Item = &'a ChartX>) -> Vec<ChartX> {
let mut seen = HashSet::new();
let mut categories = Vec::new();
for value in values {
if seen.insert(value.key()) {
categories.push(value.clone());
}
}
categories
}
pub(crate) fn heatmap_model(
data: &[HeatmapDatum],
color_scale: HeatmapColorScale,
midpoint: f64,
domain: Option<ChartBounds>,
) -> HeatmapModel {
let valid = data
.iter()
.all(|datum| datum.x.is_axis_value() && datum.y.is_axis_value());
let mut seen = HashSet::new();
let cells: Vec<&HeatmapDatum> = if valid {
data.iter()
.filter(|datum| seen.insert(format!("{}|{}", datum.x.json(), datum.y.json())))
.collect()
} else {
Vec::new()
};
let x_categories = unique_categories(cells.iter().map(|cell| &cell.x));
let y_categories = unique_categories(cells.iter().map(|cell| &cell.y));
#[allow(clippy::cast_precision_loss)]
let cell_width = 496.0 / x_categories.len().max(1) as f64;
#[allow(clippy::cast_precision_loss)]
let cell_height = 248.0 / y_categories.len().max(1) as f64;
let x_index: HashMap<String, usize> = x_categories
.iter()
.enumerate()
.map(|(index, category)| (category.key(), index))
.collect();
let y_index: HashMap<String, usize> = y_categories
.iter()
.enumerate()
.map(|(index, category)| (category.key(), index))
.collect();
let automatic = chart_domain(cells.iter().map(|cell| cell.finite_value()), false);
let (domain, midpoint) = heatmap_scale(automatic, color_scale, midpoint, domain);
let midpoint_percent = scale_value(midpoint, domain, 0.0, 100.0);
let label_for_x = |value: &ChartX| {
cells
.iter()
.find(|cell| cell.x == *value)
.and_then(|cell| cell.x_label.clone())
.unwrap_or_else(|| value.display())
};
let label_for_y = |value: &ChartX| {
cells
.iter()
.find(|cell| cell.y == *value)
.and_then(|cell| cell.y_label.clone())
.unwrap_or_else(|| value.display())
};
#[allow(clippy::cast_precision_loss)]
let column_positions: Vec<f64> = (0..x_categories.len())
.map(|index| 120.0 + (index as f64 + 0.5) * 496.0 / x_categories.len() as f64)
.collect();
let column_labels: Vec<String> = x_categories.iter().map(label_for_x).collect();
let x_ticks = category_ticks(
&column_labels,
CategoryTickOptions::new(120.0, 616.0)
.bounds(0.0, 640.0)
.positions(&column_positions),
);
#[allow(clippy::cast_precision_loss)]
let y_ticks = y_categories
.iter()
.enumerate()
.map(|(index, value)| HeatmapRowTick {
label: fitted_label(&label_for_y(value), 104.0),
position: 24.0 + (index as f64 + 0.5) * 248.0 / y_categories.len() as f64,
value: value.clone(),
})
.collect();
#[allow(clippy::cast_precision_loss)]
let positioned = cells
.iter()
.filter_map(|datum| {
let column = x_index.get(&datum.x.key())?;
let row = y_index.get(&datum.y.key())?;
Some(HeatmapCell {
datum: (*datum).clone(),
height: cell_height,
width: cell_width,
x: *column as f64 * cell_width + 120.0,
y: *row as f64 * cell_height + 24.0,
})
})
.collect();
let legend_background = if color_scale == HeatmapColorScale::Diverging {
format!(
"linear-gradient(to right, hsl(var(--chart-diverging-negative)), hsl(var(--chart-diverging-mid)) {}%, hsl(var(--chart-diverging-positive)))",
js_number(midpoint_percent)
)
} else {
"linear-gradient(to right, hsl(var(--chart-sequential-low)), hsl(var(--chart-sequential-high)))".to_string()
};
HeatmapModel {
cells: positioned,
domain,
legend_background,
midpoint,
midpoint_percent,
x_ticks,
y_ticks,
}
}
pub(crate) fn heatmap_color(
value: Option<f64>,
domain: ChartDomain,
color_scale: HeatmapColorScale,
midpoint: f64,
) -> String {
let Some(value) = value.filter(|value| value.is_finite()) else {
return "hsl(var(--surface-muted))".to_string();
};
let ratio = |start: f64, end: f64| {
if js_equals(end, start) {
0.5
} else {
value_ratio(value, ChartDomain::new(start, end))
}
};
let (overlay, base, amount) = if color_scale == HeatmapColorScale::Diverging {
if value < midpoint {
(
"diverging-negative",
"diverging-mid",
1.0 - ratio(domain.min, midpoint),
)
} else {
(
"diverging-positive",
"diverging-mid",
ratio(midpoint, domain.max),
)
}
} else {
(
"sequential-high",
"sequential-low",
ratio(domain.min, domain.max),
)
};
format!(
"color-mix(in srgb, hsl(var(--chart-{overlay})) {}%, hsl(var(--chart-{base})))",
js_number(amount * 100.0)
)
}
#[derive(Clone, Debug, PartialEq)]
pub struct RangeChartDatum {
pub x: ChartX,
pub low: Option<f64>,
pub high: Option<f64>,
pub id: Option<String>,
pub label: Option<String>,
pub x_label: Option<String>,
}
impl RangeChartDatum {
pub fn new(
x: impl Into<ChartX>,
low: impl Into<Option<f64>>,
high: impl Into<Option<f64>>,
) -> Self {
Self {
x: x.into(),
low: low.into(),
high: high.into(),
id: None,
label: None,
x_label: 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
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RangePoint {
pub(crate) datum: RangeChartDatum,
pub(crate) high: f64,
pub(crate) low: f64,
pub(crate) x: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct RangeGeometry {
pub(crate) area_path: String,
pub(crate) domain: ChartDomain,
pub(crate) plot: PlotFrame,
pub(crate) points: Vec<RangePoint>,
pub(crate) ticks: Vec<f64>,
}
const RANGE_INSET: f64 = 8.0;
pub(crate) fn range_geometry(
data: &[RangeChartDatum],
padding: Margin,
width: f64,
height: f64,
axis_font_size: Option<f64>,
format_value: Option<&Callback<f64, String>>,
) -> RangeGeometry {
let finite = |datum: &RangeChartDatum| match (
datum.low.filter(|v| v.is_finite()),
datum.high.filter(|v| v.is_finite()),
) {
(Some(low), Some(high)) => Some((low, high)),
_ => None,
};
let values: Vec<Option<f64>> = data
.iter()
.filter_map(finite)
.flat_map(|(low, high)| [Some(low), Some(high)])
.collect();
let domain = axis_domain(&values, None, false);
let mut plot = PlotFrame::new(width, height, padding);
if axis_font_size.is_some() {
let tick_labels = format_ticks(&chart_ticks(domain), format_value);
plot.left = (plot.right - 40.0).min(axis_padding(&tick_labels, plot.left, axis_font_size));
}
let inset = resolve_inset(Some(RANGE_INSET), plot.right - plot.left);
let (point_left, point_right) = (plot.left + inset, plot.right - inset);
let mut segments: Vec<Vec<RangePoint>> = Vec::new();
let mut current: Vec<RangePoint> = Vec::new();
for (index, datum) in data.iter().enumerate() {
let Some((low, high)) = finite(datum) else {
if !current.is_empty() {
segments.push(std::mem::take(&mut current));
}
continue;
};
#[allow(clippy::cast_precision_loss)]
let ratio = if data.len() == 1 {
0.5
} else {
index as f64 / (data.len().max(2) - 1) as f64
};
current.push(RangePoint {
datum: datum.clone(),
high: scale_value(high, domain, plot.bottom, plot.top),
low: scale_value(low, domain, plot.bottom, plot.top),
x: point_left + ratio * (point_right - point_left),
});
}
if !current.is_empty() {
segments.push(current);
}
let area_path = segments
.iter()
.map(|segment| {
let mut parts: Vec<String> = segment
.iter()
.enumerate()
.map(|(index, point)| {
format!(
"{} {} {}",
if index == 0 { "M" } else { "L" },
js_to_fixed(point.x, 3),
js_to_fixed(point.high, 3)
)
})
.collect();
parts.extend(segment.iter().rev().map(|point| {
format!(
"L {} {}",
js_to_fixed(point.x, 3),
js_to_fixed(point.low, 3)
)
}));
parts.push("Z".to_string());
parts.join(" ")
})
.collect::<Vec<_>>()
.join(" ");
RangeGeometry {
area_path,
domain,
plot,
points: segments.into_iter().flatten().collect(),
ticks: chart_ticks(domain),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LineChartAnnotationAxis {
#[default]
Y,
X,
}
#[derive(Clone, Debug, PartialEq)]
pub struct LineChartAnnotation {
pub id: String,
pub label: String,
pub value: ChartX,
pub axis: LineChartAnnotationAxis,
pub tone: Option<ChartTone>,
}
impl LineChartAnnotation {
pub fn y(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
Self {
id: id.into(),
label: label.into(),
value: ChartX::Number(value),
axis: LineChartAnnotationAxis::Y,
tone: None,
}
}
pub fn x(id: impl Into<String>, label: impl Into<String>, value: impl Into<ChartX>) -> Self {
Self {
id: id.into(),
label: label.into(),
value: value.into(),
axis: LineChartAnnotationAxis::X,
tone: None,
}
}
#[must_use]
pub fn with_tone(mut self, tone: ChartTone) -> Self {
self.tone = Some(tone);
self
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct AnnotationMark {
pub(crate) annotation: LineChartAnnotation,
pub(crate) coordinate: f64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct ChartRect {
pub(crate) height: f64,
pub(crate) width: f64,
pub(crate) x: f64,
pub(crate) y: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LineChartModel {
pub(crate) annotation_marks: Vec<AnnotationMark>,
pub(crate) categories: Vec<ChartX>,
pub(crate) category_ticks: Vec<CategoryTick>,
pub(crate) clip: ChartRect,
pub(crate) domain: ChartDomain,
pub(crate) geometries: Vec<LineGeometry>,
pub(crate) height: f64,
pub(crate) inset: f64,
pub(crate) padding_bottom: f64,
pub(crate) padding_left: f64,
pub(crate) padding_right: f64,
pub(crate) padding_top: f64,
pub(crate) positions: Vec<f64>,
pub(crate) series: Vec<ChartSeries>,
pub(crate) tick_labels: Vec<String>,
pub(crate) ticks: Vec<f64>,
pub(crate) width: f64,
}
const LINE_PADDING_TOP: f64 = 16.0;
const LINE_ANNOTATION_LABEL_SPACE: f64 = 16.0;
const LINE_PADDING_RIGHT: f64 = 24.0;
const LINE_PADDING_BOTTOM: f64 = 44.0;
const LINE_PLOT_INSET: f64 = 8.0;
const LINE_MARKER_ALLOWANCE: f64 = 6.0;
pub(crate) const COMPACT_AXIS_LABEL_SIZE: f64 = 22.0;
#[derive(Clone, Default)]
pub(crate) struct LineChartModelOptions<'a> {
pub(crate) annotations: &'a [LineChartAnnotation],
pub(crate) domain: Option<ChartBounds>,
pub(crate) format_category: Option<&'a Callback<ChartX, String>>,
pub(crate) format_value: Option<&'a Callback<f64, String>>,
pub(crate) height: Option<f64>,
pub(crate) reference_value: Option<f64>,
pub(crate) width: Option<f64>,
pub(crate) x_domain: Option<ChartBounds>,
pub(crate) x_scale: LineChartScale,
}
fn same_value_zero(a: &ChartX, b: &ChartX) -> bool {
match (a, b) {
(ChartX::Number(left), ChartX::Number(right)) => {
js_equals(*left, *right) || (left.is_nan() && right.is_nan())
}
_ => a == b,
}
}
pub(crate) fn chart_size(value: Option<f64>, fallback: f64) -> f64 {
match value {
Some(value) if value.is_finite() => value.max(240.0),
_ => fallback,
}
}
#[allow(clippy::too_many_lines)]
pub(crate) fn line_chart_model(
input: &[ChartSeries],
options: &LineChartModelOptions<'_>,
) -> LineChartModel {
let scale = options.x_scale;
let width = chart_size(options.width, 640.0);
let height = chart_size(options.height, 240.0);
let mut categories: Vec<ChartX> = chart_categories(input)
.into_iter()
.filter(|value| scale == LineChartScale::Categorical || numeric_x(value, scale).is_some())
.collect();
if scale != LineChartScale::Categorical {
categories.sort_by(|a, b| {
numeric_x(a, scale)
.unwrap_or(0.0)
.partial_cmp(&numeric_x(b, scale).unwrap_or(0.0))
.unwrap_or(std::cmp::Ordering::Equal)
});
}
let series: Vec<ChartSeries> = input
.iter()
.map(|item| align_series(item, &categories))
.collect();
let mut annotation_ids = HashSet::new();
let annotations: Vec<&LineChartAnnotation> = options
.annotations
.iter()
.filter(|annotation| annotation.value.is_axis_value())
.filter(|annotation| annotation_ids.insert(annotation.id.clone()))
.collect();
let values: Vec<Option<f64>> = series
.iter()
.flat_map(|item| item.data.iter().map(|datum| datum.y))
.chain(std::iter::once(options.reference_value))
.collect();
let domain = resolve_ordered_domain(
axis_domain(&values, None, false),
Some(axis_domain(&values, options.domain, false).into()),
);
let ticks = chart_ticks(domain);
let tick_labels = format_ticks(&ticks, options.format_value);
let has_x_annotation = annotations
.iter()
.any(|annotation| annotation.axis == LineChartAnnotationAxis::X);
let padding_top = LINE_PADDING_TOP
+ if has_x_annotation {
LINE_ANNOTATION_LABEL_SPACE
} else {
0.0
};
let category_labels: Vec<String> = categories
.iter()
.map(|value| category_label(&series, value, options.format_category, LabelContext::Axis))
.collect();
let edge_label_reach = |label: Option<&String>| {
(width / 5.0).min(
estimate_chart_label_width(label.map_or("", String::as_str), COMPACT_AXIS_LABEL_SIZE)
/ 2.0
- LINE_PLOT_INSET,
)
};
let padding_right = LINE_PADDING_RIGHT.max(edge_label_reach(category_labels.last()));
let padding_bottom = LINE_PADDING_BOTTOM;
let padding_left = (width - padding_right - 40.0).min(
40f64
.max(axis_padding(
&tick_labels,
0.0,
Some(COMPACT_AXIS_LABEL_SIZE),
))
.max(edge_label_reach(category_labels.first())),
);
let plot_right = width - padding_right;
let plot_bottom = height - padding_bottom;
let inset = LINE_PLOT_INSET.min((plot_right - padding_left).max(0.0) / 4.0);
let point_start = padding_left + inset;
let point_end = plot_right - inset;
let numeric: Vec<Option<f64>> = categories
.iter()
.filter_map(|value| {
(scale != LineChartScale::Categorical)
.then(|| numeric_x(value, scale))
.flatten()
.map(Some)
})
.collect();
let x_domain = resolve_ordered_domain(chart_domain(numeric, false), options.x_domain);
let category_count = categories.len();
let position_for = |value: &ChartX| -> Option<f64> {
if scale != LineChartScale::Categorical {
return numeric_x(value, scale)
.map(|number| scale_value(number, x_domain, point_start, point_end));
}
let index = categories
.iter()
.position(|category| same_value_zero(category, value))?;
#[allow(clippy::cast_precision_loss)]
let ratio = if category_count == 1 {
0.5
} else {
index as f64 / category_count.saturating_sub(1).max(1) as f64
};
Some(point_start + ratio * (point_end - point_start))
};
let positions: Vec<f64> = categories
.iter()
.map(|value| position_for(value).unwrap_or(point_start))
.collect();
let geometries = series
.iter()
.map(|item| {
let geometry_options = LineGeometryOptions {
domain: Some(domain.into()),
height,
include_zero: false,
inset: Some(inset),
padding_bottom,
padding_left,
padding_right,
padding_top,
width,
x_domain: Some(x_domain.into()),
x_scale: scale,
};
line_geometry(&item.data, geometry_options)
})
.collect();
let visible: Vec<(usize, f64)> = positions
.iter()
.enumerate()
.filter(|(_, position)| **position >= padding_left && **position <= plot_right)
.map(|(index, position)| (index, *position))
.collect();
let visible_labels: Vec<&str> = visible
.iter()
.map(|(index, _)| category_labels[*index].as_str())
.collect();
let visible_positions: Vec<f64> = visible.iter().map(|(_, position)| *position).collect();
let category_ticks = category_ticks(
&visible_labels,
CategoryTickOptions::new(padding_left, plot_right)
.bounds(0.0, width)
.maximum_font_size(COMPACT_AXIS_LABEL_SIZE)
.positions(&visible_positions),
)
.into_iter()
.map(|tick| CategoryTick {
index: visible
.get(tick.index)
.map_or(tick.index, |(index, _)| *index),
..tick
})
.collect();
let annotation_marks = annotations
.into_iter()
.filter_map(|annotation| {
let coordinate = match annotation.axis {
LineChartAnnotationAxis::X => position_for(&annotation.value)?,
LineChartAnnotationAxis::Y => match annotation.value {
ChartX::Number(value) if value.is_finite() => {
scale_value(value, domain, plot_bottom, padding_top)
}
_ => return None,
},
};
let in_bounds = match annotation.axis {
LineChartAnnotationAxis::X => {
coordinate >= padding_left && coordinate <= plot_right
}
LineChartAnnotationAxis::Y => {
coordinate >= padding_top && coordinate <= plot_bottom
}
};
in_bounds.then(|| AnnotationMark {
annotation: annotation.clone(),
coordinate,
})
})
.collect();
let marker_allowance = LINE_MARKER_ALLOWANCE.min(padding_top);
let clip = ChartRect {
height: (plot_bottom - padding_top).max(0.0) + marker_allowance * 2.0,
width: (plot_right - padding_left).max(0.0),
x: padding_left,
y: padding_top - marker_allowance,
};
LineChartModel {
annotation_marks,
categories,
category_ticks,
clip,
domain,
geometries,
height,
inset,
padding_bottom,
padding_left,
padding_right,
padding_top,
positions,
series,
tick_labels,
ticks,
width,
}
}
#[cfg(test)]
mod tests {
use super::{
BarChartLayout, BarChartOrientation, BarGeometryOptions, ChartRect, HeatmapColorScale,
HeatmapDatum, LineChartAnnotation, LineChartModelOptions, LineChartScale,
LineGeometryOptions, Margin, PieChartVariant, PlotFrame, RangeChartDatum,
ScatterChartReference, ScatterChartScale, bar_geometry, heatmap_color, heatmap_model,
line_chart_model, line_geometry, numeric_x, parse_iso_timestamp, pie_geometry,
range_geometry, scatter_geometry, scatter_references,
};
use crate::charts::model::{ChartBounds, ChartDatum, ChartDomain, ChartSeries, ChartX};
fn uniform(padding: f64) -> Margin {
Margin {
bottom: padding,
left: padding,
right: padding,
top: padding,
}
}
fn react_frame() -> Margin {
Margin {
top: 16.0,
right: 24.0,
..uniform(44.0)
}
}
fn sparkline(values: &[f64]) -> super::LineGeometry {
let data: Vec<ChartDatum> = values
.iter()
.enumerate()
.map(|(index, value)| ChartDatum::new(i32::try_from(index).unwrap_or(0), *value))
.collect();
line_geometry(&data, LineGeometryOptions::new(120.0, 40.0, 3.0))
}
#[test]
fn line_paths_use_fixed_coordinates_and_break_at_gaps() {
let geometry = sparkline(&[1.0, 3.0, 2.0]);
assert_eq!(
geometry.path,
"M 3.000 37.000 L 60.000 3.000 L 117.000 20.000"
);
let data = vec![
ChartDatum::new("a", 1.0),
ChartDatum::missing("b"),
ChartDatum::new("c", f64::NAN),
ChartDatum::new("d", 2.0),
ChartDatum::new("e", 4.0),
];
let gapped = line_geometry(&data, LineGeometryOptions::new(100.0, 100.0, 4.0));
assert_eq!(gapped.path.matches('M').count(), 2);
assert_eq!(gapped.area_paths.len(), 2);
assert_eq!(gapped.points.len(), 3);
}
#[test]
fn line_edge_cases_stay_finite() {
assert_eq!(sparkline(&[]).path, "");
let single = sparkline(&[5.0]);
assert_eq!(single.path, "M 60.000 20.000");
let negative = sparkline(&[-4.0, -1.0]);
assert!(negative.points.iter().all(|point| point.y.is_finite()));
let flat = sparkline(&[2.0, 2.0, 2.0]);
assert!(
flat.points
.iter()
.all(|point| (point.y - 20.0).abs() < 1e-9)
);
}
#[test]
fn bars_stack_positive_and_negative_values() {
let series = vec![
ChartSeries::new(
"a",
"A",
[ChartDatum::new("x", 4.0), ChartDatum::new("y", -2.0)],
),
ChartSeries::new(
"b",
"B",
[ChartDatum::new("x", 6.0), ChartDatum::missing("y")],
),
];
let grouped = bar_geometry(&series, &BarGeometryOptions::default());
assert_eq!(grouped.marks.len(), 3);
assert_eq!(grouped.domain, ChartDomain::new(-2.0, 6.0));
assert_eq!(grouped.ticks, vec![-2.0, 0.0, 2.0, 4.0, 6.0]);
assert_eq!(grouped.tick_labels, ["-2", "0", "2", "4", "6"]);
let stacked = bar_geometry(
&series,
&BarGeometryOptions {
layout: BarChartLayout::Stacked,
..BarGeometryOptions::default()
},
);
assert_eq!(stacked.domain, ChartDomain::new(-5.0, 10.0));
assert_eq!(stacked.ticks, vec![-5.0, 0.0, 5.0, 10.0]);
let horizontal = bar_geometry(
&series,
&BarGeometryOptions {
orientation: BarChartOrientation::Horizontal,
..BarGeometryOptions::default()
},
);
assert!((horizontal.margin.left - 112.0).abs() < 1e-9);
assert_eq!(bar_geometry(&[], &BarGeometryOptions::default()).marks, []);
}
#[test]
fn bars_round_automatic_domains_and_keep_requested_ones() {
let series = vec![ChartSeries::new(
"downloads",
"Downloads",
[ChartDatum::new("Lumen", 18_420.0)],
)];
let bars = bar_geometry(
&series,
&BarGeometryOptions {
orientation: BarChartOrientation::Horizontal,
..BarGeometryOptions::default()
},
);
assert_eq!(bars.domain, ChartDomain::new(0.0, 20_000.0));
assert_eq!(bars.ticks, vec![0.0, 5_000.0, 10_000.0, 15_000.0, 20_000.0]);
assert_eq!(bars.tick_labels, ["0", "5K", "10K", "15K", "20K"]);
let exact = bar_geometry(
&series,
&BarGeometryOptions {
domain: Some(ChartBounds::new(0.0, 18_420.0)),
..BarGeometryOptions::default()
},
);
assert_eq!(exact.domain, ChartDomain::new(0.0, 18_420.0));
}
#[test]
fn pie_slices_cover_the_circle_and_skip_invalid_values() {
let data = vec![
ChartDatum::new("a", 1.0),
ChartDatum::new("b", -3.0),
ChartDatum::new("c", f64::INFINITY),
ChartDatum::new("d", 3.0),
];
let geometry = pie_geometry(&data, PieChartVariant::Donut);
assert_eq!(geometry.slices.len(), 2);
assert!((geometry.total - 4.0).abs() < 1e-12);
assert!(
geometry.slices[0]
.path
.starts_with("M 160.000 12.000 A 148.000 148.000 0 0 1")
);
let full = pie_geometry(&[ChartDatum::new("only", 2.0)], PieChartVariant::Pie);
assert_eq!(
full.slices[0].path,
"M 160.000 12.000 A 148.000 148.000 0 1 1 160.000 308.000 A 148.000 148.000 0 1 1 160.000 12.000 Z"
);
assert_eq!(pie_geometry(&[], PieChartVariant::Pie).slices, []);
}
#[test]
fn scatter_rejects_invalid_domains_instead_of_panicking() {
let series = vec![ChartSeries::new(
"a",
"A",
[ChartDatum::new(1, 2.0), ChartDatum::new(10, 4.0)],
)];
let padding = uniform(44.0);
assert!(
scatter_geometry(
&series,
ScatterChartScale::Linear,
None,
None,
padding,
None,
None,
)
.is_some()
);
let log = scatter_geometry(
&series,
ScatterChartScale::Log,
None,
None,
padding,
None,
None,
);
assert!(
log.is_some_and(|geometry| geometry.domain == ChartDomain::new(1.0, 5.0)
&& (geometry.x_domain.min - 0.913_981_699_465_490_5).abs() < 1e-12)
);
assert!(
scatter_geometry(
&series,
ScatterChartScale::Linear,
None,
Some(ChartBounds::new(5.0, 1.0)),
padding,
None,
None,
)
.is_none()
);
assert!(
scatter_geometry(
&series,
ScatterChartScale::Log,
Some(ChartBounds::new(-1.0, 10.0)),
None,
padding,
None,
None,
)
.is_none()
);
let empty = scatter_geometry(
&[],
ScatterChartScale::Linear,
None,
None,
padding,
None,
None,
);
assert!(empty.is_some_and(|geometry| geometry.points.is_empty()));
}
#[test]
fn scatter_domains_end_on_ticks_and_share_the_plot_with_references() {
let cohorts = vec![ChartSeries::new(
"cohorts",
"Cohorts",
[
ChartDatum::new(18, 12.0).with_size(44.0),
ChartDatum::new(91, 84.0).with_size(30.0),
],
)];
let nice = scatter_geometry(
&cohorts,
ScatterChartScale::Linear,
None,
None,
uniform(44.0),
None,
None,
);
assert!(
nice.is_some_and(|geometry| geometry.domain == ChartDomain::new(0.0, 100.0)
&& geometry.x_domain == ChartDomain::new(0.0, 100.0))
);
let series = vec![ChartSeries::new(
"a",
"A",
[ChartDatum::new(0, 0.0), ChartDatum::new(100, 100.0)],
)];
let Some(geometry) = scatter_geometry(
&series,
ScatterChartScale::Linear,
Some(ChartBounds::new(0.0, 100.0)),
Some(ChartBounds::new(0.0, 100.0)),
Margin {
top: 16.0,
..uniform(44.0)
},
None,
None,
) else {
panic!("valid scatter domains");
};
let goal = ScatterChartReference {
id: "goal".into(),
label: "Goal".into(),
y: Some(100.0),
..ScatterChartReference::default()
};
let references = scatter_references(&[goal], &geometry, ScatterChartScale::Linear);
assert_eq!(
geometry.plot,
PlotFrame {
bottom: 276.0,
left: 44.0,
right: 596.0,
top: 16.0,
}
);
assert_eq!(
geometry
.points
.iter()
.map(|point| (point.x, point.y))
.collect::<Vec<_>>(),
[(44.0, 276.0), (596.0, 16.0)]
);
assert_eq!(
references
.iter()
.map(|reference| (reference.x1, reference.x2, reference.y1, reference.y2))
.collect::<Vec<_>>(),
[(44.0, 596.0, 16.0, 16.0)]
);
}
#[test]
fn heatmaps_keep_the_first_cell_and_mix_colors() {
let data = vec![
HeatmapDatum::new("Mon", 1, 2.0),
HeatmapDatum::new("Mon", 1, 9.0),
HeatmapDatum::new("Tue", 1, None),
HeatmapDatum::new("Tue", 2, -1.0),
];
let model = heatmap_model(&data, HeatmapColorScale::Sequential, 0.0, None);
assert_eq!(model.cells.len(), 3);
assert_eq!(model.domain, ChartDomain::new(-1.0, 2.0));
let diverging = heatmap_model(&data, HeatmapColorScale::Diverging, 0.0, None);
assert_eq!(diverging.domain, ChartDomain::new(-2.0, 2.0));
assert_eq!(
heatmap_color(
Some(2.0),
ChartDomain::new(0.0, 4.0),
HeatmapColorScale::Sequential,
0.0
),
"color-mix(in srgb, hsl(var(--chart-sequential-high)) 50%, hsl(var(--chart-sequential-low)))"
);
assert_eq!(
heatmap_color(
None,
ChartDomain::new(0.0, 4.0),
HeatmapColorScale::Sequential,
0.0
),
"hsl(var(--surface-muted))"
);
let invalid = heatmap_model(
&[HeatmapDatum::new(f64::NAN, 1, 1.0)],
HeatmapColorScale::Sequential,
0.0,
None,
);
assert_eq!(invalid.cells, []);
}
#[test]
fn ranges_break_on_missing_bounds() {
let data = vec![
RangeChartDatum::new("a", 1.0, 3.0),
RangeChartDatum::new("b", None, 3.0),
RangeChartDatum::new("c", 2.0, 5.0),
];
let geometry = range_geometry(&data, uniform(44.0), 640.0, 320.0, None, None);
assert_eq!(geometry.points.len(), 2);
assert_eq!(geometry.area_path.matches('Z').count(), 2);
assert_eq!(geometry.domain, ChartDomain::new(1.0, 5.0));
assert_eq!(geometry.ticks, vec![1.0, 2.0, 3.0, 4.0, 5.0]);
assert_eq!(
range_geometry(&[], uniform(44.0), 640.0, 320.0, None, None).area_path,
""
);
}
#[test]
fn ranges_inset_intervals_and_report_their_plot_frame() {
let week = [
RangeChartDatum::new("Mon", 14.0, 24.0),
RangeChartDatum::new("Wed", 19.0, 31.0),
RangeChartDatum::new("Sun", 12.0, 24.0),
];
let geometry = range_geometry(&week, uniform(44.0), 640.0, 320.0, None, None);
assert_eq!(geometry.domain, ChartDomain::new(10.0, 35.0));
assert_eq!(geometry.ticks, vec![10.0, 15.0, 20.0, 25.0, 30.0, 35.0]);
let pair = [
RangeChartDatum::new("Mon", 14.0, 24.0),
RangeChartDatum::new("Sun", 13.0, 24.0),
];
let geometry = range_geometry(
&pair,
Margin {
top: 16.0,
..uniform(44.0)
},
640.0,
320.0,
None,
None,
);
assert_eq!(
geometry.plot,
PlotFrame {
bottom: 276.0,
left: 44.0,
right: 596.0,
top: 16.0,
}
);
assert_eq!(
geometry
.points
.iter()
.map(|point| point.x)
.collect::<Vec<_>>(),
[52.0, 588.0]
);
assert!(geometry.points[0].high >= 16.0);
assert_eq!(
range_geometry(&pair, react_frame(), 640.0, 320.0, None, None).plot,
PlotFrame {
bottom: 276.0,
left: 44.0,
right: 616.0,
top: 16.0,
}
);
}
#[test]
fn line_insets_are_capped_to_keep_usable_width() {
let data = [ChartDatum::new("A", 1.0), ChartDatum::new("B", 2.0)];
let x = |inset: Option<f64>| {
let options = LineGeometryOptions {
inset,
..LineGeometryOptions::new(40.0, 100.0, 0.0)
};
line_geometry(&data, options)
.points
.iter()
.map(|point| point.x)
.collect::<Vec<_>>()
};
assert_eq!(x(Some(1_000.0)), [10.0, 30.0]);
assert_eq!(x(Some(f64::NAN)), [0.0, 40.0]);
assert_eq!(x(None), [0.0, 40.0]);
}
#[test]
fn line_models_reserve_room_for_centred_edge_labels_and_markers() {
let series = vec![ChartSeries::new(
"a",
"A",
[
ChartDatum::new("Mon", 18_420.0),
ChartDatum::new("Tue", 9_870.0),
ChartDatum::new("September 30", 6_320.0),
],
)];
let annotations = [
LineChartAnnotation::x("n", "Launch", "Tue"),
LineChartAnnotation::x("n", "Duplicate", "Mon"),
LineChartAnnotation::y("g", "Goal", 15_000.0),
];
let model = line_chart_model(
&series,
&LineChartModelOptions {
annotations: &annotations,
..LineChartModelOptions::default()
},
);
assert!((model.padding_right - 76.0).abs() < 1e-12);
assert!((model.padding_left - 58.0).abs() < 1e-12);
assert!((model.padding_top - 32.0).abs() < 1e-12);
assert!((model.padding_bottom - 44.0).abs() < 1e-12);
assert!((model.inset - 8.0).abs() < 1e-12);
assert_eq!(
model.clip,
ChartRect {
height: 176.0,
width: 506.0,
x: 58.0,
y: 26.0,
}
);
assert_eq!(model.positions, [66.0, 311.0, 556.0]);
assert_eq!(model.domain, ChartDomain::new(5_000.0, 20_000.0));
assert_eq!(model.tick_labels, ["5K", "10K", "15K", "20K"]);
assert_eq!(
model
.category_ticks
.iter()
.map(|tick| (tick.index, tick.position))
.collect::<Vec<_>>(),
[(0, 66.0), (1, 311.0), (2, 556.0)]
);
assert_eq!(
model
.annotation_marks
.iter()
.map(|mark| mark.annotation.id.as_str())
.collect::<Vec<_>>(),
["n", "g"]
);
assert!((model.annotation_marks[1].coordinate - 86.666_666_666_666_67).abs() < 1e-9);
assert!((model.geometries[0].points[0].y - 49.274_666_666_666_66).abs() < 1e-9);
let empty = line_chart_model(&[], &LineChartModelOptions::default());
assert!((empty.padding_right - 24.0).abs() < 1e-12);
assert!((empty.padding_top - 16.0).abs() < 1e-12);
assert_eq!(empty.tick_labels, ["0", "0.2", "0.4", "0.6", "0.8", "1"]);
assert_eq!(
empty.clip,
ChartRect {
height: 192.0,
width: 558.0,
x: 58.0,
y: 10.0,
}
);
}
#[test]
fn line_models_label_only_categories_inside_an_explicit_viewport() {
let series = vec![ChartSeries::new(
"a",
"A",
[
ChartDatum::new(1, 2.0),
ChartDatum::new(5, 3.0),
ChartDatum::new(9, 4.0),
],
)];
let model = line_chart_model(
&series,
&LineChartModelOptions {
domain: Some(ChartBounds::min(0.0)),
x_domain: Some(ChartBounds::new(4.0, 10.0)),
x_scale: LineChartScale::Linear,
..LineChartModelOptions::default()
},
);
assert_eq!(model.domain, ChartDomain::new(0.0, 4.0));
assert!((model.positions[0] + 232.0).abs() < 1e-9);
assert_eq!(
model
.category_ticks
.iter()
.map(|tick| (tick.index, tick.label.as_str()))
.collect::<Vec<_>>(),
[(1, "5"), (2, "9")]
);
}
#[test]
fn iso_dates_parse_strictly_in_linear_time() {
assert_eq!(parse_iso_timestamp("1970-01-01"), Some(0.0));
assert_eq!(parse_iso_timestamp("2024-02-29"), Some(1_709_164_800_000.0));
assert_eq!(parse_iso_timestamp("2023-02-29"), None);
assert_eq!(
parse_iso_timestamp("2024-01-01T12:30:00Z"),
Some(1_704_112_200_000.0)
);
assert_eq!(
parse_iso_timestamp("2024-01-01T12:30+02:00"),
Some(1_704_105_000_000.0)
);
assert_eq!(parse_iso_timestamp("2024"), Some(1_704_067_200_000.0));
assert_eq!(parse_iso_timestamp("2024-13-01"), None);
assert_eq!(parse_iso_timestamp("Jan 1"), None);
assert_eq!(parse_iso_timestamp(&"9".repeat(100_000)), None);
assert_eq!(
numeric_x(&ChartX::from(" 42 "), LineChartScale::Linear),
Some(42.0)
);
assert_eq!(numeric_x(&ChartX::from(""), LineChartScale::Linear), None);
assert_eq!(
numeric_x(&ChartX::from("Infinity"), LineChartScale::Linear),
None
);
assert_eq!(
numeric_x(&ChartX::from(f64::NAN), LineChartScale::Time),
None
);
}
}