1use dioxus::prelude::*;
5
6use super::format::{js_number, json_number, json_string};
7
8#[derive(Clone, Debug, PartialEq)]
13#[non_exhaustive]
14pub enum ChartX {
15 Number(f64),
17 Text(String),
19}
20
21impl ChartX {
22 pub fn display(&self) -> String {
24 match self {
25 Self::Number(value) => js_number(*value),
26 Self::Text(text) => text.clone(),
27 }
28 }
29
30 pub(crate) fn key(&self) -> String {
32 match self {
33 Self::Number(value) => format!("number:{}", js_number(*value)),
34 Self::Text(text) => format!("string:{text}"),
35 }
36 }
37
38 pub(crate) fn json(&self) -> String {
40 match self {
41 Self::Number(value) => json_number(*value),
42 Self::Text(text) => json_string(text),
43 }
44 }
45
46 pub(crate) fn typed_json(&self) -> String {
48 match self {
49 Self::Number(value) => format!("[\"number\",{}]", json_number(*value)),
50 Self::Text(text) => format!("[\"string\",{}]", json_string(text)),
51 }
52 }
53
54 pub(crate) fn is_axis_value(&self) -> bool {
56 match self {
57 Self::Number(value) => value.is_finite(),
58 Self::Text(_) => true,
59 }
60 }
61}
62
63impl From<f64> for ChartX {
64 fn from(value: f64) -> Self {
65 Self::Number(value)
66 }
67}
68
69impl From<f32> for ChartX {
70 fn from(value: f32) -> Self {
71 Self::Number(f64::from(value))
72 }
73}
74
75impl From<i32> for ChartX {
76 fn from(value: i32) -> Self {
77 Self::Number(f64::from(value))
78 }
79}
80
81impl From<u32> for ChartX {
82 fn from(value: u32) -> Self {
83 Self::Number(f64::from(value))
84 }
85}
86
87impl From<&str> for ChartX {
88 fn from(value: &str) -> Self {
89 Self::Text(value.to_string())
90 }
91}
92
93impl From<String> for ChartX {
94 fn from(value: String) -> Self {
95 Self::Text(value)
96 }
97}
98
99impl From<&String> for ChartX {
100 fn from(value: &String) -> Self {
101 Self::Text(value.clone())
102 }
103}
104
105#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub enum ChartTone {
109 #[default]
111 Series1,
112 Series2,
114 Series3,
116 Series4,
118 Series5,
120 Series6,
122 Series7,
124 Series8,
126 Brand,
128 Accent,
130 Success,
132 Warning,
134 Danger,
136 Neutral,
138}
139
140const SERIES_TONES: [ChartTone; 8] = [
141 ChartTone::Series1,
142 ChartTone::Series2,
143 ChartTone::Series3,
144 ChartTone::Series4,
145 ChartTone::Series5,
146 ChartTone::Series6,
147 ChartTone::Series7,
148 ChartTone::Series8,
149];
150
151impl ChartTone {
152 pub fn as_str(self) -> &'static str {
154 match self {
155 Self::Series1 => "series-1",
156 Self::Series2 => "series-2",
157 Self::Series3 => "series-3",
158 Self::Series4 => "series-4",
159 Self::Series5 => "series-5",
160 Self::Series6 => "series-6",
161 Self::Series7 => "series-7",
162 Self::Series8 => "series-8",
163 Self::Brand => "brand",
164 Self::Accent => "accent",
165 Self::Success => "success",
166 Self::Warning => "warning",
167 Self::Danger => "danger",
168 Self::Neutral => "neutral",
169 }
170 }
171
172 pub fn class_name(self) -> &'static str {
174 match self {
175 Self::Series1 => "ui-chart-tone--series-1",
176 Self::Series2 => "ui-chart-tone--series-2",
177 Self::Series3 => "ui-chart-tone--series-3",
178 Self::Series4 => "ui-chart-tone--series-4",
179 Self::Series5 => "ui-chart-tone--series-5",
180 Self::Series6 => "ui-chart-tone--series-6",
181 Self::Series7 => "ui-chart-tone--series-7",
182 Self::Series8 => "ui-chart-tone--series-8",
183 Self::Brand => "ui-chart-tone--brand",
184 Self::Accent => "ui-chart-tone--accent",
185 Self::Success => "ui-chart-tone--success",
186 Self::Warning => "ui-chart-tone--warning",
187 Self::Danger => "ui-chart-tone--danger",
188 Self::Neutral => "ui-chart-tone--neutral",
189 }
190 }
191
192 pub fn resolve(tone: Option<Self>, index: usize) -> Self {
194 tone.unwrap_or(SERIES_TONES[index % SERIES_TONES.len()])
195 }
196}
197
198#[derive(Clone, Debug, PartialEq)]
200pub struct ChartDatum {
201 pub x: ChartX,
203 pub y: Option<f64>,
205 pub id: Option<String>,
207 pub label: Option<String>,
209 pub x_label: Option<String>,
211 pub size: Option<f64>,
213 pub tone: Option<ChartTone>,
215 pub tone_label: Option<String>,
217}
218
219impl ChartDatum {
220 pub fn new(x: impl Into<ChartX>, y: impl Into<Option<f64>>) -> Self {
222 Self {
223 x: x.into(),
224 y: y.into(),
225 id: None,
226 label: None,
227 x_label: None,
228 size: None,
229 tone: None,
230 tone_label: None,
231 }
232 }
233
234 pub fn missing(x: impl Into<ChartX>) -> Self {
236 Self::new(x, None)
237 }
238
239 #[must_use]
241 pub fn with_id(mut self, id: impl Into<String>) -> Self {
242 self.id = Some(id.into());
243 self
244 }
245
246 #[must_use]
248 pub fn with_label(mut self, label: impl Into<String>) -> Self {
249 self.label = Some(label.into());
250 self
251 }
252
253 #[must_use]
255 pub fn with_x_label(mut self, label: impl Into<String>) -> Self {
256 self.x_label = Some(label.into());
257 self
258 }
259
260 #[must_use]
262 pub fn with_size(mut self, size: f64) -> Self {
263 self.size = Some(size);
264 self
265 }
266
267 #[must_use]
269 pub fn with_tone(mut self, tone: ChartTone) -> Self {
270 self.tone = Some(tone);
271 self
272 }
273
274 pub(crate) fn value(&self) -> Option<f64> {
276 self.y.filter(|value| value.is_finite())
277 }
278}
279
280#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
283#[non_exhaustive]
284pub enum ChartSeriesDash {
285 #[default]
287 Solid,
288 Dashed,
290 Dotted,
292}
293
294impl ChartSeriesDash {
295 pub fn as_str(self) -> &'static str {
297 match self {
298 Self::Solid => "solid",
299 Self::Dashed => "dashed",
300 Self::Dotted => "dotted",
301 }
302 }
303}
304
305#[derive(Clone, Debug, PartialEq)]
307pub struct ChartSeries {
308 pub id: String,
310 pub label: String,
312 pub data: Vec<ChartDatum>,
314 pub tone: Option<ChartTone>,
316 pub dash: Option<ChartSeriesDash>,
318}
319
320impl ChartSeries {
321 pub fn new(
323 id: impl Into<String>,
324 label: impl Into<String>,
325 data: impl IntoIterator<Item = ChartDatum>,
326 ) -> Self {
327 Self {
328 id: id.into(),
329 label: label.into(),
330 data: data.into_iter().collect(),
331 tone: None,
332 dash: None,
333 }
334 }
335
336 #[must_use]
338 pub fn with_dash(mut self, dash: ChartSeriesDash) -> Self {
339 self.dash = Some(dash);
340 self
341 }
342
343 #[must_use]
345 pub fn with_tone(mut self, tone: ChartTone) -> Self {
346 self.tone = Some(tone);
347 self
348 }
349}
350
351#[derive(Clone, Copy, Debug, PartialEq)]
353pub struct ChartDomain {
354 pub min: f64,
356 pub max: f64,
358}
359
360impl ChartDomain {
361 pub fn new(min: f64, max: f64) -> Self {
363 Self { min, max }
364 }
365}
366
367#[derive(Clone, Copy, Debug, Default, PartialEq)]
369pub struct ChartBounds {
370 pub min: Option<f64>,
372 pub max: Option<f64>,
374}
375
376impl ChartBounds {
377 pub fn new(min: f64, max: f64) -> Self {
379 Self {
380 min: Some(min),
381 max: Some(max),
382 }
383 }
384
385 pub fn min(min: f64) -> Self {
387 Self {
388 min: Some(min),
389 max: None,
390 }
391 }
392
393 pub fn max(max: f64) -> Self {
395 Self {
396 min: None,
397 max: Some(max),
398 }
399 }
400}
401
402impl From<ChartDomain> for ChartBounds {
403 fn from(domain: ChartDomain) -> Self {
404 Self::new(domain.min, domain.max)
405 }
406}
407
408#[derive(Clone, Debug, PartialEq)]
410pub struct ChartSummary {
411 pub available_point_count: usize,
413 pub maximum: Option<f64>,
415 pub minimum: Option<f64>,
417 pub missing_point_count: usize,
419 pub series_count: usize,
421 pub maximum_label: String,
423 pub minimum_label: String,
425}
426
427#[derive(Clone, PartialEq)]
430#[allow(missing_docs)]
431pub struct ChartLabels {
432 pub count: String,
433 pub density: String,
434 pub end: String,
435 pub invalid_data: String,
436 pub start: String,
437 pub category: String,
438 pub chart_data: String,
439 pub chart_legend: String,
440 pub column: String,
441 pub empty: String,
442 pub explore_data: String,
443 pub high: String,
444 pub low: String,
445 pub not_available: String,
446 pub row: String,
447 pub series: String,
448 pub size: String,
449 pub value: String,
450 pub view_data: String,
451 pub x: String,
452 pub format_datum_action: Option<Callback<String, String>>,
454 pub format_heatmap_summary: Option<Callback<usize, String>>,
456 pub format_range_summary: Option<Callback<usize, String>>,
458 pub format_summary: Option<Callback<ChartSummary, String>>,
460}
461
462impl Default for ChartLabels {
463 fn default() -> Self {
464 Self {
465 count: "Count".into(),
466 density: "Frequency density".into(),
467 end: "End".into(),
468 invalid_data: "Chart data is invalid. Check the supplied values.".into(),
469 start: "Start".into(),
470 category: "Category".into(),
471 chart_data: "Chart data".into(),
472 chart_legend: "Chart legend".into(),
473 column: "Column".into(),
474 empty: "No chart data available.".into(),
475 explore_data: "Explore chart data".into(),
476 high: "High".into(),
477 low: "Low".into(),
478 not_available: "Not available".into(),
479 row: "Row".into(),
480 series: "Series".into(),
481 size: "Size".into(),
482 value: "Value".into(),
483 view_data: "View chart data".into(),
484 x: "X".into(),
485 format_datum_action: None,
486 format_heatmap_summary: None,
487 format_range_summary: None,
488 format_summary: None,
489 }
490 }
491}
492
493impl ChartLabels {
494 pub fn datum_action(&self, context: &str) -> String {
496 match &self.format_datum_action {
497 Some(format) => format.call(context.to_string()),
498 None => format!("Open details: {context}"),
499 }
500 }
501
502 pub fn heatmap_summary(&self, count: usize) -> String {
504 match &self.format_heatmap_summary {
505 Some(format) => format.call(count),
506 None if count == 0 => "No chart data available.".to_string(),
507 None => format!(
508 "{count} available heatmap {}.",
509 if count == 1 { "cell" } else { "cells" }
510 ),
511 }
512 }
513
514 pub fn range_summary(&self, count: usize) -> String {
516 match &self.format_range_summary {
517 Some(format) => format.call(count),
518 None if count == 0 => "No chart data available.".to_string(),
519 None => format!(
520 "{count} available {}.",
521 if count == 1 { "range" } else { "ranges" }
522 ),
523 }
524 }
525
526 pub fn summary(&self, summary: ChartSummary) -> String {
528 if let Some(format) = &self.format_summary {
529 return format.call(summary);
530 }
531
532 if summary.available_point_count == 0 {
533 return "No chart data available.".to_string();
534 }
535
536 let points = if summary.available_point_count == 1 {
537 "point"
538 } else {
539 "points"
540 };
541 let missing = if summary.missing_point_count == 0 {
542 String::new()
543 } else {
544 format!(
545 " {} missing {}.",
546 summary.missing_point_count,
547 if summary.missing_point_count == 1 {
548 "value"
549 } else {
550 "values"
551 }
552 )
553 };
554
555 format!(
556 "{} series, {} {points}. Values range from {} to {}.{missing}",
557 summary.series_count,
558 summary.available_point_count,
559 summary.minimum_label,
560 summary.maximum_label
561 )
562 }
563}
564
565pub(crate) fn format_with(formatter: Option<&Callback<f64, String>>, value: f64) -> String {
567 match formatter {
568 Some(format) => format.call(value),
569 None => js_number(value),
570 }
571}
572
573pub(crate) fn format_category_with(
575 formatter: Option<&Callback<ChartX, String>>,
576 value: &ChartX,
577) -> String {
578 match formatter {
579 Some(format) => format.call(value.clone()),
580 None => value.display(),
581 }
582}
583
584pub(crate) fn summarize(
586 series: &[ChartSeries],
587 format_value: Option<&Callback<f64, String>>,
588) -> ChartSummary {
589 let mut available = 0;
590 let mut missing = 0;
591 let mut maximum = f64::NEG_INFINITY;
592 let mut minimum = f64::INFINITY;
593
594 for item in series {
595 for datum in &item.data {
596 match datum.value() {
597 Some(value) => {
598 available += 1;
599 maximum = maximum.max(value);
600 minimum = minimum.min(value);
601 }
602 None => missing += 1,
603 }
604 }
605 }
606
607 let maximum = maximum.is_finite().then_some(maximum);
608 let minimum = minimum.is_finite().then_some(minimum);
609
610 ChartSummary {
611 available_point_count: available,
612 maximum,
613 minimum,
614 missing_point_count: missing,
615 series_count: series.len(),
616 maximum_label: format_with(format_value, maximum.unwrap_or(0.0)),
617 minimum_label: format_with(format_value, minimum.unwrap_or(0.0)),
618 }
619}
620
621#[cfg(test)]
622mod tests {
623 use super::{ChartDatum, ChartLabels, ChartSeries, ChartTone, ChartX, summarize};
624
625 #[test]
626 fn x_identity_follows_javascript() {
627 assert_eq!(ChartX::from(0.0), ChartX::from(-0.0));
628 assert_ne!(ChartX::Number(f64::NAN), ChartX::Number(f64::NAN));
629 assert_ne!(ChartX::from(1), ChartX::from("1"));
630 assert_eq!(ChartX::from(1.5).key(), "number:1.5");
631 assert_eq!(ChartX::from("Jan").key(), "string:Jan");
632 assert_eq!(ChartX::from(f64::NAN).json(), "null");
633 assert_eq!(ChartX::from("a\"b").typed_json(), "[\"string\",\"a\\\"b\"]");
634 assert!(!ChartX::from(f64::INFINITY).is_axis_value());
635 }
636
637 #[test]
638 fn tones_cycle_through_eight_series_colors() {
639 assert_eq!(ChartTone::resolve(None, 0), ChartTone::Series1);
640 assert_eq!(ChartTone::resolve(None, 9), ChartTone::Series2);
641 assert_eq!(
642 ChartTone::resolve(Some(ChartTone::Danger), 3),
643 ChartTone::Danger
644 );
645 assert_eq!(ChartTone::Series4.class_name(), "ui-chart-tone--series-4");
646 }
647
648 #[test]
649 fn summaries_count_available_and_missing_points() {
650 let series = vec![ChartSeries::new(
651 "a",
652 "A",
653 [
654 ChartDatum::new("x", 3.0),
655 ChartDatum::missing("y"),
656 ChartDatum::new("z", f64::NAN),
657 ChartDatum::new("w", -2.0),
658 ],
659 )];
660 let summary = summarize(&series, None);
661
662 assert_eq!(summary.available_point_count, 2);
663 assert_eq!(summary.missing_point_count, 2);
664 assert_eq!(
665 ChartLabels::default().summary(summary),
666 "1 series, 2 points. Values range from -2 to 3. 2 missing values."
667 );
668 assert_eq!(
669 ChartLabels::default().summary(summarize(&[], None)),
670 "No chart data available."
671 );
672 }
673}