Skip to main content

lumen_dioxus/charts/
model.rs

1//! Chart data types shared by every chart: x identities, data points, series, tones, domains,
2//! and the localizable labels.
3
4use dioxus::prelude::*;
5
6use super::format::{js_number, json_number, json_string};
7
8/// An x value: a category name or a number (a linear value or a millisecond timestamp).
9///
10/// Equality follows JavaScript's `===`: `Number(0.0)` equals `Number(-0.0)`, `NaN` never equals
11/// itself, and a number never equals text.
12#[derive(Clone, Debug, PartialEq)]
13#[non_exhaustive]
14pub enum ChartX {
15    /// A numeric x value.
16    Number(f64),
17    /// A category name or an ISO 8601 date.
18    Text(String),
19}
20
21impl ChartX {
22    /// `String(x)` in JavaScript: the default display label.
23    pub fn display(&self) -> String {
24        match self {
25            Self::Number(value) => js_number(*value),
26            Self::Text(text) => text.clone(),
27        }
28    }
29
30    /// The identity key lumen-core uses to group categories: `number:1` or `string:Jan`.
31    pub(crate) fn key(&self) -> String {
32        match self {
33            Self::Number(value) => format!("number:{}", js_number(*value)),
34            Self::Text(text) => format!("string:{text}"),
35        }
36    }
37
38    /// `JSON.stringify(x)` in JavaScript.
39    pub(crate) fn json(&self) -> String {
40        match self {
41            Self::Number(value) => json_number(*value),
42            Self::Text(text) => json_string(text),
43        }
44    }
45
46    /// `[typeof x, x]` serialized as JSON, as used in motion keys.
47    pub(crate) fn typed_json(&self) -> String {
48        match self {
49            Self::Number(value) => format!("[\"number\",{}]", json_number(*value)),
50            Self::Text(text) => format!("[\"string\",{}]", json_string(text)),
51        }
52    }
53
54    /// Whether the value is text or a finite number (the axis values lumen-core accepts).
55    pub(crate) fn is_axis_value(&self) -> bool {
56        match self {
57            Self::Number(value) => value.is_finite(),
58            Self::Text(_) => true,
59        }
60    }
61}
62
63impl From<f64> for ChartX {
64    fn from(value: f64) -> Self {
65        Self::Number(value)
66    }
67}
68
69impl From<f32> for ChartX {
70    fn from(value: f32) -> Self {
71        Self::Number(f64::from(value))
72    }
73}
74
75impl From<i32> for ChartX {
76    fn from(value: i32) -> Self {
77        Self::Number(f64::from(value))
78    }
79}
80
81impl From<u32> for ChartX {
82    fn from(value: u32) -> Self {
83        Self::Number(f64::from(value))
84    }
85}
86
87impl From<&str> for ChartX {
88    fn from(value: &str) -> Self {
89        Self::Text(value.to_string())
90    }
91}
92
93impl From<String> for ChartX {
94    fn from(value: String) -> Self {
95        Self::Text(value)
96    }
97}
98
99impl From<&String> for ChartX {
100    fn from(value: &String) -> Self {
101        Self::Text(value.clone())
102    }
103}
104
105/// The chart color tokens. Series tones cycle through `series-1` to `series-8`.
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub enum ChartTone {
109    /// `series-1`.
110    #[default]
111    Series1,
112    /// `series-2`.
113    Series2,
114    /// `series-3`.
115    Series3,
116    /// `series-4`.
117    Series4,
118    /// `series-5`.
119    Series5,
120    /// `series-6`.
121    Series6,
122    /// `series-7`.
123    Series7,
124    /// `series-8`.
125    Series8,
126    /// The brand color.
127    Brand,
128    /// The accent color.
129    Accent,
130    /// Positive status.
131    Success,
132    /// Cautionary status.
133    Warning,
134    /// Negative status.
135    Danger,
136    /// Neutral gray.
137    Neutral,
138}
139
140const SERIES_TONES: [ChartTone; 8] = [
141    ChartTone::Series1,
142    ChartTone::Series2,
143    ChartTone::Series3,
144    ChartTone::Series4,
145    ChartTone::Series5,
146    ChartTone::Series6,
147    ChartTone::Series7,
148    ChartTone::Series8,
149];
150
151impl ChartTone {
152    /// The token name, such as `series-1` or `danger`.
153    pub fn as_str(self) -> &'static str {
154        match self {
155            Self::Series1 => "series-1",
156            Self::Series2 => "series-2",
157            Self::Series3 => "series-3",
158            Self::Series4 => "series-4",
159            Self::Series5 => "series-5",
160            Self::Series6 => "series-6",
161            Self::Series7 => "series-7",
162            Self::Series8 => "series-8",
163            Self::Brand => "brand",
164            Self::Accent => "accent",
165            Self::Success => "success",
166            Self::Warning => "warning",
167            Self::Danger => "danger",
168            Self::Neutral => "neutral",
169        }
170    }
171
172    /// The `ui-chart-tone--*` class that sets `--ui-chart-color`.
173    pub fn class_name(self) -> &'static str {
174        match self {
175            Self::Series1 => "ui-chart-tone--series-1",
176            Self::Series2 => "ui-chart-tone--series-2",
177            Self::Series3 => "ui-chart-tone--series-3",
178            Self::Series4 => "ui-chart-tone--series-4",
179            Self::Series5 => "ui-chart-tone--series-5",
180            Self::Series6 => "ui-chart-tone--series-6",
181            Self::Series7 => "ui-chart-tone--series-7",
182            Self::Series8 => "ui-chart-tone--series-8",
183            Self::Brand => "ui-chart-tone--brand",
184            Self::Accent => "ui-chart-tone--accent",
185            Self::Success => "ui-chart-tone--success",
186            Self::Warning => "ui-chart-tone--warning",
187            Self::Danger => "ui-chart-tone--danger",
188            Self::Neutral => "ui-chart-tone--neutral",
189        }
190    }
191
192    /// The explicit tone, or the series tone for `index` (cycling through eight series colors).
193    pub fn resolve(tone: Option<Self>, index: usize) -> Self {
194        tone.unwrap_or(SERIES_TONES[index % SERIES_TONES.len()])
195    }
196}
197
198/// One data point of a [`ChartSeries`].
199#[derive(Clone, Debug, PartialEq)]
200pub struct ChartDatum {
201    /// The x identity: a category, a number, or an ISO 8601 date.
202    pub x: ChartX,
203    /// The value. `None` (or a non-finite number) is a missing measurement that breaks lines.
204    pub y: Option<f64>,
205    /// A stable id, used for motion keys and activation details.
206    pub id: Option<String>,
207    /// A formatted value label that replaces the formatted `y` in tooltips and tables.
208    pub label: Option<String>,
209    /// A display label for `x` on axes and in tables.
210    pub x_label: Option<String>,
211    /// The bubble size in a [`ScatterChart`](crate::ScatterChart).
212    pub size: Option<f64>,
213    /// A tone for this point (pie slices and scatter points).
214    pub tone: Option<ChartTone>,
215    /// A label describing the tone, for consumers that present it.
216    pub tone_label: Option<String>,
217}
218
219impl ChartDatum {
220    /// A point at `x` with value `y`.
221    pub fn new(x: impl Into<ChartX>, y: impl Into<Option<f64>>) -> Self {
222        Self {
223            x: x.into(),
224            y: y.into(),
225            id: None,
226            label: None,
227            x_label: None,
228            size: None,
229            tone: None,
230            tone_label: None,
231        }
232    }
233
234    /// A point at `x` without a measurement.
235    pub fn missing(x: impl Into<ChartX>) -> Self {
236        Self::new(x, None)
237    }
238
239    /// Sets the stable id.
240    #[must_use]
241    pub fn with_id(mut self, id: impl Into<String>) -> Self {
242        self.id = Some(id.into());
243        self
244    }
245
246    /// Sets the formatted value label.
247    #[must_use]
248    pub fn with_label(mut self, label: impl Into<String>) -> Self {
249        self.label = Some(label.into());
250        self
251    }
252
253    /// Sets the x display label.
254    #[must_use]
255    pub fn with_x_label(mut self, label: impl Into<String>) -> Self {
256        self.x_label = Some(label.into());
257        self
258    }
259
260    /// Sets the bubble size.
261    #[must_use]
262    pub fn with_size(mut self, size: f64) -> Self {
263        self.size = Some(size);
264        self
265    }
266
267    /// Sets the tone.
268    #[must_use]
269    pub fn with_tone(mut self, tone: ChartTone) -> Self {
270        self.tone = Some(tone);
271        self
272    }
273
274    /// The value when it is a finite number.
275    pub(crate) fn value(&self) -> Option<f64> {
276        self.y.filter(|value| value.is_finite())
277    }
278}
279
280/// An explicit line pattern for a [`ChartSeries`] in `LineChart` or `ComboChart`.
281/// Leave [`ChartSeries::dash`] unset to use the stylesheet's automatic series patterns.
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
283#[non_exhaustive]
284pub enum ChartSeriesDash {
285    /// A continuous stroke.
286    #[default]
287    Solid,
288    /// A dashed stroke.
289    Dashed,
290    /// A dotted stroke.
291    Dotted,
292}
293
294impl ChartSeriesDash {
295    /// The shared `data-ui-chart-dash` attribute value.
296    pub fn as_str(self) -> &'static str {
297        match self {
298            Self::Solid => "solid",
299            Self::Dashed => "dashed",
300            Self::Dotted => "dotted",
301        }
302    }
303}
304
305/// A named sequence of [`ChartDatum`] values.
306#[derive(Clone, Debug, PartialEq)]
307pub struct ChartSeries {
308    /// A unique id.
309    pub id: String,
310    /// The display name used in legends, tooltips, and tables.
311    pub label: String,
312    /// The points, in x order.
313    pub data: Vec<ChartDatum>,
314    /// The series color; defaults to the series tone for its position.
315    pub tone: Option<ChartTone>,
316    /// An explicit line pattern; `None` keeps automatic series patterns.
317    pub dash: Option<ChartSeriesDash>,
318}
319
320impl ChartSeries {
321    /// A series with an id, a display name, and its points.
322    pub fn new(
323        id: impl Into<String>,
324        label: impl Into<String>,
325        data: impl IntoIterator<Item = ChartDatum>,
326    ) -> Self {
327        Self {
328            id: id.into(),
329            label: label.into(),
330            data: data.into_iter().collect(),
331            tone: None,
332            dash: None,
333        }
334    }
335
336    /// Sets the explicit line pattern for line and combo charts.
337    #[must_use]
338    pub fn with_dash(mut self, dash: ChartSeriesDash) -> Self {
339        self.dash = Some(dash);
340        self
341    }
342
343    /// Sets the series tone.
344    #[must_use]
345    pub fn with_tone(mut self, tone: ChartTone) -> Self {
346        self.tone = Some(tone);
347        self
348    }
349}
350
351/// A numeric domain from `min` to `max`.
352#[derive(Clone, Copy, Debug, PartialEq)]
353pub struct ChartDomain {
354    /// The lower bound.
355    pub min: f64,
356    /// The upper bound.
357    pub max: f64,
358}
359
360impl ChartDomain {
361    /// A domain from `min` to `max`.
362    pub fn new(min: f64, max: f64) -> Self {
363        Self { min, max }
364    }
365}
366
367/// Optional domain bounds; a missing bound is calculated from the data.
368#[derive(Clone, Copy, Debug, Default, PartialEq)]
369pub struct ChartBounds {
370    /// The requested lower bound.
371    pub min: Option<f64>,
372    /// The requested upper bound.
373    pub max: Option<f64>,
374}
375
376impl ChartBounds {
377    /// Both bounds.
378    pub fn new(min: f64, max: f64) -> Self {
379        Self {
380            min: Some(min),
381            max: Some(max),
382        }
383    }
384
385    /// Only the lower bound.
386    pub fn min(min: f64) -> Self {
387        Self {
388            min: Some(min),
389            max: None,
390        }
391    }
392
393    /// Only the upper bound.
394    pub fn max(max: f64) -> Self {
395        Self {
396            min: None,
397            max: Some(max),
398        }
399    }
400}
401
402impl From<ChartDomain> for ChartBounds {
403    fn from(domain: ChartDomain) -> Self {
404        Self::new(domain.min, domain.max)
405    }
406}
407
408/// Facts about a chart's data, passed to [`ChartLabels::format_summary`].
409#[derive(Clone, Debug, PartialEq)]
410pub struct ChartSummary {
411    /// Points with a finite value.
412    pub available_point_count: usize,
413    /// The largest finite value.
414    pub maximum: Option<f64>,
415    /// The smallest finite value.
416    pub minimum: Option<f64>,
417    /// Points without a finite value.
418    pub missing_point_count: usize,
419    /// The number of series.
420    pub series_count: usize,
421    /// `maximum` formatted with the chart's value formatter (`0` when missing).
422    pub maximum_label: String,
423    /// `minimum` formatted with the chart's value formatter (`0` when missing).
424    pub minimum_label: String,
425}
426
427/// The visible and assistive text of every chart. Override fields with struct update syntax:
428/// `ChartLabels { empty: "Nothing yet".into(), ..ChartLabels::default() }`.
429#[derive(Clone, PartialEq)]
430#[allow(missing_docs)]
431pub struct ChartLabels {
432    pub count: String,
433    pub density: String,
434    pub end: String,
435    pub invalid_data: String,
436    pub start: String,
437    pub category: String,
438    pub chart_data: String,
439    pub chart_legend: String,
440    pub column: String,
441    pub empty: String,
442    pub explore_data: String,
443    pub high: String,
444    pub low: String,
445    pub not_available: String,
446    pub row: String,
447    pub series: String,
448    pub size: String,
449    pub value: String,
450    pub view_data: String,
451    pub x: String,
452    /// The accessible name of a datum action button; receives the point's description.
453    pub format_datum_action: Option<Callback<String, String>>,
454    /// The heatmap summary for a count of available cells.
455    pub format_heatmap_summary: Option<Callback<usize, String>>,
456    /// The range chart summary for a count of available ranges.
457    pub format_range_summary: Option<Callback<usize, String>>,
458    /// The screen reader summary of series charts.
459    pub format_summary: Option<Callback<ChartSummary, String>>,
460}
461
462impl Default for ChartLabels {
463    fn default() -> Self {
464        Self {
465            count: "Count".into(),
466            density: "Frequency density".into(),
467            end: "End".into(),
468            invalid_data: "Chart data is invalid. Check the supplied values.".into(),
469            start: "Start".into(),
470            category: "Category".into(),
471            chart_data: "Chart data".into(),
472            chart_legend: "Chart legend".into(),
473            column: "Column".into(),
474            empty: "No chart data available.".into(),
475            explore_data: "Explore chart data".into(),
476            high: "High".into(),
477            low: "Low".into(),
478            not_available: "Not available".into(),
479            row: "Row".into(),
480            series: "Series".into(),
481            size: "Size".into(),
482            value: "Value".into(),
483            view_data: "View chart data".into(),
484            x: "X".into(),
485            format_datum_action: None,
486            format_heatmap_summary: None,
487            format_range_summary: None,
488            format_summary: None,
489        }
490    }
491}
492
493impl ChartLabels {
494    /// The accessible name of a datum action.
495    pub fn datum_action(&self, context: &str) -> String {
496        match &self.format_datum_action {
497            Some(format) => format.call(context.to_string()),
498            None => format!("Open details: {context}"),
499        }
500    }
501
502    /// The heatmap summary.
503    pub fn heatmap_summary(&self, count: usize) -> String {
504        match &self.format_heatmap_summary {
505            Some(format) => format.call(count),
506            None if count == 0 => "No chart data available.".to_string(),
507            None => format!(
508                "{count} available heatmap {}.",
509                if count == 1 { "cell" } else { "cells" }
510            ),
511        }
512    }
513
514    /// The range chart summary.
515    pub fn range_summary(&self, count: usize) -> String {
516        match &self.format_range_summary {
517            Some(format) => format.call(count),
518            None if count == 0 => "No chart data available.".to_string(),
519            None => format!(
520                "{count} available {}.",
521                if count == 1 { "range" } else { "ranges" }
522            ),
523        }
524    }
525
526    /// The series summary.
527    pub fn summary(&self, summary: ChartSummary) -> String {
528        if let Some(format) = &self.format_summary {
529            return format.call(summary);
530        }
531
532        if summary.available_point_count == 0 {
533            return "No chart data available.".to_string();
534        }
535
536        let points = if summary.available_point_count == 1 {
537            "point"
538        } else {
539            "points"
540        };
541        let missing = if summary.missing_point_count == 0 {
542            String::new()
543        } else {
544            format!(
545                " {} missing {}.",
546                summary.missing_point_count,
547                if summary.missing_point_count == 1 {
548                    "value"
549                } else {
550                    "values"
551                }
552            )
553        };
554
555        format!(
556            "{} series, {} {points}. Values range from {} to {}.{missing}",
557            summary.series_count,
558            summary.available_point_count,
559            summary.minimum_label,
560            summary.maximum_label
561        )
562    }
563}
564
565/// A value formatter: `formatValue` in lumen-react. Defaults to JavaScript's `String(value)`.
566pub(crate) fn format_with(formatter: Option<&Callback<f64, String>>, value: f64) -> String {
567    match formatter {
568        Some(format) => format.call(value),
569        None => js_number(value),
570    }
571}
572
573/// A category formatter: `formatCategory` in lumen-react.
574pub(crate) fn format_category_with(
575    formatter: Option<&Callback<ChartX, String>>,
576    value: &ChartX,
577) -> String {
578    match formatter {
579        Some(format) => format.call(value.clone()),
580        None => value.display(),
581    }
582}
583
584/// `summarizeLumenChart` plus the formatted extremes.
585pub(crate) fn summarize(
586    series: &[ChartSeries],
587    format_value: Option<&Callback<f64, String>>,
588) -> ChartSummary {
589    let mut available = 0;
590    let mut missing = 0;
591    let mut maximum = f64::NEG_INFINITY;
592    let mut minimum = f64::INFINITY;
593
594    for item in series {
595        for datum in &item.data {
596            match datum.value() {
597                Some(value) => {
598                    available += 1;
599                    maximum = maximum.max(value);
600                    minimum = minimum.min(value);
601                }
602                None => missing += 1,
603            }
604        }
605    }
606
607    let maximum = maximum.is_finite().then_some(maximum);
608    let minimum = minimum.is_finite().then_some(minimum);
609
610    ChartSummary {
611        available_point_count: available,
612        maximum,
613        minimum,
614        missing_point_count: missing,
615        series_count: series.len(),
616        maximum_label: format_with(format_value, maximum.unwrap_or(0.0)),
617        minimum_label: format_with(format_value, minimum.unwrap_or(0.0)),
618    }
619}
620
621#[cfg(test)]
622mod tests {
623    use super::{ChartDatum, ChartLabels, ChartSeries, ChartTone, ChartX, summarize};
624
625    #[test]
626    fn x_identity_follows_javascript() {
627        assert_eq!(ChartX::from(0.0), ChartX::from(-0.0));
628        assert_ne!(ChartX::Number(f64::NAN), ChartX::Number(f64::NAN));
629        assert_ne!(ChartX::from(1), ChartX::from("1"));
630        assert_eq!(ChartX::from(1.5).key(), "number:1.5");
631        assert_eq!(ChartX::from("Jan").key(), "string:Jan");
632        assert_eq!(ChartX::from(f64::NAN).json(), "null");
633        assert_eq!(ChartX::from("a\"b").typed_json(), "[\"string\",\"a\\\"b\"]");
634        assert!(!ChartX::from(f64::INFINITY).is_axis_value());
635    }
636
637    #[test]
638    fn tones_cycle_through_eight_series_colors() {
639        assert_eq!(ChartTone::resolve(None, 0), ChartTone::Series1);
640        assert_eq!(ChartTone::resolve(None, 9), ChartTone::Series2);
641        assert_eq!(
642            ChartTone::resolve(Some(ChartTone::Danger), 3),
643            ChartTone::Danger
644        );
645        assert_eq!(ChartTone::Series4.class_name(), "ui-chart-tone--series-4");
646    }
647
648    #[test]
649    fn summaries_count_available_and_missing_points() {
650        let series = vec![ChartSeries::new(
651            "a",
652            "A",
653            [
654                ChartDatum::new("x", 3.0),
655                ChartDatum::missing("y"),
656                ChartDatum::new("z", f64::NAN),
657                ChartDatum::new("w", -2.0),
658            ],
659        )];
660        let summary = summarize(&series, None);
661
662        assert_eq!(summary.available_point_count, 2);
663        assert_eq!(summary.missing_point_count, 2);
664        assert_eq!(
665            ChartLabels::default().summary(summary),
666            "1 series, 2 points. Values range from -2 to 3. 2 missing values."
667        );
668        assert_eq!(
669            ChartLabels::default().summary(summarize(&[], None)),
670            "No chart data available."
671        );
672    }
673}