lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! Datum activation: the typed detail a chart reports when a mark or its action button is
//! activated, serialized exactly like lumen-core's `data-ui-chart-datum` attribute.

use super::format::{json_number, json_string};
use super::model::{ChartDatum, ChartLabels, ChartX};

/// What a chart reports through `on_datum_activate`: data identities and values, never pixel
/// coordinates.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ChartDatumActivation {
    /// A point of a series chart (bar, line, pie, scatter, combo).
    Series {
        /// The series id.
        series_id: String,
        /// The point's x identity.
        x: ChartX,
        /// The point's value.
        y: f64,
        /// The point's id, when it has one.
        datum_id: Option<String>,
    },
    /// A heatmap cell.
    Heatmap {
        /// The column identity.
        x: ChartX,
        /// The row identity.
        y: ChartX,
        /// The cell value.
        value: f64,
        /// The cell's id, when it has one.
        datum_id: Option<String>,
    },
    /// A range chart interval.
    Range {
        /// The x identity.
        x: ChartX,
        /// The lower value.
        low: f64,
        /// The upper value.
        high: f64,
        /// The interval's id, when it has one.
        datum_id: Option<String>,
    },
}

impl ChartDatumActivation {
    /// `createLumenChartDatumActivation`: `None` unless x is text or finite and y is finite.
    pub(crate) fn series(series_id: &str, datum: &ChartDatum) -> Option<Self> {
        let y = datum.y.filter(|value| value.is_finite())?;

        datum.x.is_axis_value().then(|| Self::Series {
            series_id: series_id.to_string(),
            x: datum.x.clone(),
            y,
            datum_id: datum.id.clone(),
        })
    }

    /// `createLumenHeatmapDatumActivation`.
    pub(crate) fn heatmap(
        x: &ChartX,
        y: &ChartX,
        value: Option<f64>,
        datum_id: Option<&String>,
    ) -> Option<Self> {
        let value = value.filter(|value| value.is_finite())?;

        (x.is_axis_value() && y.is_axis_value()).then(|| Self::Heatmap {
            x: x.clone(),
            y: y.clone(),
            value,
            datum_id: datum_id.cloned(),
        })
    }

    /// `createLumenRangeDatumActivation`: also requires `low <= high`.
    pub(crate) fn range(
        x: &ChartX,
        low: Option<f64>,
        high: Option<f64>,
        datum_id: Option<&String>,
    ) -> Option<Self> {
        let low = low.filter(|value| value.is_finite())?;
        let high = high.filter(|value| value.is_finite())?;

        (x.is_axis_value() && low <= high).then(|| Self::Range {
            x: x.clone(),
            low,
            high,
            datum_id: datum_id.cloned(),
        })
    }

    fn datum_id(&self) -> Option<&String> {
        match self {
            Self::Series { datum_id, .. }
            | Self::Heatmap { datum_id, .. }
            | Self::Range { datum_id, .. } => datum_id.as_ref(),
        }
    }

    /// `JSON.stringify(detail)`, the `data-ui-chart-datum` attribute value.
    pub fn serialize(&self) -> String {
        let body = match self {
            Self::Series {
                series_id, x, y, ..
            } => format!(
                "\"kind\":\"series\",\"seriesId\":{},\"x\":{},\"y\":{}",
                json_string(series_id),
                x.json(),
                json_number(*y)
            ),
            Self::Heatmap { x, y, value, .. } => format!(
                "\"kind\":\"heatmap\",\"value\":{},\"x\":{},\"y\":{}",
                json_number(*value),
                x.json(),
                y.json()
            ),
            Self::Range { x, low, high, .. } => format!(
                "\"high\":{},\"kind\":\"range\",\"low\":{},\"x\":{}",
                json_number(*high),
                json_number(*low),
                x.json()
            ),
        };

        match self.datum_id() {
            Some(id) => format!("{{{body},\"datumId\":{}}}", json_string(id)),
            None => format!("{{{body}}}"),
        }
    }
}

/// `getLumenChartMotionKey`: the stable `data-ui-chart-motion-key` of a series point.
pub(crate) fn motion_key(series_id: &str, datum_id: Option<&String>, x: &ChartX) -> String {
    let point = datum_id.map_or_else(|| x.typed_json(), |id| json_string(id));

    format!("[{},{point}]", json_string(series_id))
}

/// A datum action: the accessible label and serialized detail of one clickable mark.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct DatumAction {
    pub(crate) detail: ChartDatumActivation,
    pub(crate) label: String,
    pub(crate) serialized: String,
}

impl DatumAction {
    pub(crate) fn new(
        detail: Option<ChartDatumActivation>,
        context: &str,
        labels: &ChartLabels,
    ) -> Option<Self> {
        detail.map(|detail| Self {
            serialized: detail.serialize(),
            label: labels.datum_action(context),
            detail,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::ChartDatumActivation;
    use crate::charts::model::{ChartDatum, ChartX};

    #[test]
    fn series_details_serialize_like_json_stringify() {
        let detail =
            ChartDatumActivation::series("revenue", &ChartDatum::new("Jan", 12.5)).unwrap();
        assert_eq!(
            detail.serialize(),
            r#"{"kind":"series","seriesId":"revenue","x":"Jan","y":12.5}"#
        );
        let with_id =
            ChartDatumActivation::series("a", &ChartDatum::new(3, 4.0).with_id("p\"1")).unwrap();
        assert_eq!(
            with_id.serialize(),
            r#"{"kind":"series","seriesId":"a","x":3,"y":4,"datumId":"p\"1"}"#
        );
    }

    #[test]
    fn invalid_details_are_rejected() {
        assert!(ChartDatumActivation::series("a", &ChartDatum::missing("Jan")).is_none());
        assert!(ChartDatumActivation::series("a", &ChartDatum::new(f64::NAN, 1.0)).is_none());
        assert!(ChartDatumActivation::series("a", &ChartDatum::new("x", f64::INFINITY)).is_none());
        assert!(
            ChartDatumActivation::range(&ChartX::from("a"), Some(5.0), Some(2.0), None).is_none()
        );
        assert!(
            ChartDatumActivation::heatmap(&ChartX::from("a"), &ChartX::from(1), None, None)
                .is_none()
        );
    }

    #[test]
    fn heatmap_and_range_keys_follow_lumen_core_order() {
        let heatmap =
            ChartDatumActivation::heatmap(&ChartX::from("Mon"), &ChartX::from(9), Some(3.0), None)
                .unwrap();
        assert_eq!(
            heatmap.serialize(),
            r#"{"kind":"heatmap","value":3,"x":"Mon","y":9}"#
        );
        let range = ChartDatumActivation::range(
            &ChartX::from("Q1"),
            Some(1.0),
            Some(2.5),
            Some(&"r".to_string()),
        )
        .unwrap();
        assert_eq!(
            range.serialize(),
            r#"{"high":2.5,"kind":"range","low":1,"x":"Q1","datumId":"r"}"#
        );
    }
}