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};
#[derive(Clone, Debug, PartialEq)]
pub struct BulletChartRange {
pub end: f64,
pub label: String,
pub tone: Option<ChartTone>,
}
impl BulletChartRange {
pub fn new(end: f64, label: impl Into<String>) -> Self {
Self {
end,
label: label.into(),
tone: None,
}
}
#[must_use]
pub fn with_tone(mut self, tone: ChartTone) -> Self {
self.tone = Some(tone);
self
}
}
#[derive(Props, Clone, PartialEq)]
pub struct BulletChartProps {
pub value: Option<f64>,
pub target: f64,
#[props(default)]
pub ranges: Vec<BulletChartRange>,
pub domain: Option<ChartDomain>,
#[props(into)]
pub value_label: Option<String>,
#[props(default = "Target".to_string(), into)]
pub target_label: String,
#[props(default)]
pub tone: ChartTone,
pub format_value: Option<Callback<f64, String>>,
pub labels: Option<ChartLabels>,
#[props(default = true)]
pub show_table: bool,
#[props(into)]
pub heading: Option<String>,
#[props(into)]
pub description: Option<String>,
#[props(into)]
pub summary: Option<String>,
#[props(into)]
pub caption: Option<String>,
#[props(default)]
pub presentation: ChartPresentation,
#[props(default, into)]
pub glass: Glass,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = figure)]
pub attributes: Vec<Attribute>,
}
#[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,
}
#[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(),
}
}
#[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());
}
}
}