lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! [`RangeChart`]: low-to-high intervals across categories, joined into a band.

use dioxus::prelude::*;

use super::activation::{ChartDatumActivation, DatumAction};
use super::format::js_number;
use super::frame::{
    ChartFrame, ChartPresentation, activate_on_click, datum_actions, plot_label, render_frame,
    serialized, table_value,
};
use super::geometry::{
    COMPACT_AXIS_LABEL_SIZE, Margin, RangeChartDatum, chart_size, range_geometry,
};
use super::model::{ChartLabels, ChartTone, format_with};
use super::scale::{CategoryTick, CategoryTickOptions, category_ticks, format_ticks, scale_value};
use crate::class::{Glass, compose};

/// Props for [`RangeChart`].
#[derive(Props, Clone, PartialEq)]
pub struct RangeChartProps {
    /// SVG coordinate width, at least 240 (default 640).
    pub width: Option<f64>,
    /// SVG coordinate height, at least 240 (default 320).
    pub height: Option<f64>,
    /// The intervals, in x order. A missing bound breaks the band.
    #[props(default)]
    pub data: Vec<RangeChartDatum>,
    /// The band color.
    #[props(default)]
    pub tone: ChartTone,
    /// Formats values on the axis, in tooltips, and in the table. Without it, tooltips and the table
    /// use `String(value)` and axis ticks use grouped `en-US` numbers (`1,000`), switching the whole
    /// axis to compact notation (`15K`) when a label would exceed five characters.
    pub format_value: Option<Callback<f64, String>>,
    /// Localized chart text.
    pub labels: Option<ChartLabels>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// Makes every interval 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 the count of available ranges.
    #[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 IntervalView {
    key: String,
    x: String,
    high: String,
    low: String,
    title: String,
    hit: [String; 3],
    action: Option<DatumAction>,
}

/// Shows a low-to-high range per category (forecast bands, min and max temperatures), with a data
/// table and optional datum activation.
#[component]
#[allow(clippy::too_many_lines)]
pub fn RangeChart(props: RangeChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value.as_ref();
    let width = chart_size(props.width, 640.0);
    let height = chart_size(props.height, 320.0);
    let geometry = range_geometry(
        &props.data,
        Margin {
            bottom: 44.0,
            left: 44.0,
            right: 24.0,
            top: 16.0,
        },
        width,
        height,
        Some(COMPACT_AXIS_LABEL_SIZE),
        format_value,
    );
    let plot = geometry.plot;
    let on_activate = props.on_datum_activate;
    let tick_labels: Vec<String> = geometry
        .points
        .iter()
        .map(|point| {
            point
                .datum
                .x_label
                .clone()
                .unwrap_or_else(|| point.datum.x.display())
        })
        .collect();
    let tick_positions: Vec<f64> = geometry.points.iter().map(|point| point.x).collect();
    let category_ticks: Vec<(String, &'static str, String, String)> = category_ticks(
        &tick_labels,
        CategoryTickOptions::new(plot.left, plot.right)
            .bounds(0.0, width)
            .maximum_font_size(COMPACT_AXIS_LABEL_SIZE)
            .positions(&tick_positions),
    )
    .into_iter()
    .map(|tick| {
        (
            tick.index.to_string(),
            CategoryTick::ANCHOR,
            js_number(tick.position),
            tick.label,
        )
    })
    .collect();
    let grid: Vec<(String, String, String)> = geometry
        .ticks
        .iter()
        .zip(format_ticks(&geometry.ticks, format_value))
        .map(|(tick, label)| {
            (
                js_number(*tick),
                js_number(scale_value(*tick, geometry.domain, plot.bottom, plot.top)),
                label,
            )
        })
        .collect();
    let intervals: Vec<IntervalView> = geometry
        .points
        .iter()
        .map(|point| {
            let datum = &point.datum;
            let text = datum.label.clone().unwrap_or_else(|| {
                format!(
                    "{}–{}",
                    format_with(format_value, datum.low.unwrap_or(0.0)),
                    format_with(format_value, datum.high.unwrap_or(0.0))
                )
            });
            let title = format!(
                "{}: {text}",
                datum.x_label.clone().unwrap_or_else(|| datum.x.display())
            );
            let action = on_activate.and_then(|_| {
                DatumAction::new(
                    ChartDatumActivation::range(&datum.x, datum.low, datum.high, datum.id.as_ref()),
                    &title,
                    &labels,
                )
            });
            let span = (point.high - point.low).abs();

            IntervalView {
                key: datum.id.clone().unwrap_or_else(|| datum.x.key()),
                x: js_number(point.x),
                high: js_number(point.high),
                low: js_number(point.low),
                hit: [
                    js_number(point.x - 10.0),
                    js_number(point.high.min(point.low) - (20.0 - span).max(0.0) / 2.0),
                    js_number(span.max(20.0)),
                ],
                title,
                action,
            }
        })
        .collect();
    let actions: Vec<Option<DatumAction>> = intervals
        .iter()
        .map(|interval| interval.action.clone())
        .collect();
    let rows: Vec<(String, String, String, String)> = props
        .data
        .iter()
        .map(|datum| {
            (
                datum.id.clone().unwrap_or_else(|| datum.x.key()),
                datum.x_label.clone().unwrap_or_else(|| datum.x.display()),
                table_value(datum.low, format_value, &labels.not_available),
                table_value(datum.high, format_value, &labels.not_available),
            )
        })
        .collect();
    let empty = geometry.points.is_empty();
    let plot_name = plot_label(
        &props.attributes,
        props.heading.as_ref(),
        &labels.chart_data,
    );
    let frame = ChartFrame {
        chart_class: Some(compose([
            Some("ui-range-chart"),
            Some(props.tone.class_name()),
            props.class.as_deref(),
        ])),
        heading: props.heading.clone(),
        description: props.description.clone(),
        value: props.value.clone(),
        summary: Some(
            props
                .summary
                .clone()
                .unwrap_or_else(|| labels.range_summary(geometry.points.len())),
        ),
        caption: props.caption.clone(),
        presentation: props.presentation,
        glass: props.glass,
        activation: on_activate.is_some(),
        attributes: props.attributes.clone(),
        on_mounted: None,
    };
    let left = js_number(plot.left);
    let right = js_number(plot.right);
    let label_x = js_number(plot.left - 8.0);
    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
    let viewbox_width = js_number(width);

    let axis_y = js_number(height - 12.0);
    let body = rsx! {
        if empty {
            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
        }
        div {
            aria_label: "{plot_name}",
            class: "ui-chart__plot",
            role: "region",
            tabindex: "0",
            hidden: empty,
            svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
                g { class: "ui-chart__grid",
                    for (key, y, text) in grid {
                        g { key: "{key}",
                            line { x1: "{left}", x2: "{right}", y1: "{y}", y2: "{y}" }
                            text { x: "{label_x}", y: "{y}", "{text}" }
                        }
                    }
                }
                g { class: "ui-chart__axis-labels",
                    for (key, anchor, x, label) in category_ticks {
                        text { key: "{key}", x: "{x}", y: "{axis_y}", "text-anchor": anchor, "{label}" }
                    }
                }
                path { class: "ui-range-chart__area", d: "{geometry.area_path}" }
                for interval in intervals.iter() {
                    line {
                        key: "{interval.key}",
                        "data-ui-chart-datum": serialized(interval.action.as_ref()),
                        class: "ui-range-chart__interval",
                        x1: "{interval.x}",
                        x2: "{interval.x}",
                        y1: "{interval.high}",
                        y2: "{interval.low}",
                        onclick: activate_on_click(interval.action.as_ref(), on_activate),
                        title { "{interval.title}" }
                    }
                }
                if on_activate.is_some() {
                    for interval in intervals.iter() {
                        rect {
                            key: "hit-{interval.key}",
                            class: "ui-chart__datum-hit",
                            x: "{interval.hit[0]}",
                            y: "{interval.hit[1]}",
                            width: "20",
                            height: "{interval.hit[2]}",
                            "data-ui-chart-datum": serialized(interval.action.as_ref()),
                            onclick: activate_on_click(interval.action.as_ref(), on_activate),
                        }
                    }
                }
            }
        }
        if props.show_table {
            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.category}" }
                                th { scope: "col", "{labels.low}" }
                                th { scope: "col", "{labels.high}" }
                            }
                        }
                        tbody {
                            for (key, label, low, high) in rows {
                                tr { key: "{key}",
                                    th { scope: "row", "{label}" }
                                    td { "{low}" }
                                    td { "{high}" }
                                }
                            }
                        }
                    }
                }
            }
        }
        if on_activate.is_some() {
            {datum_actions(&actions, &labels.explore_data, on_activate)}
        }
    };

    render_frame(frame, body)
}