#![expect(
clippy::suboptimal_flops,
reason = "the y-axis label values become strings that the other surface \
also computes, so a fused multiply-add -- rounding once where \
JavaScript rounds twice -- could change a label by a digit. \
Agreement is the objective here, as in `chart::geometry`."
)]
use std::rc::Rc;
use meo_canvas_scene::{
Length,
style::{
Dimension,
effect::Transform,
paint::{Color, ColorValue},
},
};
use crate::{
Align, Box as BoxElement, Column, Element, Error, Justify, Overflow,
PositionType, Row, Style, Styled, Text,
chart::{
frame::{LegendPosition, framed, legend},
geometry::{Bar, GRID_DIVISIONS, bar_layout, grid_lines, series_color},
},
fraction, pct, px,
unit::sides,
};
#[derive(Debug, Clone, Default)]
pub struct Dataset {
pub label: Option<String>,
pub color: Option<String>,
pub data: Vec<f64>,
}
#[derive(Debug, Clone, Default)]
pub struct Grid {
pub show: bool,
pub color: Option<String>,
}
#[derive(Debug)]
pub struct LabelItem<'a> {
pub item: &'a str,
pub index: usize,
}
#[derive(Debug)]
pub struct ValueItem {
pub item: f64,
pub index: usize,
pub dataset_index: usize,
}
#[derive(Debug)]
pub enum LegendEntry<'a> {
Series(&'a Dataset),
Slice(&'a crate::chart::pie::Slice),
}
#[derive(Debug)]
pub struct LegendItem<'a> {
pub item: LegendEntry<'a>,
pub index: usize,
pub color: &'a str,
}
pub type LabelHatch = Rc<dyn Fn(LabelItem<'_>) -> Option<Element>>;
pub type ValueHatch = Rc<dyn Fn(ValueItem) -> Option<Element>>;
pub type LegendHatch = Rc<dyn Fn(LegendItem<'_>) -> Option<Element>>;
pub type XAxisFormatter = Rc<dyn Fn(&str, usize) -> String>;
pub type YAxisFormatter = Rc<dyn Fn(f64) -> String>;
pub const DEFAULT_INNER_FRACTION: f64 = 0.6;
#[derive(Clone, Default)]
#[expect(
clippy::struct_excessive_bools,
reason = "an option bag mirroring the other surface's, one field per \
switch it has"
)]
pub struct Options {
pub show_labels: bool,
pub show_values: bool,
pub show_y_axis: bool,
pub show_legend: bool,
pub legend_position: LegendPosition,
pub grid: Grid,
pub label_font_size: Option<f32>,
pub value_font_size: Option<f32>,
pub y_axis_font_size: Option<f32>,
pub label_color: Option<Color>,
pub value_color: Option<Color>,
pub y_axis_color: Option<Color>,
pub axis_color: Option<Color>,
pub font_family: Option<String>,
pub inner_fraction: Option<f64>,
pub render_label_item: Option<LabelHatch>,
pub render_value_item: Option<ValueHatch>,
pub render_legend_item: Option<LegendHatch>,
pub x_axis_label_formatter: Option<XAxisFormatter>,
pub y_axis_label_formatter: Option<YAxisFormatter>,
}
impl core::fmt::Debug for Options {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
const fn hatch<T>(value: Option<&T>) -> &'static str {
if value.is_some() {
"Some(<fn>)"
} else {
"None"
}
}
f.debug_struct("Options")
.field("show_labels", &self.show_labels)
.field("show_values", &self.show_values)
.field("show_y_axis", &self.show_y_axis)
.field("show_legend", &self.show_legend)
.field("legend_position", &self.legend_position)
.field("grid", &self.grid)
.field("label_font_size", &self.label_font_size)
.field("value_font_size", &self.value_font_size)
.field("y_axis_font_size", &self.y_axis_font_size)
.field("label_color", &self.label_color)
.field("value_color", &self.value_color)
.field("y_axis_color", &self.y_axis_color)
.field("axis_color", &self.axis_color)
.field("font_family", &self.font_family)
.field("inner_fraction", &self.inner_fraction)
.field("render_label_item", &hatch(self.render_label_item.as_ref()))
.field("render_value_item", &hatch(self.render_value_item.as_ref()))
.field(
"render_legend_item",
&hatch(self.render_legend_item.as_ref()),
)
.field(
"x_axis_label_formatter",
&hatch(self.x_axis_label_formatter.as_ref()),
)
.field(
"y_axis_label_formatter",
&hatch(self.y_axis_label_formatter.as_ref()),
)
.finish()
}
}
const GRID_COLOR: Color = crate::hex_rgb(0xe0_e0_e0);
const TEXT_COLOR: Color = crate::hex_rgb(0x00_00_00);
const TEXT_SIZE: f32 = 12.0;
const VALUE_LIFT: f32 = 5.0;
pub fn bar(
labels: &[String],
datasets: &[Dataset],
options: &Options,
) -> Result<Element, Error> {
let values: Vec<Vec<f64>> =
datasets.iter().map(|set| set.data.clone()).collect();
let max_value = values.iter().flatten().copied().fold(0.0_f64, f64::max);
let placed = bar_layout(labels.len(), datasets.len(), &values, max_value)?;
let mut bars: Vec<Element> = Vec::new();
for (index, group) in placed.iter().enumerate() {
for (dataset, bar) in group.iter().enumerate() {
bars.push(one_bar(
*bar, index, dataset, &values, datasets, options,
)?);
}
}
let mut body: Vec<Element> = vec![plot_area(options, max_value, bars)?];
if options.show_labels {
body.push(label_strip(labels, options));
}
Ok(framed(
options,
Column::new().name("body").flex_grow(1.0).children(body),
legend(options, &series_labels(datasets))?,
"bar chart",
))
}
fn one_bar(
bar: Bar,
index: usize,
dataset: usize,
values: &[Vec<f64>],
datasets: &[Dataset],
options: &Options,
) -> Result<Element, Error> {
let colour = series_color(dataset, datasets[dataset].color.as_deref());
let value = values
.get(dataset)
.and_then(|row| row.get(index))
.copied()
.unwrap_or(0.0);
let mut drawn = BoxElement::new()
.name(format!("bar {index}.{dataset}"))
.with_style(
Style::new()
.position_type(PositionType::Absolute)
.position(sides(
None,
None,
Some(px(0.0)),
Some(fraction(bar.x)),
))
.width(fraction(bar.width))
.height(fraction(bar.height))
.background_color(
meo_canvas_core::color::parse_color_value(&colour).ok_or(
Error::Chart("a bar colour could not be read"),
)?,
),
);
if options.show_values {
drawn = drawn.children([value_label(value, index, dataset, options)]);
}
Ok(drawn)
}
fn value_label(
value: f64,
index: usize,
dataset_index: usize,
options: &Options,
) -> Element {
let drawn = options.render_value_item.as_ref().and_then(|draw| {
draw(ValueItem {
item: value,
index,
dataset_index,
})
});
BoxElement::new()
.with_style(
Style::new()
.position_type(PositionType::Absolute)
.position(sides(
None,
Some(px(0.0)),
Some(pct(100.0)),
Some(px(0.0)),
))
.margin(sides(
Dimension::Points(0.0),
Dimension::Points(0.0),
Dimension::Points(VALUE_LIFT),
Dimension::Points(0.0),
))
.align_items(Align::Center),
)
.children([drawn.unwrap_or_else(|| {
text(
&value.to_string(),
options,
options.value_font_size,
options.value_color,
)
})])
}
pub(crate) fn label_strip(labels: &[String], options: &Options) -> Element {
Row::new().name("labels").children(
labels
.iter()
.enumerate()
.map(|(index, label)| {
let drawn = options
.render_label_item
.as_ref()
.and_then(|draw| draw(LabelItem { item: label, index }));
let shown =
options.x_axis_label_formatter.as_ref().map_or_else(
|| label.clone(),
|format| format(label, index),
);
BoxElement::new()
.with_style(
Style::new()
.flex_grow(1.0)
.flex_basis(Dimension::Points(0.0))
.justify_content(Justify::Center)
.align_items(Align::Center),
)
.children([drawn.unwrap_or_else(|| {
text(
&shown,
options,
options.label_font_size,
options.label_color,
)
})])
})
.collect::<Vec<_>>(),
)
}
pub(crate) fn plot_area(
options: &Options,
max_value: f64,
bars: Vec<Element>,
) -> Result<Element, Error> {
let mut inside = grid(options)?;
inside.extend(bars);
let plot = BoxElement::new()
.name("plot")
.with_style(
Style::new()
.flex_grow(1.0)
.position_type(PositionType::Relative),
)
.children(inside);
if !options.show_y_axis {
return Ok(plot);
}
let labels: Vec<String> = grid_lines(GRID_DIVISIONS)
.into_iter()
.map(|fraction| {
let value = max_value - max_value * fraction;
options
.y_axis_label_formatter
.as_ref()
.map_or_else(|| format_number(value), |format| format(value))
})
.collect();
let widest = labels
.iter()
.fold(None::<&String>, |best, label| match best {
Some(held) if held.chars().count() >= label.chars().count() => {
Some(held)
}
_ => Some(label),
})
.cloned()
.unwrap_or_default();
let colour = options.y_axis_color.or(options.axis_color);
let mut gutter: Vec<Element> = vec![
BoxElement::new()
.name("gutter sizer")
.with_style(Style::new().height(px(0.0)).overflow(Overflow::Hidden))
.children([text(
&widest,
options,
options.y_axis_font_size,
colour,
)]),
];
for (index, label) in labels.iter().enumerate() {
let top = grid_lines(GRID_DIVISIONS)[index];
gutter.push(
BoxElement::new()
.name(format!("axis label {index}"))
.with_style(
Style::new()
.position_type(PositionType::Absolute)
.position(sides(
Some(fraction(top)),
None,
None,
Some(px(0.0)),
))
.transform(Transform {
translate_y: Length::Percent(-0.5),
..Transform::default()
}),
)
.children([text(
label,
options,
options.y_axis_font_size,
colour,
)]),
);
}
Ok(Row::new().name("plot area").flex_grow(1.0).children([
Column::new()
.name("y axis")
.position_type(PositionType::Relative)
.children(gutter),
plot,
]))
}
fn grid(options: &Options) -> Result<Vec<Element>, Error> {
if !options.grid.show {
return Ok(Vec::new());
}
let colour = match options.grid.color.as_deref() {
None => ColorValue::Rgba(GRID_COLOR),
Some(written) => meo_canvas_core::color::parse_color_value(written)
.ok_or(Error::Chart("the grid colour could not be read"))?,
};
Ok(grid_lines(GRID_DIVISIONS)
.into_iter()
.map(|at| {
BoxElement::new().name(format!("gridline {at}")).with_style(
Style::new()
.position_type(PositionType::Absolute)
.position(sides(
Some(fraction(at)),
Some(px(0.0)),
None,
Some(px(0.0)),
))
.height(px(1.0))
.background_color(colour),
)
})
.collect())
}
pub(crate) fn text(
content: &str,
options: &Options,
size: Option<f32>,
colour: Option<Color>,
) -> Element {
let mut style = Style::new()
.font_size(size.unwrap_or(TEXT_SIZE))
.color(ColorValue::Rgba(colour.unwrap_or(TEXT_COLOR)));
if let Some(family) = options.font_family.as_deref() {
style = style.font_family(family);
}
Text::new(content).with_style(style)
}
fn format_number(value: f64) -> String {
let rounded = (value * 100.0).round() / 100.0;
let text = format!("{rounded}");
text
}
pub(crate) fn series_labels(
datasets: &[Dataset],
) -> Vec<(String, String, LegendEntry<'_>)> {
datasets
.iter()
.enumerate()
.map(|(index, set)| {
(
set.label
.clone()
.unwrap_or_else(|| format!("Series {}", index + 1)),
series_color(index, set.color.as_deref()),
LegendEntry::Series(set),
)
})
.collect()
}