meo-canvas 0.2.1

Describe a picture, get image bytes back. CSS flexbox, grid and block layout on a Skia backend.
Documentation
//! A pie or doughnut, drawn as stacked paths in one square space.
//!
//! **Every slice is drawn in the same square and stacked**, so each one's
//! viewBox is the whole drawing rather than its own bounds -- which is what
//! keeps them concentric. `xMidYMid meet` keeps the pie circular in any box.

#![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,
};

/// The space a pie is drawn in, before it is scaled into its box.
const PIE_SPACE: f64 = 100.0;

/// How much of the radius the inset around a pie takes.
///
/// A proportion rather than pixels: the drawing is authored once and scaled,
/// so a pixel is not a fixed quantity inside it.
const PIE_INSET: f64 = 0.05;

/// How far along the radius a slice's label sits.
const PIE_LABEL_REACH: f64 = 0.7;

/// The white stroke around every slice, in pixels, which separates two slices
/// of similar colour.
const SLICE_STROKE: f32 = 2.0;

/// One wedge of a pie.
#[derive(Debug, Clone, Default)]
pub struct Slice {
    /// What the label and the legend call it.
    pub label: String,
    /// How much of the whole it is.
    pub value: f64,
    /// Its colour. Taken from the palette in order when absent.
    pub color: Option<String>,
}

/// A pie, with no hole: [`Options::inner_fraction`] is ignored here, and
/// [`doughnut`] is the kind that reads it.
///
/// # Errors
///
/// Returns [`Error::Chart`] for a negative value, as the bar chart does and
/// for the same reason, and for a slice colour that cannot be read.
pub fn pie(slices: &[Slice], options: &Options) -> Result<Element, Error> {
    // A pie has no hole, and `inner_fraction` is a doughnut's option -- the
    // other surface passes a literal `0` down this path and reads the option
    // only down the other one.
    wedges(slices, 0.0, Kind::Pie, options)
}

/// A doughnut: a pie with a hole of [`Options::inner_fraction`], or of
/// [`DEFAULT_INNER_FRACTION`] when that is unset.
///
/// **Split from [`pie`] because the default belongs to one kind and not the
/// other**: a single shared function defaulting it would turn every pie into a
/// doughnut.
///
/// # Errors
///
/// As [`pie`].
pub fn doughnut(slices: &[Slice], options: &Options) -> Result<Element, Error> {
    wedges(
        slices,
        options.inner_fraction.unwrap_or(DEFAULT_INNER_FRACTION),
        Kind::Doughnut,
        options,
    )
}

/// Which of the two this is, as the caller declared it.
///
/// Declared rather than read off the hole: a doughnut with a zero
/// `inner_fraction` is still a doughnut, and its encoded node name says so.
#[derive(Clone, Copy)]
enum Kind {
    Pie,
    Doughnut,
}

impl Kind {
    /// The chart's own node name.
    const fn name(self) -> &'static str {
        match self {
            Self::Pie => "pie chart",
            Self::Doughnut => "doughnut chart",
        }
    }
}

/// What both kinds draw, given the hole they differ by.
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)| {
                    // A slice's legend entry carries its value beside its
                    // label, unlike a series'.
                    (
                        format!("{} ({})", slice.label, slice.value),
                        series_color(index, slice.color.as_deref()),
                        LegendEntry::Slice(slice),
                    )
                })
                .collect::<Vec<_>>(),
        )?,
        kind.name(),
    ))
}

/// A slice's label, seven tenths of the way along its own middle angle.
///
/// **In percentages of the plot rather than pixels**, since the drawing is
/// square and centred and the label rides with it.
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)),
                ))
                // Half its own width and height back from the point, so the
                // label centres on it rather than hanging down and right.
                .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,
                )
            })])
}