lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! [`BulletChart`]: an actual value against a target over optional qualitative ranges.

use dioxus::prelude::*;

use super::super::format::{css_percent, js_number};
use super::super::frame::{ChartFrame, ChartPresentation, render_frame};
use super::super::model::{ChartDomain, ChartLabels, ChartTone, format_with};
use super::super::scale::{chart_ticks, nice_domain, scale_value};
use super::{empty_status, is_blank, tick_style};
use crate::class::{Glass, compose};

/// A qualitative band of a [`BulletChart`], such as "Poor" or "Good", ending at `end`.
#[derive(Clone, Debug, PartialEq)]
pub struct BulletChartRange {
    /// Where the band ends. Bands start where the previous band ends.
    pub end: f64,
    /// The non-blank band name.
    pub label: String,
    /// The band color; defaults to neutral.
    pub tone: Option<ChartTone>,
}

impl BulletChartRange {
    /// A band that ends at `end`.
    pub fn new(end: f64, label: impl Into<String>) -> Self {
        Self {
            end,
            label: label.into(),
            tone: None,
        }
    }

    /// Sets the band color.
    #[must_use]
    pub fn with_tone(mut self, tone: ChartTone) -> Self {
        self.tone = Some(tone);
        self
    }
}

/// Props for [`BulletChart`].
#[derive(Props, Clone, PartialEq)]
pub struct BulletChartProps {
    /// The actual value, or `None` when it is not known yet.
    pub value: Option<f64>,
    /// The target value.
    pub target: f64,
    /// Qualitative bands, sorted by their end.
    #[props(default)]
    pub ranges: Vec<BulletChartRange>,
    /// The scale. It must include zero and every value; automatic bounds round outward to
    /// readable ticks. Explicit bounds are preserved exactly.
    pub domain: Option<ChartDomain>,
    /// The name of the actual value. Defaults to the `value` label.
    #[props(into)]
    pub value_label: Option<String>,
    /// The name of the target.
    #[props(default = "Target".to_string(), into)]
    pub target_label: String,
    /// The color of the actual-value bar.
    #[props(default)]
    pub tone: ChartTone,
    /// Formats values. Defaults to JavaScript's `String(value)`.
    pub format_value: Option<Callback<f64, String>>,
    /// Visible and assistive text.
    pub labels: Option<ChartLabels>,
    /// Shows the collapsible data table.
    #[props(default = true)]
    pub show_table: bool,
    /// The chart title.
    #[props(into)]
    pub heading: Option<String>,
    /// Supporting text under the heading.
    #[props(into)]
    pub description: Option<String>,
    /// A screen reader summary; defaults to the value and target.
    #[props(into)]
    pub summary: Option<String>,
    /// A visible caption.
    #[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>,
}

/// A band with its start and positions on the `0..1` scale.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BulletSegment {
    pub(crate) range: BulletChartRange,
    pub(crate) start: f64,
    pub(crate) start_ratio: f64,
    pub(crate) end_ratio: f64,
}

/// `createLumenBulletGeometry`.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct BulletModel {
    pub(crate) valid: bool,
    pub(crate) domain: ChartDomain,
    pub(crate) ranges: Vec<BulletSegment>,
    pub(crate) target_ratio: f64,
    pub(crate) ticks: Vec<(f64, f64)>,
    pub(crate) value_start_ratio: f64,
    pub(crate) value_width_ratio: f64,
}

fn automatic_domain(values: &[f64]) -> ChartDomain {
    let (mut minimum, mut maximum) = (0.0_f64, 0.0_f64);

    for value in values.iter().filter(|value| value.is_finite()) {
        minimum = minimum.min(*value);
        maximum = maximum.max(*value);
    }

    ChartDomain::new(
        minimum,
        if maximum - minimum == 0.0 {
            minimum + 1.0
        } else {
            maximum
        },
    )
}

fn valid_domain(domain: ChartDomain) -> bool {
    domain.min.is_finite()
        && domain.max.is_finite()
        && domain.min < domain.max
        && domain.min <= 0.0
        && domain.max >= 0.0
}

pub(crate) fn bullet_geometry(
    value: Option<f64>,
    target: f64,
    ranges: &[BulletChartRange],
    domain: Option<ChartDomain>,
) -> BulletModel {
    let finite_ranges = ranges.iter().all(|range| range.end.is_finite());
    let mut sorted: Vec<BulletChartRange> = if finite_ranges {
        ranges.to_vec()
    } else {
        Vec::new()
    };
    sorted.sort_by(|left, right| left.end.total_cmp(&right.end));
    let mut values = vec![0.0, target];
    values.extend(sorted.iter().map(|range| range.end));
    values.extend(value);
    let requested = domain.unwrap_or_else(|| nice_domain(automatic_domain(&values)));
    let requested_valid = valid_domain(requested);
    let domain = if requested_valid {
        requested
    } else {
        ChartDomain::new(0.0, 1.0)
    };
    let within = values
        .iter()
        .all(|number| number.is_finite() && *number >= domain.min && *number <= domain.max);
    let mut previous_end = domain.min;
    let ordered = sorted.iter().all(|range| {
        let valid = !is_blank(&range.label) && range.end > previous_end;
        previous_end = range.end;
        valid
    });
    let valid = finite_ranges && requested_valid && within && ordered;
    let position = |number: f64| scale_value(number, domain, 0.0, 1.0);
    let zero = position(0.0);
    let actual = match value {
        Some(value) if valid => position(value),
        _ => zero,
    };
    let mut start = domain.min;
    let segments = if valid {
        sorted
            .into_iter()
            .map(|range| {
                let segment = BulletSegment {
                    start,
                    start_ratio: position(start),
                    end_ratio: position(range.end),
                    range,
                };
                start = segment.range.end;
                segment
            })
            .collect()
    } else {
        Vec::new()
    };

    BulletModel {
        valid,
        domain,
        ranges: segments,
        target_ratio: if valid { position(target) } else { zero },
        ticks: if valid {
            chart_ticks(domain)
                .into_iter()
                .map(|tick| (tick, position(tick)))
                .collect()
        } else {
            Vec::new()
        },
        value_start_ratio: zero.min(actual),
        value_width_ratio: (actual - zero).abs(),
    }
}

/// Progress toward a goal: the actual value as a bar, the target as a marker, and optional
/// qualitative bands behind them.
#[component]
pub fn BulletChart(props: BulletChartProps) -> Element {
    let labels = props.labels.clone().unwrap_or_default();
    let format_value = props.format_value;
    let format = |value: f64| format_with(format_value.as_ref(), value);
    let model = bullet_geometry(props.value, props.target, &props.ranges, props.domain);
    let title = props
        .value_label
        .clone()
        .unwrap_or_else(|| labels.value.clone());
    let actual = match props.value {
        Some(value) if model.valid => format(value),
        _ => labels.not_available.clone(),
    };
    let target = format(props.target);
    let factual = if model.valid {
        format!("{title}: {actual}. {}: {target}.", props.target_label)
    } else {
        labels.invalid_data.clone()
    };
    let frame = ChartFrame {
        chart_class: Some(compose([Some("ui-bullet-chart"), props.class.as_deref()])),
        heading: props.heading.clone(),
        description: props.description.clone(),
        value: None,
        summary: Some(props.summary.clone().unwrap_or(factual)),
        caption: props.caption.clone(),
        presentation: props.presentation,
        glass: props.glass,
        activation: false,
        attributes: props.attributes.clone(),
        on_mounted: None,
    };

    if !model.valid {
        return render_frame(frame, empty_status(&labels.invalid_data));
    }

    let count = model.ranges.len();
    let bands: Vec<(String, String, String, String)> = model
        .ranges
        .iter()
        .enumerate()
        .map(|(index, segment)| {
            #[allow(clippy::cast_precision_loss)]
            let opacity = 0.08 + index as f64 / count.saturating_sub(1).max(1) as f64 * 0.14;

            (
                js_number(segment.range.end),
                compose([
                    Some("ui-bullet-chart__range"),
                    Some(
                        segment
                            .range
                            .tone
                            .unwrap_or(ChartTone::Neutral)
                            .class_name(),
                    ),
                ]),
                format!(
                    "left:{};width:{};opacity:{}",
                    css_percent(segment.start_ratio),
                    css_percent(segment.end_ratio - segment.start_ratio),
                    js_number(opacity)
                ),
                format!("{}–{}", format(segment.start), format(segment.range.end)),
            )
        })
        .collect();
    let legend: Vec<(String, &'static str, String, String)> = model
        .ranges
        .iter()
        .zip(&bands)
        .map(|(segment, (key, _, _, span))| {
            (
                key.clone(),
                segment
                    .range
                    .tone
                    .unwrap_or(ChartTone::Neutral)
                    .class_name(),
                segment.range.label.clone(),
                span.clone(),
            )
        })
        .collect();
    let bar_class = compose([Some("ui-bullet-chart__bar"), Some(props.tone.class_name())]);
    let bar_style = format!(
        "left:{};width:{}",
        css_percent(model.value_start_ratio),
        css_percent(model.value_width_ratio)
    );
    let target_style = format!("left:{}", css_percent(model.target_ratio));
    let ticks: Vec<(String, String)> = model
        .ticks
        .iter()
        .map(|(tick, position)| (tick_style(*position), format(*tick)))
        .collect();
    let body = rsx! {
        div { class: "ui-bullet-chart__values",
            div {
                span { "{title}" }
                strong { "{actual}" }
            }
            p {
                span { class: "ui-bullet-chart__target-key", aria_hidden: "true" }
                "{props.target_label}"
                strong { "{target}" }
            }
        }
        div { aria_hidden: "true", class: "ui-bullet-chart__plot",
            div { class: "ui-bullet-chart__track",
                for (key, class, style, _) in bands.iter() {
                    span { key: "{key}", class: "{class}", style: "{style}" }
                }
                if props.value.is_some() {
                    span { class: "{bar_class}", style: "{bar_style}" }
                }
                span { class: "ui-bullet-chart__target", style: "{target_style}" }
            }
            div { class: "ui-bullet-chart__ticks",
                for (key, text) in ticks {
                    span { key: "{key}", style: "{key}", "{text}" }
                }
            }
        }
        if !legend.is_empty() {
            ul { class: "ui-bullet-chart__ranges",
                for (key, tone, label, span) in legend.iter() {
                    li { class: *tone, key: "{key}",
                        span { "{label}" }
                        span { "{span}" }
                    }
                }
            }
        }
        if props.show_table {
            details { class: "ui-chart__data",
                summary { "{labels.view_data}" }
                div { role: "group", tabindex: "0", aria_label: "{labels.chart_data}",
                    table {
                        thead {
                            tr {
                                th { scope: "col", "{labels.category}" }
                                th { scope: "col", "{labels.value}" }
                            }
                        }
                        tbody {
                            tr {
                                th { scope: "row", "{title}" }
                                td { "{actual}" }
                            }
                            tr {
                                th { scope: "row", "{props.target_label}" }
                                td { "{target}" }
                            }
                            for (key, _, label, span) in legend.iter() {
                                tr { key: "{key}",
                                    th { scope: "row", "{label}" }
                                    td { "{span}" }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    render_frame(frame, body)
}

#[cfg(test)]
mod tests {
    use super::{BulletChartRange, bullet_geometry};
    use crate::charts::model::ChartDomain;

    fn ranges() -> Vec<BulletChartRange> {
        vec![
            BulletChartRange::new(100.0, "Good"),
            BulletChartRange::new(50.0, "Poor"),
            BulletChartRange::new(75.0, "Fair"),
        ]
    }

    #[test]
    fn ranges_are_sorted_and_chained() {
        let model = bullet_geometry(Some(72.0), 80.0, &ranges(), None);
        assert!(model.valid);
        assert_eq!(model.domain, ChartDomain::new(0.0, 100.0));
        let starts: Vec<f64> = model.ranges.iter().map(|segment| segment.start).collect();
        assert_eq!(starts, vec![0.0, 50.0, 75.0]);
        assert!((model.target_ratio - 0.8).abs() < 1e-12);
        assert!((model.value_width_ratio - 0.72).abs() < 1e-12);
        assert_eq!(model.ticks.len(), 5);
    }

    #[test]
    fn negative_values_grow_left_from_zero() {
        let model = bullet_geometry(Some(-20.0), 10.0, &[], None);
        assert!(model.valid);
        assert_eq!(model.domain, ChartDomain::new(-20.0, 10.0));
        assert!(model.value_start_ratio.abs() < 1e-12);
        assert!((model.value_width_ratio - 2.0 / 3.0).abs() < 1e-12);
    }

    #[test]
    fn missing_values_and_zero_targets_stay_valid() {
        let model = bullet_geometry(None, 0.0, &[], None);
        assert!(model.valid);
        assert_eq!(model.domain, ChartDomain::new(0.0, 1.0));
        assert!(model.value_width_ratio.abs() < 1e-12);
    }

    #[test]
    fn nice_bounds_preserve_measurements_and_explicit_axes() {
        let automatic = bullet_geometry(Some(67.0), 83.0, &[], None);
        assert!(automatic.valid);
        assert_eq!(automatic.domain, ChartDomain::new(0.0, 100.0));
        assert_eq!(automatic.value_width_ratio, 0.67);
        assert_eq!(automatic.target_ratio, 0.83);

        let domain = ChartDomain::new(-3.0, 87.0);
        let exact = bullet_geometry(Some(67.0), 83.0, &[], Some(domain));
        assert!(exact.valid);
        assert_eq!(exact.domain, domain);
        assert_eq!(exact.ticks.len(), 5);
        for (value, position) in exact.ticks {
            assert_eq!(position, (value + 3.0) / 90.0);
        }
    }

    #[test]
    fn invalid_input_fails_closed() {
        let cases = [
            bullet_geometry(Some(30.0), 50.0, &[], Some(ChartDomain::new(10.0, 100.0))),
            bullet_geometry(Some(f64::NAN), 50.0, &[], None),
            bullet_geometry(Some(30.0), f64::INFINITY, &[], None),
            bullet_geometry(
                Some(30.0),
                50.0,
                &[BulletChartRange::new(f64::NAN, "A")],
                None,
            ),
            bullet_geometry(Some(30.0), 50.0, &[BulletChartRange::new(40.0, " ")], None),
            bullet_geometry(
                Some(30.0),
                50.0,
                &[
                    BulletChartRange::new(40.0, "A"),
                    BulletChartRange::new(40.0, "B"),
                ],
                None,
            ),
            bullet_geometry(Some(300.0), 50.0, &[], Some(ChartDomain::new(0.0, 100.0))),
        ];
        for model in cases {
            assert!(!model.valid);
            assert!(model.ranges.is_empty() && model.ticks.is_empty());
        }
    }
}