lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! [`ScatterChart`]: points and bubbles on two numeric axes.

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction};
use super::format::js_number;
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, chart_legend, datum_actions, plot_label,
    render_frame, serialized, table_value,
};
use super::geometry::{
    COMPACT_AXIS_LABEL_SIZE, Margin, ScatterChartReference, ScatterChartScale, scatter_geometry,
    scatter_references,
};
use super::model::{ChartBounds, ChartLabels, ChartSeries, ChartX, format_with, summarize};
use crate::class::{Glass, compose};
use crate::hooks::use_unique_id;

/// Props for [`ScatterChart`].
#[derive(Props, Clone, PartialEq)]
pub struct ScatterChartProps {
    /// The point series. `x` is numeric (or an ISO date on the time scale); `size` draws bubbles.
    #[props(default)]
    pub series: Vec<ChartSeries>,
    /// The x scale: linear (default), logarithmic, or time.
    #[props(default)]
    pub x_scale: ScatterChartScale,
    /// Requested x bounds, kept exactly. Automatic bounds leave room for the largest bubble and, on
    /// a linear scale, round outward to the next tick.
    pub x_domain: Option<ChartBounds>,
    /// Requested y bounds, kept exactly. Automatic bounds leave room for the largest bubble and
    /// round outward to the next tick.
    pub domain: Option<ChartBounds>,
    /// Reference lines and regions behind the points.
    #[props(default)]
    pub references: Vec<ScatterChartReference>,
    /// Formats y values and sizes. Defaults to `String(value)`.
    pub format_value: Option<Callback<f64, String>>,
    /// Formats x values. Defaults to `String(x)`.
    pub format_x: Option<Callback<ChartX, String>>,
    /// Formats y values; defaults to `format_value`.
    pub format_y: Option<Callback<f64, String>>,
    /// Localized chart text.
    pub labels: Option<ChartLabels>,
    /// Shows the legend. Defaults to `true` with more than one series.
    pub show_legend: Option<bool>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// Makes every point clickable and adds a keyboard-reachable action menu.
    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
    /// The chart title.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A headline value beside the heading.
    #[props(into)]
    pub value: Option<String>,
    /// A screen reader summary; defaults to a generated description of the data.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption, such as the data source.
    #[props(into)]
    pub caption: Option<String>,
    /// `Bare` removes the card chrome.
    #[props(default)]
    pub presentation: ChartPresentation,
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<figure>` or global attribute.
    #[props(extends = GlobalAttributes, extends = figure)]
    pub attributes: Vec<Attribute>,
}

struct PointView {
    key: String,
    class: &'static str,
    cx: String,
    cy: String,
    r: String,
    hit_r: String,
    visible: bool,
    x_text: String,
    series_label: String,
    y_text: String,
    size_text: String,
    action: Option<DatumAction>,
}

struct ReferenceView {
    id: String,
    label: String,
    region: bool,
    values: [String; 4],
}

/// Plots numeric relationships as points or bubbles, with reference lines and regions, a legend,
/// a data table, and optional datum activation.
#[component]
#[allow(clippy::too_many_lines)]
pub fn ScatterChart(props: ScatterChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value.as_ref();
    let format_y = props.format_y.as_ref().or(format_value);
    let format_x = props.format_x.as_ref();
    let clip_id = use_unique_id();
    let on_activate = props.on_datum_activate;
    let geometry = scatter_geometry(
        &props.series,
        props.x_scale,
        props.x_domain,
        props.domain,
        Margin {
            bottom: 44.0,
            left: 44.0,
            right: 24.0,
            top: 16.0,
        },
        Some(COMPACT_AXIS_LABEL_SIZE),
        format_y,
    );
    let frame = ChartFrame {
        chart_class: Some(compose([Some("ui-scatter-chart"), props.class.as_deref()])),
        heading: props.heading.clone(),
        description: props.description.clone(),
        value: props.value.clone(),
        summary: props.summary.clone(),
        caption: props.caption.clone(),
        presentation: props.presentation,
        glass: props.glass,
        activation: on_activate.is_some(),
        attributes: props.attributes.clone(),
        on_mounted: None,
    };

    // lumen-core throws for an empty, reversed, or non-positive log domain; report it instead.
    let Some(geometry) = geometry else {
        let invalid = labels.invalid_data.clone();
        let frame = ChartFrame {
            summary: Some(props.summary.clone().unwrap_or_else(|| invalid.clone())),
            ..frame
        };

        return render_frame(
            frame,
            rsx! {
                p { class: "ui-chart__empty", role: "status", "{invalid}" }
            },
        );
    };
    let references: Vec<ReferenceView> =
        scatter_references(&props.references, &geometry, props.x_scale)
            .into_iter()
            .map(|reference| ReferenceView {
                values: if reference.region {
                    [
                        js_number(reference.x1.min(reference.x2)),
                        js_number(reference.y1.min(reference.y2)),
                        js_number((reference.x2 - reference.x1).abs()),
                        js_number((reference.y2 - reference.y1).abs()),
                    ]
                } else {
                    [
                        js_number(reference.x1),
                        js_number(reference.x2),
                        js_number(reference.y1),
                        js_number(reference.y2),
                    ]
                },
                id: reference.id,
                label: reference.label,
                region: reference.region,
            })
            .collect();
    let rendered: Vec<ChartSeries> = props
        .series
        .iter()
        .map(|item| ChartSeries {
            data: geometry
                .points
                .iter()
                .filter(|point| point.series_id == item.id)
                .map(|point| point.datum.clone())
                .collect(),
            ..item.clone()
        })
        .filter(|item| !item.data.is_empty())
        .collect();
    let has_data = !geometry.points.is_empty();
    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
    let (width, height, plot) = (geometry.width, geometry.height, geometry.plot);
    let points: Vec<PointView> = geometry
        .points
        .iter()
        .enumerate()
        .map(|(index, point)| {
            let x_text = point
                .datum
                .x_label
                .clone()
                .unwrap_or_else(|| super::frame::plain_category(&point.datum.x, format_x));
            let y_text = point
                .datum
                .label
                .clone()
                .unwrap_or_else(|| format_with(format_y, point.datum.y.unwrap_or(0.0)));
            let action = on_activate.and_then(|_| {
                DatumAction::new(
                    ChartDatumActivation::series(&point.series_id, &point.datum),
                    &format!("{x_text} ยท {}: {y_text}", point.series_label),
                    &labels,
                )
            });

            PointView {
                key: format!(
                    "{}:{}",
                    point.series_id,
                    point
                        .datum
                        .id
                        .clone()
                        .unwrap_or_else(|| format!("{}:{index}", point.datum.x.key()))
                ),
                class: point.tone.class_name(),
                cx: js_number(point.x),
                cy: js_number(point.y),
                r: js_number(point.radius),
                hit_r: js_number(point.radius.max(10.0)),
                visible: plot.contains(point.x, point.y),
                x_text,
                series_label: point.series_label.clone(),
                y_text,
                size_text: table_value(point.datum.size, format_value, &labels.not_available),
                action,
            }
        })
        .collect();
    let actions: Vec<Option<DatumAction>> =
        points.iter().map(|point| point.action.clone()).collect();
    let summary = props
        .summary
        .clone()
        .or_else(|| Some(labels.summary(summarize(&rendered, format_y))));
    let frame = ChartFrame { summary, ..frame };
    let plot_name = plot_label(
        &props.attributes,
        props.heading.as_ref(),
        &labels.chart_data,
    );
    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
    let viewbox_width = js_number(width);
    let clip_rect = [
        js_number(plot.left),
        js_number(plot.top),
        js_number(plot.right - plot.left),
        js_number(plot.bottom - plot.top),
    ];
    let clip_url = format!("url(#{clip_id})");
    let body = rsx! {
        if show_legend && has_data {
            {chart_legend(&labels.chart_legend, &props.series)}
        }
        if !has_data {
            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
        }
        div {
            aria_label: "{plot_name}",
            class: "ui-chart__plot",
            role: "region",
            tabindex: "0",
            hidden: !has_data,
            svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
                defs {
                    clipPath { id: "{clip_id}",
                        rect { x: "{clip_rect[0]}", y: "{clip_rect[1]}", width: "{clip_rect[2]}", height: "{clip_rect[3]}" }
                    }
                }
                g { "clip-path": "{clip_url}",
                    g { class: "ui-scatter-chart__references",
                        for reference in references.iter() {
                            if reference.region {
                                rect {
                                    key: "{reference.id}",
                                    x: "{reference.values[0]}",
                                    y: "{reference.values[1]}",
                                    width: "{reference.values[2]}",
                                    height: "{reference.values[3]}",
                                    title { "{reference.label}" }
                                }
                            } else {
                                line {
                                    key: "{reference.id}",
                                    x1: "{reference.values[0]}",
                                    x2: "{reference.values[1]}",
                                    y1: "{reference.values[2]}",
                                    y2: "{reference.values[3]}",
                                    title { "{reference.label}" }
                                }
                            }
                        }
                    }
                    g { class: "ui-scatter-chart__marks",
                        for point in points.iter() {
                            circle {
                                key: "{point.key}",
                                "data-ui-chart-datum": serialized(point.action.as_ref()),
                                class: point.class,
                                cx: "{point.cx}",
                                cy: "{point.cy}",
                                r: "{point.r}",
                                onclick: activate_on_click(point.action.as_ref(), on_activate),
                                title { "{point.x_text} ยท {point.series_label}: {point.y_text}" }
                            }
                        }
                    }
                }
                if on_activate.is_some() {
                    for point in points.iter().filter(|point| point.visible) {
                        circle {
                            key: "hit-{point.key}",
                            class: "ui-chart__datum-hit",
                            cx: "{point.cx}",
                            cy: "{point.cy}",
                            r: "{point.hit_r}",
                            "data-ui-chart-datum": serialized(point.action.as_ref()),
                            onclick: activate_on_click(point.action.as_ref(), on_activate),
                        }
                    }
                }
            }
        }
        if !references.is_empty() {
            ul { class: "ui-scatter-chart__reference-labels",
                for reference in references.iter() {
                    li { key: "{reference.id}", "{reference.label}" }
                }
            }
        }
        if props.show_table && has_data {
            details { class: "ui-chart__data",
                summary { "{labels.view_data}" }
                div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
                    table {
                        thead {
                            tr {
                                th { scope: "col", "{labels.x}" }
                                th { scope: "col", "{labels.series}" }
                                th { scope: "col", "{labels.value}" }
                                th { scope: "col", "{labels.size}" }
                            }
                        }
                        tbody {
                            for point in points.iter() {
                                tr { key: "{point.key}",
                                    th { scope: "row", "{point.x_text}" }
                                    td { "{point.series_label}" }
                                    td { "{point.y_text}" }
                                    td { "{point.size_text}" }
                                }
                            }
                        }
                    }
                }
            }
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame(frame, body)
}