1use std::collections::HashSet;
4
5use dioxus::prelude::*;
6
7use super::super::format::js_number;
8use super::super::frame::{ChartPresentation, plot_label, render_frame};
9use super::super::model::{
10 ChartDatum, ChartDomain, ChartLabels, ChartSeries, ChartTone, format_with, summarize,
11};
12use super::super::scale::{
13 CategoryTick, CategoryTickOptions, TickFormatter, axis_domain, axis_padding, category_ticks,
14 chart_ticks, estimate_chart_label_width, format_ticks, scale_value,
15};
16use super::empty_status;
17use crate::class::{Glass, compose};
18
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum WaterfallChartKind {
23 #[default]
25 Delta,
26 Total,
28}
29
30#[derive(Clone, Debug, PartialEq)]
32pub struct WaterfallChartDatum {
33 pub id: String,
35 pub label: String,
37 pub value: f64,
39 pub kind: WaterfallChartKind,
41 pub tone: Option<ChartTone>,
44}
45
46impl WaterfallChartDatum {
47 pub fn delta(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
49 Self {
50 id: id.into(),
51 label: label.into(),
52 value,
53 kind: WaterfallChartKind::Delta,
54 tone: None,
55 }
56 }
57
58 pub fn total(id: impl Into<String>, label: impl Into<String>, value: f64) -> Self {
60 Self {
61 kind: WaterfallChartKind::Total,
62 ..Self::delta(id, label, value)
63 }
64 }
65
66 #[must_use]
68 pub fn with_tone(mut self, tone: ChartTone) -> Self {
69 self.tone = Some(tone);
70 self
71 }
72}
73
74#[derive(Clone, Debug, PartialEq)]
76pub struct HistogramBin {
77 pub start: f64,
79 pub end: f64,
81 pub count: f64,
83 pub label: Option<String>,
85}
86
87impl HistogramBin {
88 pub fn new(start: f64, end: f64, count: f64) -> Self {
90 Self {
91 start,
92 end,
93 count,
94 label: None,
95 }
96 }
97
98 #[must_use]
100 pub fn with_label(mut self, label: impl Into<String>) -> Self {
101 self.label = Some(label.into());
102 self
103 }
104}
105
106#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108#[non_exhaustive]
109pub enum HistogramFrequency {
110 #[default]
112 Count,
113 Density,
115}
116
117#[derive(Props, Clone, PartialEq)]
119pub struct WaterfallChartProps {
120 #[props(default)]
123 pub data: Vec<WaterfallChartDatum>,
124 #[props(into)]
126 pub value_label: Option<String>,
127 pub format_value: Option<Callback<f64, String>>,
130 pub labels: Option<ChartLabels>,
132 #[props(default = true)]
134 pub show_table: bool,
135 #[props(into)]
137 pub heading: Option<String>,
138 #[props(into)]
140 pub description: Option<String>,
141 #[props(into)]
143 pub value: Option<String>,
144 #[props(into)]
146 pub summary: Option<String>,
147 #[props(into)]
149 pub caption: Option<String>,
150 #[props(default)]
152 pub presentation: ChartPresentation,
153 #[props(default, into)]
155 pub glass: Glass,
156 #[props(into)]
158 pub class: Option<String>,
159 #[props(extends = GlobalAttributes, extends = figure)]
161 pub attributes: Vec<Attribute>,
162}
163
164#[derive(Props, Clone, PartialEq)]
166pub struct HistogramProps {
167 #[props(default)]
170 pub bins: Vec<HistogramBin>,
171 #[props(default)]
173 pub frequency: HistogramFrequency,
174 #[props(default)]
176 pub tone: ChartTone,
177 #[props(into)]
179 pub value_label: Option<String>,
180 pub format_boundary: Option<Callback<f64, String>>,
183 pub format_value: Option<Callback<f64, String>>,
186 pub labels: Option<ChartLabels>,
188 #[props(default = true)]
190 pub show_table: bool,
191 #[props(into)]
193 pub heading: Option<String>,
194 #[props(into)]
196 pub description: Option<String>,
197 #[props(into)]
199 pub value: Option<String>,
200 #[props(into)]
202 pub summary: Option<String>,
203 #[props(into)]
205 pub caption: Option<String>,
206 #[props(default)]
208 pub presentation: ChartPresentation,
209 #[props(default, into)]
211 pub glass: Glass,
212 #[props(into)]
214 pub class: Option<String>,
215 #[props(extends = GlobalAttributes, extends = figure)]
217 pub attributes: Vec<Attribute>,
218}
219
220const INTERVAL_PADDING_TOP: f64 = 16.0;
222
223#[derive(Clone, Debug, PartialEq)]
225pub(crate) struct IntervalFrame {
226 pub(crate) width: f64,
227 pub(crate) height: f64,
228 pub(crate) axis_font_size: f64,
230 pub(crate) domain: ChartDomain,
231 pub(crate) ticks: Vec<f64>,
232 pub(crate) tick_labels: Vec<String>,
233 pub(crate) left: f64,
234 pub(crate) top: f64,
235 pub(crate) right: f64,
236 pub(crate) bottom: f64,
237}
238
239impl IntervalFrame {
240 fn new(
243 values: &[f64],
244 format_value: Option<&Callback<f64, String>>,
245 trailing_label: &str,
246 ) -> Self {
247 let (width, height, font_size) = (640.0_f64, 320.0_f64, 24.0_f64);
249 let values: Vec<Option<f64>> = values.iter().copied().map(Some).collect();
250 let domain = axis_domain(&values, None, true);
251 let ticks = chart_ticks(domain);
252 let tick_labels = format_ticks(&ticks, format_value);
253 let left = (width - 64.0).min(axis_padding(&tick_labels, 44.0, None) * font_size / 12.0);
254 let trailing_reach =
255 (width / 5.0).min(estimate_chart_label_width(trailing_label, font_size) / 2.0 + 2.0);
256
257 Self {
258 width,
259 height,
260 axis_font_size: font_size,
261 domain,
262 ticks,
263 tick_labels,
264 left,
265 top: INTERVAL_PADDING_TOP,
266 right: width - 24f64.max(trailing_reach),
267 bottom: height - 48.0,
268 }
269 }
270
271 pub(crate) fn y(&self, value: f64) -> f64 {
272 scale_value(value, self.domain, self.bottom, self.top)
273 }
274}
275
276#[derive(Clone, Debug, PartialEq)]
278pub(crate) struct IntervalMark {
279 pub(crate) end: f64,
280 pub(crate) height: f64,
281 pub(crate) key: String,
282 pub(crate) label: String,
283 pub(crate) start: f64,
284 pub(crate) tone: ChartTone,
285 pub(crate) value: f64,
286 pub(crate) width: f64,
287 pub(crate) x: f64,
288 pub(crate) y: f64,
289}
290
291#[derive(Clone, Debug, PartialEq)]
293pub(crate) struct WaterfallConnector {
294 pub(crate) x1: f64,
295 pub(crate) x2: f64,
296 pub(crate) y: f64,
297}
298
299#[derive(Clone, Debug, PartialEq)]
301pub(crate) struct IntervalModel {
302 pub(crate) frame: IntervalFrame,
303 pub(crate) valid: bool,
304 pub(crate) marks: Vec<IntervalMark>,
305 pub(crate) category_ticks: Vec<CategoryTick>,
306 pub(crate) connectors: Vec<WaterfallConnector>,
307 pub(crate) density_counts: Option<Vec<f64>>,
309 pub(crate) format_boundary: Option<TickFormatter>,
311}
312
313fn waterfall_tone(step: &WaterfallChartDatum) -> ChartTone {
314 match (step.tone, step.kind) {
315 (Some(tone), _) => tone,
316 (None, WaterfallChartKind::Total) => ChartTone::Series1,
317 (None, WaterfallChartKind::Delta) if step.value < 0.0 => ChartTone::Series5,
318 (None, WaterfallChartKind::Delta) => ChartTone::Series2,
319 }
320}
321
322pub(crate) fn waterfall_geometry(
324 data: &[WaterfallChartDatum],
325 format_value: Option<&Callback<f64, String>>,
326) -> IntervalModel {
327 let mut balance = 0.0;
328 let steps: Vec<(f64, f64)> = data
329 .iter()
330 .map(|datum| {
331 let (start, end) = match datum.kind {
332 WaterfallChartKind::Total => (0.0, datum.value),
333 WaterfallChartKind::Delta => (balance, balance + datum.value),
334 };
335 balance = end;
336 (start, end)
337 })
338 .collect();
339 let mut ids = HashSet::new();
340 let valid = data.iter().zip(&steps).all(|(datum, (_, end))| {
341 datum.value.is_finite() && end.is_finite() && ids.insert(datum.id.as_str())
342 });
343 let values: Vec<f64> = if valid {
344 steps
345 .iter()
346 .flat_map(|(start, end)| [*start, *end])
347 .collect()
348 } else {
349 Vec::new()
350 };
351 let frame = IntervalFrame::new(&values, format_value, "");
352 #[allow(clippy::cast_precision_loss)]
353 let band = (frame.right - frame.left) / steps.len().max(1) as f64;
354 let marks: Vec<IntervalMark> = if valid {
355 data.iter()
356 .zip(&steps)
357 .enumerate()
358 .map(|(index, (datum, (start, end)))| {
359 #[allow(clippy::cast_precision_loss)]
360 let x = frame.left + band * (index as f64 + 0.15);
361
362 IntervalMark {
363 end: *end,
364 height: (frame.y(*end) - frame.y(*start)).abs(),
365 key: datum.id.clone(),
366 label: datum.label.clone(),
367 start: *start,
368 tone: waterfall_tone(datum),
369 value: datum.value,
370 width: band * 0.7,
371 x,
372 y: frame.y(*start).min(frame.y(*end)),
373 }
374 })
375 .collect()
376 } else {
377 Vec::new()
378 };
379 let labels: Vec<&str> = marks.iter().map(|mark| mark.label.as_str()).collect();
380 let positions: Vec<f64> = marks.iter().map(|mark| mark.x + mark.width / 2.0).collect();
381 let ticks = category_ticks(
382 &labels,
383 CategoryTickOptions::new(frame.left, frame.right)
384 .bounds(0.0, frame.width)
385 .maximum_font_size(frame.axis_font_size)
386 .positions(&positions),
387 );
388 let connectors = marks
389 .windows(2)
390 .map(|pair| WaterfallConnector {
391 x1: pair[0].x + pair[0].width,
392 x2: pair[1].x,
393 y: frame.y(pair[0].end),
394 })
395 .collect();
396
397 IntervalModel {
398 frame,
399 valid,
400 marks,
401 category_ticks: ticks,
402 connectors,
403 density_counts: None,
404 format_boundary: None,
405 }
406}
407
408fn valid_bins(bins: &[HistogramBin], frequency: HistogramFrequency) -> bool {
409 let first_width = bins.first().map_or(0.0, |bin| bin.end - bin.start);
410
411 bins.iter().enumerate().all(|(index, bin)| {
412 let width = bin.end - bin.start;
413
414 if ![bin.start, bin.end, bin.count, width]
415 .iter()
416 .all(|value| value.is_finite())
417 || width <= 0.0
418 || bin.count < 0.0
419 {
420 return false;
421 }
422
423 if index > 0 && bin.start < bins[index - 1].end {
424 return false;
425 }
426
427 frequency == HistogramFrequency::Density
428 || (width - first_width).abs() <= first_width.abs() * 1e-9
429 })
430}
431
432pub(crate) fn histogram_geometry(
434 input: &[HistogramBin],
435 frequency: HistogramFrequency,
436 tone: ChartTone,
437 format_boundary: Option<&Callback<f64, String>>,
438 format_value: Option<&Callback<f64, String>>,
439) -> IntervalModel {
440 let finite_input = input
441 .iter()
442 .all(|bin| bin.start.is_finite() && bin.end.is_finite() && bin.count.is_finite());
443 let mut bins: Vec<HistogramBin> = if finite_input {
444 input.to_vec()
445 } else {
446 Vec::new()
447 };
448 bins.sort_by(|left, right| left.start.total_cmp(&right.start));
450 let value_for = |bin: &HistogramBin| match frequency {
451 HistogramFrequency::Density => bin.count / (bin.end - bin.start),
452 HistogramFrequency::Count => bin.count,
453 };
454 let finite = finite_input
455 && valid_bins(&bins, frequency)
456 && bins.iter().all(|bin| value_for(bin).is_finite());
457 let values: Vec<f64> = if finite {
458 bins.iter().map(value_for).collect()
459 } else {
460 Vec::new()
461 };
462 let mut boundaries: Vec<f64> = if finite {
465 bins.iter()
466 .flat_map(|bin| [bin.start, bin.end])
467 .map(|value| if value == 0.0 { 0.0 } else { value })
468 .collect()
469 } else {
470 Vec::new()
471 };
472
473 boundaries.sort_by(f64::total_cmp);
474 boundaries.dedup();
475
476 let boundary = TickFormatter::new(&boundaries, format_boundary);
477 let trailing_label = boundaries
478 .last()
479 .map_or_else(String::new, |value| boundary.format(*value));
480 let frame = IntervalFrame::new(&values, format_value, &trailing_label);
481 let x_domain = ChartDomain::new(
482 bins.first().map_or(0.0, |bin| bin.start),
483 bins.last().map_or(1.0, |bin| bin.end),
484 );
485 let x = |value: f64| scale_value(value, x_domain, frame.left, frame.right);
486 let marks: Vec<IntervalMark> = if finite {
487 bins.iter()
488 .map(|bin| {
489 let value = value_for(bin);
490
491 IntervalMark {
492 end: bin.end,
493 height: frame.y(0.0) - frame.y(value),
494 key: format!("number:{}", js_number(bin.start)),
495 label: bin.label.clone().unwrap_or_else(|| {
496 format!(
497 "{}–{}",
498 boundary.format(bin.start),
499 boundary.format(bin.end)
500 )
501 }),
502 start: bin.start,
503 tone,
504 value,
505 width: (x(bin.end) - x(bin.start) - 1.0).max(0.0),
506 x: x(bin.start),
507 y: frame.y(value),
508 }
509 })
510 .collect()
511 } else {
512 Vec::new()
513 };
514 let labels: Vec<String> = boundaries
515 .iter()
516 .map(|value| boundary.format(*value))
517 .collect();
518 let positions: Vec<f64> = boundaries.iter().map(|value| x(*value)).collect();
519 let ticks = category_ticks(
520 &labels,
521 CategoryTickOptions::new(frame.left, frame.right)
522 .bounds(0.0, frame.width)
523 .maximum_font_size(frame.axis_font_size)
524 .positions(&positions),
525 );
526
527 IntervalModel {
528 density_counts: (frequency == HistogramFrequency::Density).then(|| {
529 if finite {
530 bins.iter().map(|bin| bin.count).collect()
531 } else {
532 Vec::new()
533 }
534 }),
535 frame,
536 valid: finite,
537 marks,
538 category_ticks: ticks,
539 connectors: Vec::new(),
540 format_boundary: Some(boundary),
541 }
542}
543
544struct IntervalOptions<'a> {
546 model: IntervalModel,
547 value_label: String,
548 labels: ChartLabels,
549 format_value: Option<Callback<f64, String>>,
550 show_table: bool,
551 summary: Option<String>,
552 heading: Option<&'a String>,
553 attributes: &'a [Attribute],
554}
555
556#[derive(Clone, PartialEq)]
558struct MarkView {
559 key: String,
560 tone: &'static str,
561 x: String,
562 y: String,
563 width: String,
564 height: String,
565 title: String,
566 label: String,
567 start: String,
568 end: String,
569 value: String,
570 count: Option<String>,
571}
572
573fn interval_plot(options: IntervalOptions<'_>) -> (Option<String>, Element) {
575 let IntervalOptions {
576 model,
577 value_label,
578 labels,
579 format_value,
580 show_table,
581 summary,
582 heading,
583 attributes,
584 } = options;
585 let format = |value: f64| format_with(format_value.as_ref(), value);
586 let boundary = |value: f64| {
588 model
589 .format_boundary
590 .map_or_else(|| format(value), |formatter| formatter.format(value))
591 };
592 let series = [ChartSeries::new(
593 "values",
594 value_label.clone(),
595 model.marks.iter().map(|mark| {
596 ChartDatum::new(mark.key.clone(), mark.value).with_x_label(mark.label.clone())
597 }),
598 )];
599 let factual = labels.summary(summarize(&series, format_value.as_ref()));
600 let summary = summary.or_else(|| {
601 Some(if model.valid {
602 factual
603 } else {
604 labels.invalid_data.clone()
605 })
606 });
607
608 if model.marks.is_empty() {
609 let message = if model.valid {
610 &labels.empty
611 } else {
612 &labels.invalid_data
613 };
614
615 return (summary, empty_status(message));
616 }
617
618 let counts = model.density_counts.clone();
619 let marks: Vec<MarkView> = model
620 .marks
621 .iter()
622 .enumerate()
623 .map(|(index, mark)| MarkView {
624 key: mark.key.clone(),
625 tone: mark.tone.class_name(),
626 x: js_number(mark.x),
627 y: js_number(mark.y),
628 width: js_number(mark.width),
629 height: js_number(mark.height),
630 title: format!("{}: {}", mark.label, format(mark.value)),
631 label: mark.label.clone(),
632 start: boundary(mark.start),
633 end: boundary(mark.end),
634 value: format(mark.value),
635 count: counts.as_ref().map(|counts| {
636 counts
637 .get(index)
638 .map_or_else(String::new, |count| js_number(*count))
639 }),
640 })
641 .collect();
642 let plot = plot_label(attributes, heading, &labels.chart_data);
643 let svg = interval_svg(&model, &marks);
644 let table = show_table.then(|| interval_table(&labels, &value_label, counts.is_some(), &marks));
645 let body = rsx! {
646 p { class: "ui-chart__axis-title", "{value_label}" }
647 div { class: "ui-chart__plot", role: "region", tabindex: "0", aria_label: "{plot}", {svg} }
648 if let Some(table) = table {
649 {table}
650 }
651 };
652
653 (summary, body)
654}
655
656fn interval_svg(model: &IntervalModel, marks: &[MarkView]) -> Element {
658 let frame = &model.frame;
659 let view_box = format!("0 0 {} {}", js_number(frame.width), js_number(frame.height));
660 let viewbox_width = js_number(frame.width);
661 let left = js_number(frame.left);
662 let right = js_number(frame.right);
663 let text_x = js_number(frame.left - 8.0);
664 let grid: Vec<(String, String, String)> = frame
665 .ticks
666 .iter()
667 .zip(&frame.tick_labels)
668 .map(|(tick, label)| (js_number(*tick), js_number(frame.y(*tick)), label.clone()))
669 .collect();
670 let axis_y = js_number(frame.height - 16.0);
671 let axis: Vec<(usize, &'static str, String, String)> = model
672 .category_ticks
673 .iter()
674 .map(|tick| {
675 (
676 tick.index,
677 CategoryTick::ANCHOR,
678 js_number(tick.position),
679 tick.label.clone(),
680 )
681 })
682 .collect();
683 let connectors: Vec<(String, String, String)> = model
684 .connectors
685 .iter()
686 .map(|connector| {
687 (
688 js_number(connector.x1),
689 js_number(connector.x2),
690 js_number(connector.y),
691 )
692 })
693 .collect();
694
695 rsx! {
696 svg { "aria-hidden": "true", "style": "--ui-chart-viewbox-width: {viewbox_width}", "viewBox": "{view_box}",
697 g { class: "ui-chart__grid",
698 for (key, y, text) in grid {
699 line { key: "{key}", "x1": "{left}", "x2": "{right}", "y1": "{y}", "y2": "{y}" }
700 text { "x": "{text_x}", "y": "{y}", "{text}" }
701 }
702 }
703 g { class: "ui-chart__axis-labels",
704 for (index, anchor, x, label) in axis {
705 text { key: "{index}", "text-anchor": anchor, "x": "{x}", "y": "{axis_y}", "{label}" }
706 }
707 }
708 for (x1, x2, y) in connectors {
709 line {
710 key: "{x1}",
711 class: "ui-waterfall-chart__connector",
712 "x1": "{x1}",
713 "x2": "{x2}",
714 "y1": "{y}",
715 "y2": "{y}",
716 }
717 }
718 g { class: "ui-bar-chart__marks",
719 for mark in marks.iter() {
720 rect {
721 key: "{mark.key}",
722 class: mark.tone,
723 "x": "{mark.x}",
724 "y": "{mark.y}",
725 "width": "{mark.width}",
726 "height": "{mark.height}",
727 title { "{mark.title}" }
728 }
729 }
730 }
731 }
732 }
733}
734
735fn interval_table(
737 labels: &ChartLabels,
738 value_label: &str,
739 density: bool,
740 marks: &[MarkView],
741) -> Element {
742 rsx! {
743 details { class: "ui-chart__data",
744 summary { "{labels.view_data}" }
745 div { aria_label: "{labels.chart_data}", role: "group", tabindex: "0",
746 table {
747 thead {
748 tr {
749 th { scope: "col", "{labels.category}" }
750 th { scope: "col", "{labels.start}" }
751 th { scope: "col", "{labels.end}" }
752 th { scope: "col", "{value_label}" }
753 if density {
754 th { scope: "col", "{labels.count}" }
755 }
756 }
757 }
758 tbody {
759 for mark in marks.iter() {
760 tr { key: "{mark.key}",
761 th { scope: "row", "{mark.label}" }
762 td { "{mark.start}" }
763 td { "{mark.end}" }
764 td { "{mark.value}" }
765 if let Some(count) = &mark.count {
766 td { "{count}" }
767 }
768 }
769 }
770 }
771 }
772 }
773 }
774 }
775}
776
777#[component]
780pub fn WaterfallChart(props: WaterfallChartProps) -> Element {
781 let labels = props.labels.clone().unwrap_or_default();
782 let model = waterfall_geometry(&props.data, props.format_value.as_ref());
783 let (summary, body) = interval_plot(IntervalOptions {
784 model,
785 value_label: props
786 .value_label
787 .clone()
788 .unwrap_or_else(|| labels.value.clone()),
789 format_value: props.format_value,
790 show_table: props.show_table,
791 summary: props.summary.clone(),
792 heading: props.heading.as_ref(),
793 attributes: &props.attributes,
794 labels,
795 });
796 let class = compose([Some("ui-waterfall-chart"), props.class.as_deref()]);
797
798 render_frame(
799 super::super::frame::chart_frame!(props, class, summary),
800 body,
801 )
802}
803
804#[component]
807pub fn Histogram(props: HistogramProps) -> Element {
808 let labels = props.labels.clone().unwrap_or_default();
809 let model = histogram_geometry(
810 &props.bins,
811 props.frequency,
812 props.tone,
813 props.format_boundary.as_ref(),
814 props.format_value.as_ref(),
815 );
816 let default_label = match props.frequency {
817 HistogramFrequency::Count => labels.count.clone(),
818 HistogramFrequency::Density => labels.density.clone(),
819 };
820 let (summary, body) = interval_plot(IntervalOptions {
821 model,
822 value_label: props.value_label.clone().unwrap_or(default_label),
823 format_value: props.format_value,
824 show_table: props.show_table,
825 summary: props.summary.clone(),
826 heading: props.heading.as_ref(),
827 attributes: &props.attributes,
828 labels,
829 });
830 let class = compose([Some("ui-histogram"), props.class.as_deref()]);
831
832 render_frame(
833 super::super::frame::chart_frame!(props, class, summary),
834 body,
835 )
836}
837
838#[cfg(test)]
839mod tests {
840 use super::{
841 HistogramBin, HistogramFrequency, WaterfallChartDatum, histogram_geometry,
842 waterfall_geometry,
843 };
844 use crate::charts::model::{ChartDomain, ChartTone};
845
846 fn steps() -> Vec<WaterfallChartDatum> {
847 vec![
848 WaterfallChartDatum::total("open", "Opening", 120.0),
849 WaterfallChartDatum::delta("sales", "Sales", 45.0),
850 WaterfallChartDatum::delta("refunds", "Refunds", -18.0),
851 WaterfallChartDatum::total("close", "Closing", 147.0),
852 ]
853 }
854
855 #[test]
856 fn waterfall_steps_carry_the_balance() {
857 let model = waterfall_geometry(&steps(), None);
858 assert!(model.valid);
859 let spans: Vec<(f64, f64)> = model
860 .marks
861 .iter()
862 .map(|mark| (mark.start, mark.end))
863 .collect();
864 assert_eq!(
865 spans,
866 vec![(0.0, 120.0), (120.0, 165.0), (165.0, 147.0), (0.0, 147.0)]
867 );
868 let tones: Vec<ChartTone> = model.marks.iter().map(|mark| mark.tone).collect();
869 assert_eq!(
870 tones,
871 vec![
872 ChartTone::Series1,
873 ChartTone::Series2,
874 ChartTone::Series5,
875 ChartTone::Series1
876 ]
877 );
878 assert_eq!(model.connectors.len(), 3);
879 assert_eq!(model.frame.domain, ChartDomain::new(0.0, 200.0));
881 assert_eq!(model.frame.ticks, vec![0.0, 50.0, 100.0, 150.0, 200.0]);
882 assert_eq!(model.frame.tick_labels, ["0", "50", "100", "150", "200"]);
883 assert!((model.frame.left - 88.0).abs() < f64::EPSILON);
884 assert!((model.frame.top - 16.0).abs() < f64::EPSILON);
885 assert!((model.frame.right - 616.0).abs() < f64::EPSILON);
886 assert_eq!(
887 model
888 .category_ticks
889 .iter()
890 .map(|tick| tick.position)
891 .collect::<Vec<_>>(),
892 [154.0, 286.0, 418.0, 550.0]
893 );
894 assert!(model.format_boundary.is_none());
895 }
896
897 #[test]
898 fn negative_waterfalls_reach_below_zero() {
899 let model = waterfall_geometry(&[WaterfallChartDatum::delta("a", "Loss", -30.0)], None);
900 assert!(model.valid);
901 assert_eq!(model.frame.domain, ChartDomain::new(-30.0, 0.0));
902 assert_eq!(model.frame.ticks, vec![-30.0, -20.0, -10.0, 0.0]);
903 }
904
905 #[test]
906 fn invalid_waterfalls_fail_closed() {
907 let duplicate = [
908 WaterfallChartDatum::delta("a", "A", 1.0),
909 WaterfallChartDatum::delta("a", "B", 2.0),
910 ];
911 let infinite = [WaterfallChartDatum::delta("a", "A", f64::INFINITY)];
912 let overflow = [
913 WaterfallChartDatum::delta("a", "A", f64::MAX),
914 WaterfallChartDatum::delta("b", "B", f64::MAX),
915 ];
916 for data in [&duplicate[..], &infinite[..], &overflow[..]] {
917 let model = waterfall_geometry(data, None);
918 assert!(!model.valid && model.marks.is_empty());
919 }
920 let empty = waterfall_geometry(&[], None);
921 assert!(empty.valid && empty.marks.is_empty());
922 }
923
924 #[test]
925 fn histogram_bins_are_sorted_and_scaled() {
926 let model = histogram_geometry(
927 &[
928 HistogramBin::new(10.0, 20.0, 4.0),
929 HistogramBin::new(0.0, 10.0, 2.0),
930 ],
931 HistogramFrequency::Count,
932 ChartTone::Series1,
933 None,
934 None,
935 );
936 assert!(model.valid);
937 assert_eq!(model.marks[0].label, "0–10");
938 assert_eq!(model.category_ticks.len(), 3);
939 assert!(model.density_counts.is_none());
940 }
941
942 #[test]
943 fn histogram_boundaries_are_unique_sorted_and_normalize_negative_zero() {
944 let model = histogram_geometry(
945 &[
946 HistogramBin::new(20.0, 30.0, 1.0),
947 HistogramBin::new(-0.0, 10.0, 2.0),
948 HistogramBin::new(10.0, 20.0, 3.0),
949 ],
950 HistogramFrequency::Count,
951 ChartTone::Series1,
952 None,
953 None,
954 );
955 let labels: Vec<&str> = model
956 .category_ticks
957 .iter()
958 .map(|tick| tick.label.as_str())
959 .collect();
960
961 assert_eq!(labels, ["0", "10", "20", "30"]);
964 assert_eq!(
965 model
966 .marks
967 .iter()
968 .map(|mark| mark.label.as_str())
969 .collect::<Vec<_>>(),
970 ["-0–10", "10–20", "20–30"]
971 );
972 }
973
974 #[test]
975 fn histogram_boundaries_share_the_value_tick_format() {
976 let bins = [
977 HistogramBin::new(0.0, 5_000.0, 3.0),
978 HistogramBin::new(5_000.0, 10_000.0, 7.0),
979 HistogramBin::new(10_000.0, 15_000.0, 2.0),
980 ];
981 let model = histogram_geometry(
982 &bins,
983 HistogramFrequency::Count,
984 ChartTone::Series1,
985 None,
986 None,
987 );
988 let labels: Vec<&str> = model.marks.iter().map(|mark| mark.label.as_str()).collect();
989 let ticks: Vec<(&str, f64)> = model
990 .category_ticks
991 .iter()
992 .map(|tick| (tick.label.as_str(), tick.position))
993 .collect();
994
995 assert_eq!(labels, ["0–5K", "5K–10K", "10K–15K"]);
996 assert!((model.frame.right - 615.090_909_090_909_1).abs() < 1e-9);
998 assert_eq!(ticks.len(), 4);
999 assert!((ticks[1].1 - 263.696_969_696_969_7).abs() < 1e-9);
1000 assert_eq!(ticks[3].0, "15K");
1001 assert_eq!(model.frame.domain, ChartDomain::new(0.0, 8.0));
1002 assert_eq!(
1003 model.format_boundary.map(|format| format.format(2_500.0)),
1004 Some("2.5K".to_string())
1005 );
1006 }
1007
1008 #[test]
1009 fn density_allows_unequal_widths() {
1010 let bins = [
1011 HistogramBin::new(0.0, 5.0, 10.0),
1012 HistogramBin::new(5.0, 20.0, 6.0),
1013 ];
1014 let count = histogram_geometry(
1015 &bins,
1016 HistogramFrequency::Count,
1017 ChartTone::Series1,
1018 None,
1019 None,
1020 );
1021 assert!(!count.valid && count.marks.is_empty());
1022 let density = histogram_geometry(
1023 &bins,
1024 HistogramFrequency::Density,
1025 ChartTone::Series1,
1026 None,
1027 None,
1028 );
1029 assert!(density.valid);
1030 assert!((density.marks[0].value - 2.0).abs() < f64::EPSILON);
1031 assert_eq!(density.density_counts, Some(vec![10.0, 6.0]));
1032 }
1033
1034 #[test]
1035 fn invalid_bins_fail_closed() {
1036 let tone = ChartTone::Series1;
1037 let count = HistogramFrequency::Count;
1038 for bins in [
1039 vec![HistogramBin::new(0.0, 0.0, 1.0)],
1040 vec![HistogramBin::new(0.0, 1.0, -1.0)],
1041 vec![HistogramBin::new(0.0, f64::NAN, 1.0)],
1042 vec![
1043 HistogramBin::new(0.0, 2.0, 1.0),
1044 HistogramBin::new(1.0, 3.0, 1.0),
1045 ],
1046 vec![HistogramBin::new(-f64::MAX, f64::MAX, 1.0)],
1047 ] {
1048 assert!(!histogram_geometry(&bins, count, tone, None, None).valid);
1049 }
1050 let empty = histogram_geometry(&[], count, tone, None, None);
1051 assert!(empty.valid && empty.marks.is_empty());
1052 assert_eq!(empty.category_ticks.len(), 0);
1053 }
1054}