Skip to main content

lumen_dioxus/charts/extended/
bullet.rs

1//! [`BulletChart`]: an actual value against a target over optional qualitative ranges.
2
3use dioxus::prelude::*;
4
5use super::super::format::{css_percent, js_number};
6use super::super::frame::{ChartFrame, ChartPresentation, render_frame};
7use super::super::model::{ChartDomain, ChartLabels, ChartTone, format_with};
8use super::super::scale::{chart_ticks, nice_domain, scale_value};
9use super::{empty_status, is_blank, tick_style};
10use crate::class::{Glass, compose};
11
12/// A qualitative band of a [`BulletChart`], such as "Poor" or "Good", ending at `end`.
13#[derive(Clone, Debug, PartialEq)]
14pub struct BulletChartRange {
15    /// Where the band ends. Bands start where the previous band ends.
16    pub end: f64,
17    /// The non-blank band name.
18    pub label: String,
19    /// The band color; defaults to neutral.
20    pub tone: Option<ChartTone>,
21}
22
23impl BulletChartRange {
24    /// A band that ends at `end`.
25    pub fn new(end: f64, label: impl Into<String>) -> Self {
26        Self {
27            end,
28            label: label.into(),
29            tone: None,
30        }
31    }
32
33    /// Sets the band color.
34    #[must_use]
35    pub fn with_tone(mut self, tone: ChartTone) -> Self {
36        self.tone = Some(tone);
37        self
38    }
39}
40
41/// Props for [`BulletChart`].
42#[derive(Props, Clone, PartialEq)]
43pub struct BulletChartProps {
44    /// The actual value, or `None` when it is not known yet.
45    pub value: Option<f64>,
46    /// The target value.
47    pub target: f64,
48    /// Qualitative bands, sorted by their end.
49    #[props(default)]
50    pub ranges: Vec<BulletChartRange>,
51    /// The scale. It must include zero and every value; automatic bounds round outward to
52    /// readable ticks. Explicit bounds are preserved exactly.
53    pub domain: Option<ChartDomain>,
54    /// The name of the actual value. Defaults to the `value` label.
55    #[props(into)]
56    pub value_label: Option<String>,
57    /// The name of the target.
58    #[props(default = "Target".to_string(), into)]
59    pub target_label: String,
60    /// The color of the actual-value bar.
61    #[props(default)]
62    pub tone: ChartTone,
63    /// Formats values. Defaults to JavaScript's `String(value)`.
64    pub format_value: Option<Callback<f64, String>>,
65    /// Visible and assistive text.
66    pub labels: Option<ChartLabels>,
67    /// Shows the collapsible data table.
68    #[props(default = true)]
69    pub show_table: bool,
70    /// The chart title.
71    #[props(into)]
72    pub heading: Option<String>,
73    /// Supporting text under the heading.
74    #[props(into)]
75    pub description: Option<String>,
76    /// A screen reader summary; defaults to the value and target.
77    #[props(into)]
78    pub summary: Option<String>,
79    /// A visible caption.
80    #[props(into)]
81    pub caption: Option<String>,
82    /// `Bare` removes the card chrome.
83    #[props(default)]
84    pub presentation: ChartPresentation,
85    /// Glass intensity.
86    #[props(default, into)]
87    pub glass: Glass,
88    /// Extra classes appended after the Lumen classes.
89    #[props(into)]
90    pub class: Option<String>,
91    /// Any other `<figure>` or global attribute.
92    #[props(extends = GlobalAttributes, extends = figure)]
93    pub attributes: Vec<Attribute>,
94}
95
96/// A band with its start and positions on the `0..1` scale.
97#[derive(Clone, Debug, PartialEq)]
98pub(crate) struct BulletSegment {
99    pub(crate) range: BulletChartRange,
100    pub(crate) start: f64,
101    pub(crate) start_ratio: f64,
102    pub(crate) end_ratio: f64,
103}
104
105/// `createLumenBulletGeometry`.
106#[derive(Clone, Debug, PartialEq)]
107pub(crate) struct BulletModel {
108    pub(crate) valid: bool,
109    pub(crate) domain: ChartDomain,
110    pub(crate) ranges: Vec<BulletSegment>,
111    pub(crate) target_ratio: f64,
112    pub(crate) ticks: Vec<(f64, f64)>,
113    pub(crate) value_start_ratio: f64,
114    pub(crate) value_width_ratio: f64,
115}
116
117fn automatic_domain(values: &[f64]) -> ChartDomain {
118    let (mut minimum, mut maximum) = (0.0_f64, 0.0_f64);
119
120    for value in values.iter().filter(|value| value.is_finite()) {
121        minimum = minimum.min(*value);
122        maximum = maximum.max(*value);
123    }
124
125    ChartDomain::new(
126        minimum,
127        if maximum - minimum == 0.0 {
128            minimum + 1.0
129        } else {
130            maximum
131        },
132    )
133}
134
135fn valid_domain(domain: ChartDomain) -> bool {
136    domain.min.is_finite()
137        && domain.max.is_finite()
138        && domain.min < domain.max
139        && domain.min <= 0.0
140        && domain.max >= 0.0
141}
142
143pub(crate) fn bullet_geometry(
144    value: Option<f64>,
145    target: f64,
146    ranges: &[BulletChartRange],
147    domain: Option<ChartDomain>,
148) -> BulletModel {
149    let finite_ranges = ranges.iter().all(|range| range.end.is_finite());
150    let mut sorted: Vec<BulletChartRange> = if finite_ranges {
151        ranges.to_vec()
152    } else {
153        Vec::new()
154    };
155    sorted.sort_by(|left, right| left.end.total_cmp(&right.end));
156    let mut values = vec![0.0, target];
157    values.extend(sorted.iter().map(|range| range.end));
158    values.extend(value);
159    let requested = domain.unwrap_or_else(|| nice_domain(automatic_domain(&values)));
160    let requested_valid = valid_domain(requested);
161    let domain = if requested_valid {
162        requested
163    } else {
164        ChartDomain::new(0.0, 1.0)
165    };
166    let within = values
167        .iter()
168        .all(|number| number.is_finite() && *number >= domain.min && *number <= domain.max);
169    let mut previous_end = domain.min;
170    let ordered = sorted.iter().all(|range| {
171        let valid = !is_blank(&range.label) && range.end > previous_end;
172        previous_end = range.end;
173        valid
174    });
175    let valid = finite_ranges && requested_valid && within && ordered;
176    let position = |number: f64| scale_value(number, domain, 0.0, 1.0);
177    let zero = position(0.0);
178    let actual = match value {
179        Some(value) if valid => position(value),
180        _ => zero,
181    };
182    let mut start = domain.min;
183    let segments = if valid {
184        sorted
185            .into_iter()
186            .map(|range| {
187                let segment = BulletSegment {
188                    start,
189                    start_ratio: position(start),
190                    end_ratio: position(range.end),
191                    range,
192                };
193                start = segment.range.end;
194                segment
195            })
196            .collect()
197    } else {
198        Vec::new()
199    };
200
201    BulletModel {
202        valid,
203        domain,
204        ranges: segments,
205        target_ratio: if valid { position(target) } else { zero },
206        ticks: if valid {
207            chart_ticks(domain)
208                .into_iter()
209                .map(|tick| (tick, position(tick)))
210                .collect()
211        } else {
212            Vec::new()
213        },
214        value_start_ratio: zero.min(actual),
215        value_width_ratio: (actual - zero).abs(),
216    }
217}
218
219/// Progress toward a goal: the actual value as a bar, the target as a marker, and optional
220/// qualitative bands behind them.
221#[component]
222pub fn BulletChart(props: BulletChartProps) -> Element {
223    let labels = props.labels.clone().unwrap_or_default();
224    let format_value = props.format_value;
225    let format = |value: f64| format_with(format_value.as_ref(), value);
226    let model = bullet_geometry(props.value, props.target, &props.ranges, props.domain);
227    let title = props
228        .value_label
229        .clone()
230        .unwrap_or_else(|| labels.value.clone());
231    let actual = match props.value {
232        Some(value) if model.valid => format(value),
233        _ => labels.not_available.clone(),
234    };
235    let target = format(props.target);
236    let factual = if model.valid {
237        format!("{title}: {actual}. {}: {target}.", props.target_label)
238    } else {
239        labels.invalid_data.clone()
240    };
241    let frame = ChartFrame {
242        chart_class: Some(compose([Some("ui-bullet-chart"), props.class.as_deref()])),
243        heading: props.heading.clone(),
244        description: props.description.clone(),
245        value: None,
246        summary: Some(props.summary.clone().unwrap_or(factual)),
247        caption: props.caption.clone(),
248        presentation: props.presentation,
249        glass: props.glass,
250        activation: false,
251        attributes: props.attributes.clone(),
252        on_mounted: None,
253    };
254
255    if !model.valid {
256        return render_frame(frame, empty_status(&labels.invalid_data));
257    }
258
259    let count = model.ranges.len();
260    let bands: Vec<(String, String, String, String)> = model
261        .ranges
262        .iter()
263        .enumerate()
264        .map(|(index, segment)| {
265            #[allow(clippy::cast_precision_loss)]
266            let opacity = 0.08 + index as f64 / count.saturating_sub(1).max(1) as f64 * 0.14;
267
268            (
269                js_number(segment.range.end),
270                compose([
271                    Some("ui-bullet-chart__range"),
272                    Some(
273                        segment
274                            .range
275                            .tone
276                            .unwrap_or(ChartTone::Neutral)
277                            .class_name(),
278                    ),
279                ]),
280                format!(
281                    "left:{};width:{};opacity:{}",
282                    css_percent(segment.start_ratio),
283                    css_percent(segment.end_ratio - segment.start_ratio),
284                    js_number(opacity)
285                ),
286                format!("{}–{}", format(segment.start), format(segment.range.end)),
287            )
288        })
289        .collect();
290    let legend: Vec<(String, &'static str, String, String)> = model
291        .ranges
292        .iter()
293        .zip(&bands)
294        .map(|(segment, (key, _, _, span))| {
295            (
296                key.clone(),
297                segment
298                    .range
299                    .tone
300                    .unwrap_or(ChartTone::Neutral)
301                    .class_name(),
302                segment.range.label.clone(),
303                span.clone(),
304            )
305        })
306        .collect();
307    let bar_class = compose([Some("ui-bullet-chart__bar"), Some(props.tone.class_name())]);
308    let bar_style = format!(
309        "left:{};width:{}",
310        css_percent(model.value_start_ratio),
311        css_percent(model.value_width_ratio)
312    );
313    let target_style = format!("left:{}", css_percent(model.target_ratio));
314    let ticks: Vec<(String, String)> = model
315        .ticks
316        .iter()
317        .map(|(tick, position)| (tick_style(*position), format(*tick)))
318        .collect();
319    let body = rsx! {
320        div { class: "ui-bullet-chart__values",
321            div {
322                span { "{title}" }
323                strong { "{actual}" }
324            }
325            p {
326                span { class: "ui-bullet-chart__target-key", aria_hidden: "true" }
327                "{props.target_label}"
328                strong { "{target}" }
329            }
330        }
331        div { aria_hidden: "true", class: "ui-bullet-chart__plot",
332            div { class: "ui-bullet-chart__track",
333                for (key, class, style, _) in bands.iter() {
334                    span { key: "{key}", class: "{class}", style: "{style}" }
335                }
336                if props.value.is_some() {
337                    span { class: "{bar_class}", style: "{bar_style}" }
338                }
339                span { class: "ui-bullet-chart__target", style: "{target_style}" }
340            }
341            div { class: "ui-bullet-chart__ticks",
342                for (key, text) in ticks {
343                    span { key: "{key}", style: "{key}", "{text}" }
344                }
345            }
346        }
347        if !legend.is_empty() {
348            ul { class: "ui-bullet-chart__ranges",
349                for (key, tone, label, span) in legend.iter() {
350                    li { class: *tone, key: "{key}",
351                        span { "{label}" }
352                        span { "{span}" }
353                    }
354                }
355            }
356        }
357        if props.show_table {
358            details { class: "ui-chart__data",
359                summary { "{labels.view_data}" }
360                div { role: "group", tabindex: "0", aria_label: "{labels.chart_data}",
361                    table {
362                        thead {
363                            tr {
364                                th { scope: "col", "{labels.category}" }
365                                th { scope: "col", "{labels.value}" }
366                            }
367                        }
368                        tbody {
369                            tr {
370                                th { scope: "row", "{title}" }
371                                td { "{actual}" }
372                            }
373                            tr {
374                                th { scope: "row", "{props.target_label}" }
375                                td { "{target}" }
376                            }
377                            for (key, _, label, span) in legend.iter() {
378                                tr { key: "{key}",
379                                    th { scope: "row", "{label}" }
380                                    td { "{span}" }
381                                }
382                            }
383                        }
384                    }
385                }
386            }
387        }
388    };
389
390    render_frame(frame, body)
391}
392
393#[cfg(test)]
394mod tests {
395    use super::{BulletChartRange, bullet_geometry};
396    use crate::charts::model::ChartDomain;
397
398    fn ranges() -> Vec<BulletChartRange> {
399        vec![
400            BulletChartRange::new(100.0, "Good"),
401            BulletChartRange::new(50.0, "Poor"),
402            BulletChartRange::new(75.0, "Fair"),
403        ]
404    }
405
406    #[test]
407    fn ranges_are_sorted_and_chained() {
408        let model = bullet_geometry(Some(72.0), 80.0, &ranges(), None);
409        assert!(model.valid);
410        assert_eq!(model.domain, ChartDomain::new(0.0, 100.0));
411        let starts: Vec<f64> = model.ranges.iter().map(|segment| segment.start).collect();
412        assert_eq!(starts, vec![0.0, 50.0, 75.0]);
413        assert!((model.target_ratio - 0.8).abs() < 1e-12);
414        assert!((model.value_width_ratio - 0.72).abs() < 1e-12);
415        assert_eq!(model.ticks.len(), 5);
416    }
417
418    #[test]
419    fn negative_values_grow_left_from_zero() {
420        let model = bullet_geometry(Some(-20.0), 10.0, &[], None);
421        assert!(model.valid);
422        assert_eq!(model.domain, ChartDomain::new(-20.0, 10.0));
423        assert!(model.value_start_ratio.abs() < 1e-12);
424        assert!((model.value_width_ratio - 2.0 / 3.0).abs() < 1e-12);
425    }
426
427    #[test]
428    fn missing_values_and_zero_targets_stay_valid() {
429        let model = bullet_geometry(None, 0.0, &[], None);
430        assert!(model.valid);
431        assert_eq!(model.domain, ChartDomain::new(0.0, 1.0));
432        assert!(model.value_width_ratio.abs() < 1e-12);
433    }
434
435    #[test]
436    fn nice_bounds_preserve_measurements_and_explicit_axes() {
437        let automatic = bullet_geometry(Some(67.0), 83.0, &[], None);
438        assert!(automatic.valid);
439        assert_eq!(automatic.domain, ChartDomain::new(0.0, 100.0));
440        assert_eq!(automatic.value_width_ratio, 0.67);
441        assert_eq!(automatic.target_ratio, 0.83);
442
443        let domain = ChartDomain::new(-3.0, 87.0);
444        let exact = bullet_geometry(Some(67.0), 83.0, &[], Some(domain));
445        assert!(exact.valid);
446        assert_eq!(exact.domain, domain);
447        assert_eq!(exact.ticks.len(), 5);
448        for (value, position) in exact.ticks {
449            assert_eq!(position, (value + 3.0) / 90.0);
450        }
451    }
452
453    #[test]
454    fn invalid_input_fails_closed() {
455        let cases = [
456            bullet_geometry(Some(30.0), 50.0, &[], Some(ChartDomain::new(10.0, 100.0))),
457            bullet_geometry(Some(f64::NAN), 50.0, &[], None),
458            bullet_geometry(Some(30.0), f64::INFINITY, &[], None),
459            bullet_geometry(
460                Some(30.0),
461                50.0,
462                &[BulletChartRange::new(f64::NAN, "A")],
463                None,
464            ),
465            bullet_geometry(Some(30.0), 50.0, &[BulletChartRange::new(40.0, " ")], None),
466            bullet_geometry(
467                Some(30.0),
468                50.0,
469                &[
470                    BulletChartRange::new(40.0, "A"),
471                    BulletChartRange::new(40.0, "B"),
472                ],
473                None,
474            ),
475            bullet_geometry(Some(300.0), 50.0, &[], Some(ChartDomain::new(0.0, 100.0))),
476        ];
477        for model in cases {
478            assert!(!model.valid);
479            assert!(model.ranges.is_empty() && model.ticks.is_empty());
480        }
481    }
482}