Skip to main content

lumen_dioxus/charts/
scatter.rs

1//! [`ScatterChart`]: points and bubbles on two numeric axes.
2
3use dioxus::prelude::*;
4
5use super::activation::{ChartDatumActivation, DatumAction};
6use super::format::js_number;
7use super::frame::{
8    ChartFrame, ChartPresentation, activate_on_click, chart_legend, datum_actions, plot_label,
9    render_frame, serialized, table_value,
10};
11use super::geometry::{
12    COMPACT_AXIS_LABEL_SIZE, Margin, ScatterChartReference, ScatterChartScale, scatter_geometry,
13    scatter_references,
14};
15use super::model::{ChartBounds, ChartLabels, ChartSeries, ChartX, format_with, summarize};
16use crate::class::{Glass, compose};
17use crate::hooks::use_unique_id;
18
19/// Props for [`ScatterChart`].
20#[derive(Props, Clone, PartialEq)]
21pub struct ScatterChartProps {
22    /// The point series. `x` is numeric (or an ISO date on the time scale); `size` draws bubbles.
23    #[props(default)]
24    pub series: Vec<ChartSeries>,
25    /// The x scale: linear (default), logarithmic, or time.
26    #[props(default)]
27    pub x_scale: ScatterChartScale,
28    /// Requested x bounds, kept exactly. Automatic bounds leave room for the largest bubble and, on
29    /// a linear scale, round outward to the next tick.
30    pub x_domain: Option<ChartBounds>,
31    /// Requested y bounds, kept exactly. Automatic bounds leave room for the largest bubble and
32    /// round outward to the next tick.
33    pub domain: Option<ChartBounds>,
34    /// Reference lines and regions behind the points.
35    #[props(default)]
36    pub references: Vec<ScatterChartReference>,
37    /// Formats y values and sizes. Defaults to `String(value)`.
38    pub format_value: Option<Callback<f64, String>>,
39    /// Formats x values. Defaults to `String(x)`.
40    pub format_x: Option<Callback<ChartX, String>>,
41    /// Formats y values; defaults to `format_value`.
42    pub format_y: Option<Callback<f64, String>>,
43    /// Localized chart text.
44    pub labels: Option<ChartLabels>,
45    /// Shows the legend. Defaults to `true` with more than one series.
46    pub show_legend: Option<bool>,
47    /// Shows the collapsible data table.
48    #[props(default = true)]
49    pub show_table: bool,
50    /// Makes every point clickable and adds a keyboard-reachable action menu.
51    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
52    /// The chart title.
53    #[props(into)]
54    pub heading: Option<String>,
55    /// Supporting text under the heading.
56    #[props(into)]
57    pub description: Option<String>,
58    /// A headline value beside the heading.
59    #[props(into)]
60    pub value: Option<String>,
61    /// A screen reader summary; defaults to a generated description of the data.
62    #[props(into)]
63    pub summary: Option<String>,
64    /// A visible caption, such as the data source.
65    #[props(into)]
66    pub caption: Option<String>,
67    /// `Bare` removes the card chrome.
68    #[props(default)]
69    pub presentation: ChartPresentation,
70    /// Glass intensity.
71    #[props(default, into)]
72    pub glass: Glass,
73    /// Extra classes appended after the Lumen classes.
74    #[props(into)]
75    pub class: Option<String>,
76    /// Any other `<figure>` or global attribute.
77    #[props(extends = GlobalAttributes, extends = figure)]
78    pub attributes: Vec<Attribute>,
79}
80
81struct PointView {
82    key: String,
83    class: &'static str,
84    cx: String,
85    cy: String,
86    r: String,
87    hit_r: String,
88    visible: bool,
89    x_text: String,
90    series_label: String,
91    y_text: String,
92    size_text: String,
93    action: Option<DatumAction>,
94}
95
96struct ReferenceView {
97    id: String,
98    label: String,
99    region: bool,
100    values: [String; 4],
101}
102
103/// Plots numeric relationships as points or bubbles, with reference lines and regions, a legend,
104/// a data table, and optional datum activation.
105#[component]
106#[allow(clippy::too_many_lines)]
107pub fn ScatterChart(props: ScatterChartProps) -> Element {
108    let labels = props.labels.clone().unwrap_or_default();
109    let format_value = props.format_value.as_ref();
110    let format_y = props.format_y.as_ref().or(format_value);
111    let format_x = props.format_x.as_ref();
112    let clip_id = use_unique_id();
113    let on_activate = props.on_datum_activate;
114    let geometry = scatter_geometry(
115        &props.series,
116        props.x_scale,
117        props.x_domain,
118        props.domain,
119        Margin {
120            bottom: 44.0,
121            left: 44.0,
122            right: 24.0,
123            top: 16.0,
124        },
125        Some(COMPACT_AXIS_LABEL_SIZE),
126        format_y,
127    );
128    let frame = ChartFrame {
129        chart_class: Some(compose([Some("ui-scatter-chart"), props.class.as_deref()])),
130        heading: props.heading.clone(),
131        description: props.description.clone(),
132        value: props.value.clone(),
133        summary: props.summary.clone(),
134        caption: props.caption.clone(),
135        presentation: props.presentation,
136        glass: props.glass,
137        activation: on_activate.is_some(),
138        attributes: props.attributes.clone(),
139        on_mounted: None,
140    };
141
142    // lumen-core throws for an empty, reversed, or non-positive log domain; report it instead.
143    let Some(geometry) = geometry else {
144        let invalid = labels.invalid_data.clone();
145        let frame = ChartFrame {
146            summary: Some(props.summary.clone().unwrap_or_else(|| invalid.clone())),
147            ..frame
148        };
149
150        return render_frame(
151            frame,
152            rsx! {
153                p { class: "ui-chart__empty", role: "status", "{invalid}" }
154            },
155        );
156    };
157    let references: Vec<ReferenceView> =
158        scatter_references(&props.references, &geometry, props.x_scale)
159            .into_iter()
160            .map(|reference| ReferenceView {
161                values: if reference.region {
162                    [
163                        js_number(reference.x1.min(reference.x2)),
164                        js_number(reference.y1.min(reference.y2)),
165                        js_number((reference.x2 - reference.x1).abs()),
166                        js_number((reference.y2 - reference.y1).abs()),
167                    ]
168                } else {
169                    [
170                        js_number(reference.x1),
171                        js_number(reference.x2),
172                        js_number(reference.y1),
173                        js_number(reference.y2),
174                    ]
175                },
176                id: reference.id,
177                label: reference.label,
178                region: reference.region,
179            })
180            .collect();
181    let rendered: Vec<ChartSeries> = props
182        .series
183        .iter()
184        .map(|item| ChartSeries {
185            data: geometry
186                .points
187                .iter()
188                .filter(|point| point.series_id == item.id)
189                .map(|point| point.datum.clone())
190                .collect(),
191            ..item.clone()
192        })
193        .filter(|item| !item.data.is_empty())
194        .collect();
195    let has_data = !geometry.points.is_empty();
196    let show_legend = props.show_legend.unwrap_or(props.series.len() > 1);
197    let (width, height, plot) = (geometry.width, geometry.height, geometry.plot);
198    let points: Vec<PointView> = geometry
199        .points
200        .iter()
201        .enumerate()
202        .map(|(index, point)| {
203            let x_text = point
204                .datum
205                .x_label
206                .clone()
207                .unwrap_or_else(|| super::frame::plain_category(&point.datum.x, format_x));
208            let y_text = point
209                .datum
210                .label
211                .clone()
212                .unwrap_or_else(|| format_with(format_y, point.datum.y.unwrap_or(0.0)));
213            let action = on_activate.and_then(|_| {
214                DatumAction::new(
215                    ChartDatumActivation::series(&point.series_id, &point.datum),
216                    &format!("{x_text} · {}: {y_text}", point.series_label),
217                    &labels,
218                )
219            });
220
221            PointView {
222                key: format!(
223                    "{}:{}",
224                    point.series_id,
225                    point
226                        .datum
227                        .id
228                        .clone()
229                        .unwrap_or_else(|| format!("{}:{index}", point.datum.x.key()))
230                ),
231                class: point.tone.class_name(),
232                cx: js_number(point.x),
233                cy: js_number(point.y),
234                r: js_number(point.radius),
235                hit_r: js_number(point.radius.max(10.0)),
236                visible: plot.contains(point.x, point.y),
237                x_text,
238                series_label: point.series_label.clone(),
239                y_text,
240                size_text: table_value(point.datum.size, format_value, &labels.not_available),
241                action,
242            }
243        })
244        .collect();
245    let actions: Vec<Option<DatumAction>> =
246        points.iter().map(|point| point.action.clone()).collect();
247    let summary = props
248        .summary
249        .clone()
250        .or_else(|| Some(labels.summary(summarize(&rendered, format_y))));
251    let frame = ChartFrame { summary, ..frame };
252    let plot_name = plot_label(
253        &props.attributes,
254        props.heading.as_ref(),
255        &labels.chart_data,
256    );
257    let view_box = format!("0 0 {} {}", js_number(width), js_number(height));
258    let viewbox_width = js_number(width);
259    let clip_rect = [
260        js_number(plot.left),
261        js_number(plot.top),
262        js_number(plot.right - plot.left),
263        js_number(plot.bottom - plot.top),
264    ];
265    let clip_url = format!("url(#{clip_id})");
266    let body = rsx! {
267        if show_legend && has_data {
268            {chart_legend(&labels.chart_legend, &props.series)}
269        }
270        if !has_data {
271            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
272        }
273        div {
274            aria_label: "{plot_name}",
275            class: "ui-chart__plot",
276            role: "region",
277            tabindex: "0",
278            hidden: !has_data,
279            svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
280                defs {
281                    clipPath { id: "{clip_id}",
282                        rect { x: "{clip_rect[0]}", y: "{clip_rect[1]}", width: "{clip_rect[2]}", height: "{clip_rect[3]}" }
283                    }
284                }
285                g { "clip-path": "{clip_url}",
286                    g { class: "ui-scatter-chart__references",
287                        for reference in references.iter() {
288                            if reference.region {
289                                rect {
290                                    key: "{reference.id}",
291                                    x: "{reference.values[0]}",
292                                    y: "{reference.values[1]}",
293                                    width: "{reference.values[2]}",
294                                    height: "{reference.values[3]}",
295                                    title { "{reference.label}" }
296                                }
297                            } else {
298                                line {
299                                    key: "{reference.id}",
300                                    x1: "{reference.values[0]}",
301                                    x2: "{reference.values[1]}",
302                                    y1: "{reference.values[2]}",
303                                    y2: "{reference.values[3]}",
304                                    title { "{reference.label}" }
305                                }
306                            }
307                        }
308                    }
309                    g { class: "ui-scatter-chart__marks",
310                        for point in points.iter() {
311                            circle {
312                                key: "{point.key}",
313                                "data-ui-chart-datum": serialized(point.action.as_ref()),
314                                class: point.class,
315                                cx: "{point.cx}",
316                                cy: "{point.cy}",
317                                r: "{point.r}",
318                                onclick: activate_on_click(point.action.as_ref(), on_activate),
319                                title { "{point.x_text} · {point.series_label}: {point.y_text}" }
320                            }
321                        }
322                    }
323                }
324                if on_activate.is_some() {
325                    for point in points.iter().filter(|point| point.visible) {
326                        circle {
327                            key: "hit-{point.key}",
328                            class: "ui-chart__datum-hit",
329                            cx: "{point.cx}",
330                            cy: "{point.cy}",
331                            r: "{point.hit_r}",
332                            "data-ui-chart-datum": serialized(point.action.as_ref()),
333                            onclick: activate_on_click(point.action.as_ref(), on_activate),
334                        }
335                    }
336                }
337            }
338        }
339        if !references.is_empty() {
340            ul { class: "ui-scatter-chart__reference-labels",
341                for reference in references.iter() {
342                    li { key: "{reference.id}", "{reference.label}" }
343                }
344            }
345        }
346        if props.show_table && has_data {
347            details { class: "ui-chart__data",
348                summary { "{labels.view_data}" }
349                div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
350                    table {
351                        thead {
352                            tr {
353                                th { scope: "col", "{labels.x}" }
354                                th { scope: "col", "{labels.series}" }
355                                th { scope: "col", "{labels.value}" }
356                                th { scope: "col", "{labels.size}" }
357                            }
358                        }
359                        tbody {
360                            for point in points.iter() {
361                                tr { key: "{point.key}",
362                                    th { scope: "row", "{point.x_text}" }
363                                    td { "{point.series_label}" }
364                                    td { "{point.y_text}" }
365                                    td { "{point.size_text}" }
366                                }
367                            }
368                        }
369                    }
370                }
371            }
372        }
373        if on_activate.is_some() {
374            {datum_actions(&actions, &labels.explore_data, on_activate)}
375        }
376    };
377
378    render_frame(frame, body)
379}