#![expect(
clippy::suboptimal_flops,
reason = "a slice label's position is compared against the other \
surface's byte for byte, and `mul_add` is fused -- one \
rounding where JavaScript's `0.5 + Math.cos(m) * reach` has \
two and no fused form to reach for. Clippy's `more \
accurately` is true and it is the wrong property. THE LINT DID \
NOT CHANGE, THE CODE'S OBLIGATIONS DID: this was ordinary \
arithmetic until it acquired a second implementation, which \
moved it from `paint.rs`'s category to `animate`'s without the \
line being edited. And the tempting repair is the dangerous \
one -- fusing makes `chart_agreement` fail, and regenerating \
the assets would leave a green test asserting that a fused \
Rust and an unfused JavaScript match. A re-pin is how a broken \
agreement becomes a documented one."
)]
use meo_canvas_scene::{Length, node::PathPaint, style::effect::Transform};
use crate::{
Box as BoxElement, Element, Error, Path, PositionType, Style,
chart::{
bar::{DEFAULT_INNER_FRACTION, LabelItem, LegendEntry, Options, text},
frame::{framed, legend},
geometry::{series_color, slice_angles},
},
fraction, hex_rgb, px,
unit::sides,
};
const PIE_SPACE: f64 = 100.0;
const PIE_INSET: f64 = 0.05;
const PIE_LABEL_REACH: f64 = 0.7;
const SLICE_STROKE: f32 = 2.0;
#[derive(Debug, Clone, Default)]
pub struct Slice {
pub label: String,
pub value: f64,
pub color: Option<String>,
}
pub fn pie(slices: &[Slice], options: &Options) -> Result<Element, Error> {
wedges(slices, 0.0, Kind::Pie, options)
}
pub fn doughnut(slices: &[Slice], options: &Options) -> Result<Element, Error> {
wedges(
slices,
options.inner_fraction.unwrap_or(DEFAULT_INNER_FRACTION),
Kind::Doughnut,
options,
)
}
#[derive(Clone, Copy)]
enum Kind {
Pie,
Doughnut,
}
impl Kind {
const fn name(self) -> &'static str {
match self {
Self::Pie => "pie chart",
Self::Doughnut => "doughnut chart",
}
}
}
fn wedges(
slices: &[Slice],
inner_fraction: f64,
kind: Kind,
options: &Options,
) -> Result<Element, Error> {
if slices.iter().any(|slice| slice.value < 0.0) {
return Err(Error::Chart("a chart cannot draw a negative value"));
}
let outer = (PIE_SPACE / 2.0) * (1.0 - PIE_INSET);
let inner = outer * inner_fraction;
let values: Vec<f64> = slices.iter().map(|slice| slice.value).collect();
let angles = slice_angles(&values);
let mut drawn: Vec<Element> = Vec::new();
for (index, (start, end)) in angles.iter().enumerate() {
let colour = series_color(index, slices[index].color.as_deref());
#[expect(
clippy::cast_possible_truncation,
reason = "the pie's own space, narrowed once at the style boundary"
)]
let space = PIE_SPACE as f32;
drawn.push(
Path::d(crate::chart::geometry::slice_path(
*start, *end, outer, inner,
))
.name(format!("slice {index}"))
.view_box(Some((0.0, 0.0, space, space)))
.fill(Some(PathPaint::Solid(
meo_canvas_core::color::parse_color_value(&colour)
.ok_or(Error::Chart("a slice colour could not be read"))?,
)))
.stroke(Some(PathPaint::Solid(hex_rgb(0xff_ff_ff).into())))
.line_width(SLICE_STROKE)
.with_style(
Style::new().position_type(PositionType::Absolute).position(
sides(
Some(px(0.0)),
Some(px(0.0)),
Some(px(0.0)),
Some(px(0.0)),
),
),
),
);
}
if options.show_labels {
for (index, (start, end)) in angles.iter().enumerate() {
drawn.push(slice_label(
index,
*start,
*end,
outer,
&slices[index].label,
options,
));
}
}
Ok(framed(
options,
BoxElement::new()
.name("plot")
.with_style(
Style::new()
.flex_grow(1.0)
.position_type(PositionType::Relative),
)
.children(drawn),
legend(
options,
&slices
.iter()
.enumerate()
.map(|(index, slice)| {
(
format!("{} ({})", slice.label, slice.value),
series_color(index, slice.color.as_deref()),
LegendEntry::Slice(slice),
)
})
.collect::<Vec<_>>(),
)?,
kind.name(),
))
}
fn slice_label(
index: usize,
start: f64,
end: f64,
outer: f64,
label: &str,
options: &Options,
) -> Element {
let middle = start + (end - start) / 2.0;
let reach = (outer * PIE_LABEL_REACH) / PIE_SPACE;
let (left, top) = (0.5 + middle.cos() * reach, 0.5 + middle.sin() * reach);
BoxElement::new()
.name(format!("slice label {index}"))
.with_style(
Style::new()
.position_type(PositionType::Absolute)
.position(sides(
Some(fraction(top)),
None,
None,
Some(fraction(left)),
))
.transform(Transform {
translate_x: Length::Percent(-0.5),
translate_y: Length::Percent(-0.5),
..Transform::default()
}),
)
.children([options
.render_label_item
.as_ref()
.and_then(|draw| draw(LabelItem { item: label, index }))
.unwrap_or_else(|| {
text(
label,
options,
options.label_font_size,
options.label_color,
)
})])
}