Skip to main content

lumen_dioxus/charts/
heatmap.rs

1//! [`Heatmap`]: a grid of values colored on a sequential or diverging scale.
2
3use dioxus::prelude::*;
4
5use super::activation::{ChartDatumActivation, DatumAction};
6use super::format::js_number;
7use super::frame::{
8    ChartFrame, ChartPresentation, activate_on_click, datum_actions, plot_label, render_frame,
9    serialized,
10};
11use super::geometry::{HeatmapColorScale, HeatmapDatum, heatmap_color, heatmap_model};
12use super::model::{ChartBounds, ChartLabels, format_with};
13use super::scale::CategoryTick;
14use crate::class::{Glass, compose};
15
16/// Props for [`Heatmap`].
17#[derive(Props, Clone, PartialEq)]
18pub struct HeatmapProps {
19    /// The cells. The first cell wins for a repeated coordinate; `None` values are missing cells.
20    #[props(default)]
21    pub data: Vec<HeatmapDatum>,
22    /// Sequential (default) or diverging colors.
23    #[props(default)]
24    pub color_scale: HeatmapColorScale,
25    /// The neutral value of a diverging scale.
26    #[props(default)]
27    pub midpoint: f64,
28    /// Requested color bounds.
29    pub domain: Option<ChartBounds>,
30    /// Formats values in the legend, tooltips, and table. Defaults to `String(value)`.
31    pub format_value: Option<Callback<f64, String>>,
32    /// Localized chart text.
33    pub labels: Option<ChartLabels>,
34    /// Shows the color legend.
35    #[props(default = true)]
36    pub show_legend: bool,
37    /// Shows the collapsible data table.
38    #[props(default = true)]
39    pub show_table: bool,
40    /// Makes every available cell clickable and adds a keyboard-reachable action menu.
41    pub on_datum_activate: Option<EventHandler<ChartDatumActivation>>,
42    /// The chart title, also the plot's accessible name when `aria-label` is not set.
43    #[props(into)]
44    pub heading: Option<String>,
45    /// Supporting text under the heading.
46    #[props(into)]
47    pub description: Option<String>,
48    /// A headline value beside the heading.
49    #[props(into)]
50    pub value: Option<String>,
51    /// A screen reader summary; defaults to the count of available cells.
52    #[props(into)]
53    pub summary: Option<String>,
54    /// A visible caption, such as the data source.
55    #[props(into)]
56    pub caption: Option<String>,
57    /// `Bare` removes the card chrome.
58    #[props(default)]
59    pub presentation: ChartPresentation,
60    /// Glass intensity.
61    #[props(default, into)]
62    pub glass: Glass,
63    /// Extra classes appended after the Lumen classes.
64    #[props(into)]
65    pub class: Option<String>,
66    /// Any other `<figure>` or global attribute.
67    #[props(extends = GlobalAttributes, extends = figure)]
68    pub attributes: Vec<Attribute>,
69}
70
71struct CellView {
72    key: String,
73    width: String,
74    height: String,
75    x: String,
76    y: String,
77    style: String,
78    title: String,
79    missing: Option<(String, String)>,
80    column: String,
81    row: String,
82    value: String,
83    action: Option<DatumAction>,
84}
85
86/// Shows a value for every row and column pair, with a color legend, a data table, and optional
87/// datum activation. Missing cells are marked with `×`.
88#[component]
89#[allow(clippy::too_many_lines)]
90pub fn Heatmap(props: HeatmapProps) -> Element {
91    let labels = props.labels.clone().unwrap_or_default();
92    let format_value = props.format_value.as_ref();
93    let model = heatmap_model(&props.data, props.color_scale, props.midpoint, props.domain);
94    let on_activate = props.on_datum_activate;
95    let available = model
96        .cells
97        .iter()
98        .filter(|cell| cell.datum.finite_value().is_some())
99        .count();
100    let has_cells = !model.cells.is_empty();
101    let cells: Vec<CellView> = model
102        .cells
103        .iter()
104        .map(|cell| {
105            let datum = &cell.datum;
106            let column = datum.x_label.clone().unwrap_or_else(|| datum.x.display());
107            let row = datum.y_label.clone().unwrap_or_else(|| datum.y.display());
108            let value_text = datum
109                .label
110                .clone()
111                .unwrap_or_else(|| format_with(format_value, datum.value.unwrap_or(0.0)));
112            let missing = datum.finite_value().is_none();
113            let action = on_activate.and_then(|_| {
114                (!missing)
115                    .then(|| {
116                        DatumAction::new(
117                            ChartDatumActivation::heatmap(
118                                &datum.x,
119                                &datum.y,
120                                datum.value,
121                                datum.id.as_ref(),
122                            ),
123                            &format!("{column} · {row}: {value_text}"),
124                            &labels,
125                        )
126                    })
127                    .flatten()
128            });
129
130            CellView {
131                key: format!("[{},{}]", datum.x.json(), datum.y.json()),
132                width: js_number((cell.width - 2.0).max(0.0)),
133                height: js_number((cell.height - 2.0).max(0.0)),
134                x: js_number(cell.x + 1.0),
135                y: js_number(cell.y + 1.0),
136                style: format!(
137                    "fill:{}",
138                    heatmap_color(datum.value, model.domain, props.color_scale, model.midpoint)
139                ),
140                title: format!(
141                    "{column} · {row}: {}",
142                    if missing {
143                        labels.not_available.clone()
144                    } else {
145                        value_text.clone()
146                    }
147                ),
148                missing: missing.then(|| {
149                    (
150                        js_number(cell.x + cell.width / 2.0),
151                        js_number(cell.y + cell.height / 2.0),
152                    )
153                }),
154                value: datum.label.clone().unwrap_or_else(|| {
155                    datum.finite_value().map_or_else(
156                        || labels.not_available.clone(),
157                        |value| format_with(format_value, value),
158                    )
159                }),
160                column,
161                row,
162                action,
163            }
164        })
165        .collect();
166    let actions: Vec<Option<DatumAction>> = cells
167        .iter()
168        .filter(|cell| cell.missing.is_none())
169        .map(|cell| cell.action.clone())
170        .collect();
171    let x_ticks: Vec<(String, &'static str, String, String)> = model
172        .x_ticks
173        .iter()
174        .map(|tick| {
175            (
176                tick.index.to_string(),
177                CategoryTick::ANCHOR,
178                js_number(tick.position),
179                tick.label.clone(),
180            )
181        })
182        .collect();
183    let y_ticks: Vec<(String, String, String)> = model
184        .y_ticks
185        .iter()
186        .map(|tick| {
187            (
188                tick.value.key(),
189                js_number(tick.position),
190                tick.label.clone(),
191            )
192        })
193        .collect();
194    let plot_name = plot_label(
195        &props.attributes,
196        props.heading.as_ref(),
197        &labels.chart_data,
198    );
199    let legend_style = format!("background:{}", model.legend_background);
200    let midpoint_style = format!("left:{}%", js_number(model.midpoint_percent));
201    let diverging = props.color_scale == HeatmapColorScale::Diverging;
202    let frame = ChartFrame {
203        chart_class: Some(compose([Some("ui-heatmap"), props.class.as_deref()])),
204        heading: props.heading.clone(),
205        description: props.description.clone(),
206        value: props.value.clone(),
207        summary: Some(
208            props
209                .summary
210                .clone()
211                .unwrap_or_else(|| labels.heatmap_summary(available)),
212        ),
213        caption: props.caption.clone(),
214        presentation: props.presentation,
215        glass: props.glass,
216        activation: on_activate.is_some(),
217        attributes: props.attributes.clone(),
218        on_mounted: None,
219    };
220    let body = rsx! {
221        if available == 0 {
222            p { class: "ui-chart__empty", role: "status", "{labels.empty}" }
223        }
224        div {
225            aria_label: "{plot_name}",
226            class: "ui-chart__plot",
227            role: "region",
228            tabindex: "0",
229            hidden: !has_cells,
230            svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: 640", "viewBox": "0 0 640 320",
231                g { class: "ui-chart__axis-labels",
232                    for (key, anchor, x, label) in x_ticks {
233                        text { key: "{key}", "text-anchor": anchor, x: "{x}", y: "298", "{label}" }
234                    }
235                    for (key, y, label) in y_ticks {
236                        text {
237                            key: "row-{key}",
238                            class: "ui-heatmap__row-label",
239                            "text-anchor": "end",
240                            "dominant-baseline": "middle",
241                            x: "108",
242                            y: "{y}",
243                            "{label}"
244                        }
245                    }
246                }
247                g { class: "ui-heatmap__cells",
248                    for cell in cells.iter() {
249                        g { key: "{cell.key}",
250                            rect {
251                                "data-ui-chart-datum": serialized(cell.action.as_ref()),
252                                height: "{cell.height}",
253                                width: "{cell.width}",
254                                x: "{cell.x}",
255                                y: "{cell.y}",
256                                style: "{cell.style}",
257                                onclick: activate_on_click(cell.action.as_ref(), on_activate),
258                                title { "{cell.title}" }
259                            }
260                            if let Some((x, y)) = cell.missing.clone() {
261                                text {
262                                    class: "ui-heatmap__missing",
263                                    "text-anchor": "middle",
264                                    "dominant-baseline": "middle",
265                                    x: "{x}",
266                                    y: "{y}",
267                                    "×"
268                                }
269                            }
270                        }
271                    }
272                }
273            }
274        }
275        if props.show_legend && has_cells {
276            div { class: "ui-heatmap__legend", aria_label: "{labels.chart_legend}", role: "group",
277                span { "{format_with(format_value, model.domain.min)}" }
278                span { style: "{legend_style}", class: "ui-heatmap__scale",
279                    if diverging {
280                        span { style: "{midpoint_style}", "{format_with(format_value, model.midpoint)}" }
281                    }
282                }
283                span { "{format_with(format_value, model.domain.max)}" }
284                span {
285                    span { aria_hidden: "true", "×" }
286                    " {labels.not_available}"
287                }
288            }
289        }
290        if props.show_table {
291            details { class: "ui-chart__data",
292                summary { "{labels.view_data}" }
293                div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
294                    table {
295                        thead {
296                            tr {
297                                th { scope: "col", "{labels.column}" }
298                                th { scope: "col", "{labels.row}" }
299                                th { scope: "col", "{labels.value}" }
300                            }
301                        }
302                        tbody {
303                            for cell in cells.iter() {
304                                tr { key: "row-{cell.key}",
305                                    th { scope: "row", "{cell.column}" }
306                                    td { "{cell.row}" }
307                                    td { "{cell.value}" }
308                                }
309                            }
310                        }
311                    }
312                }
313            }
314        }
315        if on_activate.is_some() {
316            {datum_actions(&actions, &labels.explore_data, on_activate)}
317        }
318    };
319
320    render_frame(frame, body)
321}