meo-canvas 0.2.1

Describe a picture, get image bytes back. CSS flexbox, grid and block layout on a Skia backend.
Documentation
//! Where a chart's marks go, as fractions of the plot.
//!
//! # One specification, two implementations
//!
//! **A port of `packages/meo-canvas/src/chart.ts`**, which is the
//! specification; `tests/assets/chart/geometry.tsv` makes it checkable.
//! Nothing external can referee a chart -- Chrome has none -- so an
//! independent derivation here would be one more set of numbers free to drift.
//!
//! # `f64`, and no fused multiply-add
//!
//! Both surfaces compute these and the two are compared, so this is the same
//! case as `animate`: **agreement is the objective and accuracy is not.**

#![expect(
    clippy::suboptimal_flops,
    reason = "compared against the TypeScript surface's own numbers; a fused \
              multiply-add rounds once where JavaScript rounds twice."
)]

use crate::Error;

/// How many bands a plot's gridlines divide it into.
pub const GRID_DIVISIONS: u32 = 5;

/// The share of a group's width left empty between groups.
///
/// Half at each end, so a group's bars occupy the middle 80% of their slot.
pub const BAR_GROUP_SPACING: f64 = 0.2;

/// The colours a series takes in order when it names none.
const PALETTE: [&str; 8] = [
    "#4e79a7", "#f28e2c", "#e15759", "#76b7b2", "#59a14f", "#edc949",
    "#af7aa1", "#ff9da7",
];

/// The colour a series takes when it names none.
#[must_use]
pub fn series_color(index: usize, given: Option<&str>) -> String {
    given.map_or_else(
        || PALETTE[index % PALETTE.len()].to_owned(),
        ToOwned::to_owned,
    )
}

/// Where each gridline falls, as a fraction from the top of the plot.
///
/// **`divisions + 1` fractions, and the last one is never seen.** A fraction
/// of `1.0` puts a one-pixel rule with its *top* on the plot's bottom edge, so
/// five divisions show **five** lines rather than six. Kept because the other
/// surface emits it too -- **a test that counts six has counted emitted nodes,
/// not drawn lines.**
#[must_use]
pub fn grid_lines(divisions: u32) -> Vec<f64> {
    (0..=divisions)
        .map(|line| f64::from(line) / f64::from(divisions))
        .collect()
}

/// One bar's place in the plot, as fractions of it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Bar {
    /// Distance from the plot's left edge.
    pub x: f64,
    /// How wide the bar is.
    pub width: f64,
    /// How tall, as a share of the plot's height.
    pub height: f64,
}

/// Where every bar of a cartesian chart sits.
///
/// # Errors
///
/// Returns [`Error::Chart`] for a negative value: bars rise from the plot's
/// floor, and there is no zero baseline to draw one below.
///
/// # Panics
///
/// Never: `labels` and `series` are counts and the indices are drawn from
/// them.
pub fn bar_layout(
    labels: usize,
    series: usize,
    values: &[Vec<f64>],
    max_value: f64,
) -> Result<Vec<Vec<Bar>>, Error> {
    if values.iter().flatten().any(|value| *value < 0.0) {
        return Err(Error::Chart("a chart cannot draw a negative value"));
    }

    #[expect(
        clippy::cast_precision_loss,
        reason = "a label or series count past 2^53 is not a chart"
    )]
    let (labels_f, series_f) = (labels as f64, series as f64);
    let group_width = 1.0 / labels_f;
    let spacing = group_width * BAR_GROUP_SPACING;
    let width = (group_width - spacing) / series_f;

    Ok((0..labels)
        .map(|index| {
            (0..series)
                .map(|s| {
                    #[expect(
                        clippy::cast_precision_loss,
                        reason = "as the counts above"
                    )]
                    let (index_f, s_f) = (index as f64, s as f64);
                    Bar {
                        x: index_f * group_width + spacing / 2.0 + s_f * width,
                        width,
                        // Zero rather than `0 / 0`: an all-zero chart would
                        // reach layout as `NaN`, an absent height, and draw
                        // nothing at all.
                        height: if max_value == 0.0 {
                            0.0
                        } else {
                            values
                                .get(s)
                                .and_then(|row| row.get(index))
                                .copied()
                                .unwrap_or(0.0)
                                / max_value
                        },
                    }
                })
                .collect()
        })
        .collect())
}

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

/// Where one slice begins and ends, in radians clockwise from twelve.
#[must_use]
pub fn slice_angles(values: &[f64]) -> Vec<(f64, f64)> {
    let total: f64 = values.iter().sum();
    // From `-PI / 2` -- twelve o'clock -- sweeping clockwise.
    let mut cursor = -std::f64::consts::PI / 2.0;
    values
        .iter()
        .map(|value| {
            // A total of zero has no angles to divide: every slice is empty
            // rather than `NaN`, for the same reason a zero maximum gives a
            // zero height.
            let sweep = if total == 0.0 {
                0.0
            } else {
                (value / total) * std::f64::consts::PI * 2.0
            };
            let slice = (cursor, cursor + sweep);
            cursor += sweep;
            slice
        })
        .collect()
}

/// One slice as SVG path data, in the pie's own hundred-unit space.
///
/// **The string is compared, not the numbers**, so it is built as `chart.ts`
/// builds it: four decimals on every computed coordinate, and the centre
/// printed bare because it is a constant. A path built another way diverges
/// in bytes with no numeric difference behind it.
#[must_use]
pub fn slice_path(start: f64, end: f64, outer: f64, inner: f64) -> String {
    let centre = PIE_SPACE / 2.0;
    let at = |radius: f64, angle: f64| {
        format!(
            "{:.4} {:.4}",
            centre + angle.cos() * radius,
            centre + angle.sin() * radius
        )
    };
    // A sweep past half a turn needs SVG's large-arc flag, or the renderer
    // draws the short way round and a 300-degree slice comes out as 60.
    let large = i32::from(end - start > std::f64::consts::PI);

    if inner <= 0.0 {
        return format!(
            "M {centre} {centre} L {} A {outer} {outer} 0 {large} 1 {} Z",
            at(outer, start),
            at(outer, end)
        );
    }
    format!(
        "M {} A {outer} {outer} 0 {large} 1 {} L {} A {inner} {inner} 0 {large} 0 {} Z",
        at(outer, start),
        at(outer, end),
        at(inner, end),
        at(inner, start)
    )
}

/// The space a line plot is drawn in.
///
/// A hundred by a hundred **stretched** rather than fitted: a line plot must
/// fill its box, and `meet` would letterbox it. The numbers are arbitrary --
/// only the ratios in the path matter, since each axis is scaled onto the node
/// independently.
pub const LINE_SPACE: f64 = 100.0;

/// One point of a line series, as fractions of the plot.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Point {
    /// Distance from the plot's left edge.
    pub x: f64,
    /// Distance from the plot's top edge.
    pub y: f64,
}

/// Where each point of a line series sits.
///
/// **Points span edge to edge where bars are centred in slots**: the step is
/// `1 / (labels - 1)`, so the first and last points sit on the plot's edges.
/// A single label has no span to divide, so its point sits at the left edge.
#[must_use]
pub fn line_points(
    labels: usize,
    values: &[f64],
    max_value: f64,
) -> Vec<Point> {
    #[expect(
        clippy::cast_precision_loss,
        reason = "a label count past 2^53 is not a chart"
    )]
    let spacing = if labels > 1 {
        1.0 / (labels - 1) as f64
    } else {
        1.0
    };
    values
        .iter()
        .enumerate()
        .map(|(index, value)| {
            #[expect(
                clippy::cast_precision_loss,
                reason = "as the count above"
            )]
            let index = index as f64;
            Point {
                x: index * spacing,
                // A zero maximum has no share to take, and every point sits on
                // the floor rather than at `NaN` -- the same reason a zero
                // maximum gives a bar no height.
                y: if max_value == 0.0 {
                    1.0
                } else {
                    1.0 - value / max_value
                },
            }
        })
        .collect()
}

/// One series as SVG path data, in the line plot's own hundred-unit space.
///
/// **The string is matched, not the numbers**, for the reason
/// [`slice_path`] gives.
#[must_use]
pub fn line_path(points: &[Point]) -> String {
    points
        .iter()
        .enumerate()
        .map(|(index, point)| {
            let command = if index == 0 { "M" } else { "L" };
            format!(
                "{command} {:.4} {:.4}",
                point.x * LINE_SPACE,
                point.y * LINE_SPACE
            )
        })
        .collect::<Vec<_>>()
        .join(" ")
}