1use std::collections::HashSet;
4
5use dioxus::prelude::*;
6
7use super::super::format::css_percent;
8use super::super::frame::{ChartPresentation, render_frame};
9use super::super::model::{ChartDomain, ChartLabels, ChartTone, format_with};
10use super::super::scale::{chart_ticks, nice_domain, scale_value};
11use super::{empty_status, is_blank, summary_table, tick_style};
12use crate::class::{Glass, compose};
13
14#[derive(Clone, Debug, PartialEq)]
16pub struct BoxPlotDatum {
17 pub id: String,
19 pub label: String,
21 pub min: Option<f64>,
23 pub q1: Option<f64>,
25 pub median: Option<f64>,
27 pub q3: Option<f64>,
29 pub max: Option<f64>,
31 pub outliers: Vec<f64>,
33 pub tone: Option<ChartTone>,
35}
36
37impl BoxPlotDatum {
38 pub fn new(
40 id: impl Into<String>,
41 label: impl Into<String>,
42 [min, q1, median, q3, max]: [f64; 5],
43 ) -> Self {
44 Self {
45 id: id.into(),
46 label: label.into(),
47 min: Some(min),
48 q1: Some(q1),
49 median: Some(median),
50 q3: Some(q3),
51 max: Some(max),
52 outliers: Vec::new(),
53 tone: None,
54 }
55 }
56
57 pub fn missing(id: impl Into<String>, label: impl Into<String>) -> Self {
59 Self {
60 id: id.into(),
61 label: label.into(),
62 min: None,
63 q1: None,
64 median: None,
65 q3: None,
66 max: None,
67 outliers: Vec::new(),
68 tone: None,
69 }
70 }
71
72 #[must_use]
74 pub fn with_outliers(mut self, outliers: impl IntoIterator<Item = f64>) -> Self {
75 self.outliers = outliers.into_iter().collect();
76 self
77 }
78
79 #[must_use]
81 pub fn with_tone(mut self, tone: ChartTone) -> Self {
82 self.tone = Some(tone);
83 self
84 }
85
86 fn statistics(&self) -> [Option<f64>; 5] {
87 [self.min, self.q1, self.median, self.q3, self.max]
88 }
89}
90
91#[derive(Clone, Debug, PartialEq)]
93pub struct BoxPlotStatisticLabels {
94 pub min: String,
96 pub q1: String,
98 pub median: String,
100 pub q3: String,
102 pub max: String,
104 pub outliers: String,
106}
107
108impl Default for BoxPlotStatisticLabels {
109 fn default() -> Self {
110 Self {
111 min: "Lower whisker".into(),
112 q1: "First quartile".into(),
113 median: "Median".into(),
114 q3: "Third quartile".into(),
115 max: "Upper whisker".into(),
116 outliers: "Outliers".into(),
117 }
118 }
119}
120
121impl BoxPlotStatisticLabels {
122 fn statistics(&self) -> [&str; 5] {
123 [&self.min, &self.q1, &self.median, &self.q3, &self.max]
124 }
125}
126
127#[derive(Props, Clone, PartialEq)]
129pub struct BoxPlotProps {
130 #[props(default)]
133 pub data: Vec<BoxPlotDatum>,
134 pub domain: Option<ChartDomain>,
136 pub statistic_labels: Option<BoxPlotStatisticLabels>,
138 pub format_value: Option<Callback<f64, String>>,
140 pub labels: Option<ChartLabels>,
142 #[props(default = true)]
144 pub show_table: bool,
145 #[props(into)]
147 pub heading: Option<String>,
148 #[props(into)]
150 pub description: Option<String>,
151 #[props(into)]
153 pub value: Option<String>,
154 #[props(into)]
156 pub summary: Option<String>,
157 #[props(into)]
159 pub caption: Option<String>,
160 #[props(default)]
162 pub presentation: ChartPresentation,
163 #[props(default, into)]
165 pub glass: Glass,
166 #[props(into)]
168 pub class: Option<String>,
169 #[props(extends = GlobalAttributes, extends = figure)]
171 pub attributes: Vec<Attribute>,
172}
173
174#[derive(Clone, Debug, PartialEq)]
176pub(crate) struct BoxRow {
177 pub(crate) datum: BoxPlotDatum,
178 pub(crate) positions: [Option<f64>; 5],
179 pub(crate) outlier_positions: Vec<f64>,
180}
181
182#[derive(Clone, Debug, PartialEq)]
184pub(crate) struct BoxModel {
185 pub(crate) valid: bool,
186 pub(crate) domain: ChartDomain,
187 pub(crate) ticks: Vec<f64>,
188 pub(crate) rows: Vec<BoxRow>,
189}
190
191fn valid_row(datum: &BoxPlotDatum) -> bool {
192 if is_blank(&datum.id) || is_blank(&datum.label) {
193 return false;
194 }
195
196 let statistics = datum.statistics();
197 let missing = statistics.iter().all(Option::is_none);
198 let ordered = statistics.iter().enumerate().all(|(index, value)| {
199 value.is_some_and(f64::is_finite)
200 && (index == 0 || matches!((statistics[index - 1], value), (Some(previous), Some(current)) if *current >= previous))
201 });
202
203 (missing || ordered)
204 && datum.outliers.iter().all(|value| value.is_finite())
205 && (!missing || datum.outliers.is_empty())
206}
207
208fn automatic_domain(values: &[f64]) -> ChartDomain {
210 let Some(first) = values.first() else {
211 return ChartDomain::new(0.0, 1.0);
212 };
213 let (mut min, mut max) = (*first, *first);
214
215 for value in values {
216 min = min.min(*value);
217 max = max.max(*value);
218 }
219
220 if max - min == 0.0 {
222 let padding = (min.abs() * 0.01).max(1.0);
223 let lower = min - padding;
224 let upper = max + padding;
225 min = if lower.is_finite() { lower } else { min };
226 max = if upper.is_finite() { upper } else { max };
227 }
228
229 ChartDomain::new(min, max)
230}
231
232fn encloses(domain: ChartDomain, values: &[f64]) -> bool {
233 domain.min.is_finite()
234 && domain.max.is_finite()
235 && domain.min < domain.max
236 && values
237 .iter()
238 .all(|value| domain.min <= *value && *value <= domain.max)
239}
240
241pub(crate) fn box_geometry(data: &[BoxPlotDatum], domain: Option<ChartDomain>) -> BoxModel {
242 let mut ids = HashSet::new();
243 let valid_data = data
244 .iter()
245 .all(|datum| valid_row(datum) && ids.insert(datum.id.as_str()));
246 let values: Vec<f64> = if valid_data {
247 data.iter()
248 .flat_map(|datum| {
249 datum
250 .statistics()
251 .into_iter()
252 .flatten()
253 .chain(datum.outliers.iter().copied())
254 })
255 .collect()
256 } else {
257 Vec::new()
258 };
259 let requested = domain.unwrap_or_else(|| nice_domain(automatic_domain(&values)));
260 let valid = valid_data && encloses(requested, &values);
261 let domain = if valid {
262 requested
263 } else {
264 ChartDomain::new(0.0, 1.0)
265 };
266 let position = |value: f64| scale_value(value, domain, 0.0, 1.0);
267 let rows = if valid {
268 data.iter()
269 .map(|datum| BoxRow {
270 positions: datum.statistics().map(|value| value.map(position)),
271 outlier_positions: datum
272 .outliers
273 .iter()
274 .map(|value| position(*value))
275 .collect(),
276 datum: datum.clone(),
277 })
278 .collect()
279 } else {
280 Vec::new()
281 };
282
283 BoxModel {
284 valid,
285 domain,
286 ticks: chart_ticks(domain),
287 rows,
288 }
289}
290
291fn unique_positions(positions: &[f64]) -> Vec<f64> {
293 let mut unique: Vec<f64> = Vec::new();
294
295 for position in positions {
296 let position = if *position == 0.0 { 0.0 } else { *position };
298
299 if !unique
300 .iter()
301 .any(|seen| seen.to_bits() == position.to_bits())
302 {
303 unique.push(position);
304 }
305 }
306
307 unique
308}
309
310#[derive(Clone, PartialEq)]
312struct BoxView {
313 id: String,
314 label: String,
315 tone: &'static str,
316 median: String,
317 whisker: Option<String>,
318 box_style: Option<String>,
319 median_left: Option<String>,
320 caps: Vec<(&'static str, String)>,
321 outliers: Vec<String>,
322 cells: Vec<(&'static str, String)>,
323 outlier_text: String,
324 exact: String,
325}
326
327#[component]
330pub fn BoxPlot(props: BoxPlotProps) -> Element {
331 let labels = props.labels.clone().unwrap_or_default();
332 let names = props.statistic_labels.clone().unwrap_or_default();
333 let format_value = props.format_value;
334 let model = box_geometry(&props.data, props.domain);
335 let format = |value: Option<f64>| match value {
336 Some(value) => format_with(format_value.as_ref(), value),
337 None => labels.not_available.clone(),
338 };
339 let keys = ["min", "q1", "median", "q3", "max"];
340 let views: Vec<BoxView> = model
341 .rows
342 .iter()
343 .enumerate()
344 .map(|(index, row)| {
345 let statistics = row.datum.statistics();
346 let [min, q1, median, q3, max] = row.positions;
347 let outlier_text = row
348 .datum
349 .outliers
350 .iter()
351 .map(|value| format_with(format_value.as_ref(), *value))
352 .collect::<Vec<_>>()
353 .join(", ");
354 let outlier_text = if outlier_text.is_empty() {
355 "—".to_string()
356 } else {
357 outlier_text
358 };
359 let parts = names
360 .statistics()
361 .iter()
362 .zip(statistics)
363 .map(|(name, value)| format!("{name}: {}", format(value)))
364 .collect::<Vec<_>>()
365 .join(", ");
366
367 BoxView {
368 id: row.datum.id.clone(),
369 label: row.datum.label.clone(),
370 tone: ChartTone::resolve(row.datum.tone, index).class_name(),
371 median: format(row.datum.median),
372 whisker: min.zip(max).map(|(min, max)| {
373 format!("left:{};width:{}", css_percent(min), css_percent(max - min))
374 }),
375 box_style: q1.zip(q3).map(|(q1, q3)| {
376 format!("left:{};width:{}", css_percent(q1), css_percent(q3 - q1))
377 }),
378 median_left: median.map(css_percent),
379 caps: [("min", min), ("max", max)]
380 .into_iter()
381 .filter_map(|(key, position)| {
382 position.map(|position| (key, css_percent(position)))
383 })
384 .collect(),
385 outliers: unique_positions(&row.outlier_positions)
386 .into_iter()
387 .map(css_percent)
388 .collect(),
389 cells: keys.iter().copied().zip(statistics.map(format)).collect(),
390 exact: format!(
391 "{}: {parts}. {}: {outlier_text}",
392 row.datum.label, names.outliers
393 ),
394 outlier_text,
395 }
396 })
397 .collect();
398 let summary = props.summary.clone().or_else(|| {
399 Some(if model.valid {
400 views
401 .iter()
402 .map(|view| view.exact.clone())
403 .collect::<Vec<_>>()
404 .join(". ")
405 } else {
406 labels.invalid_data.clone()
407 })
408 });
409 let class = compose([Some("ui-box-plot"), props.class.as_deref()]);
410 let frame = super::super::frame::chart_frame!(props, class, summary);
411
412 if !model.valid || model.rows.is_empty() {
413 let message = if model.valid {
414 &labels.empty
415 } else {
416 &labels.invalid_data
417 };
418
419 return render_frame(frame, empty_status(message));
420 }
421
422 let ticks: Vec<(String, String)> = model
423 .ticks
424 .iter()
425 .map(|tick| {
426 (
427 tick_style(scale_value(*tick, model.domain, 0.0, 1.0)),
428 format_with(format_value.as_ref(), *tick),
429 )
430 })
431 .collect();
432 let mut headings = vec![("category", labels.category.clone())];
433 headings.extend(
434 keys.iter()
435 .copied()
436 .zip(names.statistics().map(str::to_string)),
437 );
438 headings.push(("outliers", names.outliers.clone()));
439 let details = if props.show_table {
440 summary_table(
441 &labels,
442 &headings,
443 rsx! {
444 for view in views.iter() {
445 tr { key: "{view.id}",
446 th { scope: "row", "{view.label}" }
447 for (key, text) in view.cells.iter() {
448 td { key: "{key}", "{text}" }
449 }
450 td { "{view.outlier_text}" }
451 }
452 }
453 },
454 )
455 } else {
456 rsx! {
457 ul { class: "ui-sr-only",
458 for view in views.iter() {
459 li { key: "{view.id}", "{view.exact}" }
460 }
461 }
462 }
463 };
464 let body = rsx! {
465 ul { class: "ui-box-plot__rows",
466 for view in views.iter() {
467 li { key: "{view.id}", class: view.tone,
468 div { class: "ui-box-plot__label",
469 span { "{view.label}" }
470 strong { "{names.median}: {view.median}" }
471 }
472 div { class: "ui-box-plot__track", aria_hidden: "true",
473 if let Some(style) = &view.whisker {
474 span { class: "ui-box-plot__whisker", style: "{style}" }
475 }
476 if let Some(style) = &view.box_style {
477 span { class: "ui-box-plot__box", style: "{style}" }
478 }
479 if let Some(left) = &view.median_left {
480 span { class: "ui-box-plot__median", style: "left:{left}" }
481 }
482 for (key, left) in view.caps.iter() {
483 span { key: "{key}", class: "ui-box-plot__cap", style: "left:{left}" }
484 }
485 for left in view.outliers.iter() {
486 span { key: "{left}", class: "ui-box-plot__outlier", style: "left:{left}" }
487 }
488 }
489 }
490 }
491 }
492 div { class: "ui-bullet-chart__ticks", aria_hidden: "true",
493 for (key, text) in ticks {
494 span { key: "{key}", style: "{key}", "{text}" }
495 }
496 }
497 {details}
498 };
499
500 render_frame(frame, body)
501}
502
503#[cfg(test)]
504mod tests {
505 use super::{BoxPlotDatum, box_geometry, unique_positions};
506 use crate::charts::model::ChartDomain;
507
508 fn api() -> BoxPlotDatum {
509 BoxPlotDatum::new("api", "API", [40.0, 120.0, 180.0, 260.0, 410.0])
510 .with_outliers([520.0, 610.0])
511 }
512
513 #[test]
514 fn rows_share_one_domain() {
515 let model = box_geometry(&[api(), BoxPlotDatum::missing("jobs", "Jobs")], None);
516 assert!(model.valid);
517 assert_eq!(model.domain, ChartDomain::new(0.0, 750.0));
518 assert_eq!(model.ticks, vec![0.0, 250.0, 500.0, 750.0]);
519 assert_eq!(model.rows[0].positions[0], Some(40.0 / 750.0));
520 assert_eq!(model.rows[0].outlier_positions[1], 610.0 / 750.0);
521 assert_eq!(model.rows[1].positions, [None; 5]);
522 }
523
524 #[test]
525 fn negative_and_flat_rows_are_supported() {
526 let flat = box_geometry(&[BoxPlotDatum::new("a", "A", [-5.0; 5])], None);
527 assert!(flat.valid);
528 assert_eq!(flat.domain, ChartDomain::new(-6.0, -4.0));
529 let empty = box_geometry(&[], None);
530 assert!(empty.valid && empty.rows.is_empty());
531 assert_eq!(empty.domain, ChartDomain::new(0.0, 1.0));
532 }
533
534 #[test]
535 fn exact_bounds_keep_whiskers_and_outliers_on_the_same_scale() {
536 let domain = ChartDomain::new(39.0, 611.0);
537 let model = box_geometry(&[api()], Some(domain));
538 assert!(model.valid);
539 assert_eq!(model.domain, domain);
540 assert_eq!(model.rows[0].positions[0], Some(1.0 / 572.0));
541 assert_eq!(model.rows[0].outlier_positions[1], 571.0 / 572.0);
542 assert_eq!(model.ticks, vec![100.0, 200.0, 300.0, 400.0, 500.0, 600.0]);
543 }
544
545 #[test]
546 fn invalid_rows_fail_closed() {
547 let mut partial = api();
548 partial.q1 = None;
549 let unordered = BoxPlotDatum::new("a", "A", [1.0, 2.0, 5.0, 4.0, 3.0]);
550 let infinite = BoxPlotDatum::new("a", "A", [1.0, 2.0, 3.0, 4.0, f64::INFINITY]);
551 let missing_with_outliers = BoxPlotDatum::missing("a", "A").with_outliers([1.0]);
552 let nan_outlier = api().with_outliers([f64::NAN]);
553 for data in [
554 vec![partial],
555 vec![unordered],
556 vec![infinite],
557 vec![missing_with_outliers],
558 vec![nan_outlier],
559 vec![api(), api()],
560 ] {
561 let model = box_geometry(&data, None);
562 assert!(!model.valid && model.rows.is_empty());
563 assert_eq!(model.domain, ChartDomain::new(0.0, 1.0));
564 }
565 assert!(!box_geometry(&[api()], Some(ChartDomain::new(0.0, 500.0))).valid);
566 assert!(!box_geometry(&[api()], Some(ChartDomain::new(f64::NAN, 900.0))).valid);
567 }
568
569 #[test]
570 fn duplicate_outlier_positions_render_once() {
571 assert_eq!(
572 unique_positions(&[0.5, 0.5, -0.0, 0.0, 1.0]),
573 vec![0.5, 0.0, 1.0]
574 );
575 }
576}