BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / card_chart.rs

card_chart.rs

card_chart.rs 16.9 KiB Download Raw
1use std::f32::consts::{FRAC_PI_2, TAU};
2
3use serde_json::Value;
4
5const CHART_TYPE_PREFIX: &str = "Chart.";
6const DEFAULT_GAUGE_MAX: f64 = 100.;
7
8#[derive(Debug, Clone, PartialEq)]
9pub struct CardChart {
10 pub title: Option<String>,
11 pub x_axis_title: Option<String>,
12 pub y_axis_title: Option<String>,
13 pub show_legend: bool,
14 pub show_values: bool,
15 pub kind: ChartKind,
16}
17
18#[derive(Debug, Clone, PartialEq)]
19pub enum ChartKind {
20 Donut(Vec<ChartPoint>),
21 Pie(Vec<ChartPoint>),
22 Gauge(ChartGauge),
23 Line(Vec<ChartSeries>),
24 VerticalBar(Vec<ChartPoint>),
25 GroupedBar {
26 series: Vec<ChartSeries>,
27 stacked: bool,
28 },
29 HorizontalBar {
30 bars: Vec<ChartPoint>,
31 mode: BarDisplayMode,
32 },
33 StackedHorizontalBar(Vec<ChartSeries>),
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum BarDisplayMode {
38 AbsoluteWithAxis,
39 AbsoluteNoAxis,
40 PartToWhole,
41}
42
43#[derive(Debug, Clone, PartialEq)]
44pub struct ChartPoint {
45 pub label: String,
46 pub value: f64,
47 pub color: ChartColor,
48}
49
50#[derive(Debug, Clone, PartialEq)]
51pub struct ChartSeries {
52 pub legend: String,
53 pub color: ChartColor,
54 pub points: Vec<ChartPoint>,
55}
56
57#[derive(Debug, Clone, PartialEq)]
58pub struct ChartGauge {
59 pub minimum: f64,
60 pub maximum: f64,
61 pub value: f64,
62 pub segments: Vec<GaugeSegment>,
63 pub sub_label: Option<String>,
64 pub format: GaugeValueFormat,
65 pub show_min_max: bool,
66}
67
68#[derive(Debug, Clone, PartialEq)]
69pub struct GaugeSegment {
70 pub legend: String,
71 pub size: f64,
72 pub color: ChartColor,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum GaugeValueFormat {
77 Percentage,
78 Fraction,
79}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub enum ChartColorSet {
83 Categorical,
84 Sequential,
85 Diverging,
86}
87
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum ChartColor {
90 Good,
91 Warning,
92 Attention,
93 Neutral,
94 CategoricalRed,
95 CategoricalPurple,
96 CategoricalLavender,
97 CategoricalBlue,
98 CategoricalLightBlue,
99 CategoricalTeal,
100 CategoricalGreen,
101 CategoricalLime,
102 CategoricalMarigold,
103 Sequential1,
104 Sequential2,
105 Sequential3,
106 Sequential4,
107 Sequential5,
108 Sequential6,
109 Sequential7,
110 Sequential8,
111 DivergingBlue,
112 DivergingLightBlue,
113 DivergingCyan,
114 DivergingTeal,
115 DivergingYellow,
116 DivergingPeach,
117 DivergingLightRed,
118 DivergingRed,
119 DivergingMaroon,
120 DivergingGray,
121}
122
123#[derive(Debug, Clone, Copy, PartialEq)]
124pub struct AxisScale {
125 pub maximum: f64,
126 pub step: f64,
127}
128
129const NAMED_COLORS: [(&str, ChartColor); 31] = [
130 ("good", ChartColor::Good),
131 ("warning", ChartColor::Warning),
132 ("attention", ChartColor::Attention),
133 ("neutral", ChartColor::Neutral),
134 ("categoricalred", ChartColor::CategoricalRed),
135 ("categoricalpurple", ChartColor::CategoricalPurple),
136 ("categoricallavender", ChartColor::CategoricalLavender),
137 ("categoricalblue", ChartColor::CategoricalBlue),
138 ("categoricallightblue", ChartColor::CategoricalLightBlue),
139 ("categoricalteal", ChartColor::CategoricalTeal),
140 ("categoricalgreen", ChartColor::CategoricalGreen),
141 ("categoricallime", ChartColor::CategoricalLime),
142 ("categoricalmarigold", ChartColor::CategoricalMarigold),
143 ("sequential1", ChartColor::Sequential1),
144 ("sequential2", ChartColor::Sequential2),
145 ("sequential3", ChartColor::Sequential3),
146 ("sequential4", ChartColor::Sequential4),
147 ("sequential5", ChartColor::Sequential5),
148 ("sequential6", ChartColor::Sequential6),
149 ("sequential7", ChartColor::Sequential7),
150 ("sequential8", ChartColor::Sequential8),
151 ("divergingblue", ChartColor::DivergingBlue),
152 ("diverginglightblue", ChartColor::DivergingLightBlue),
153 ("divergingcyan", ChartColor::DivergingCyan),
154 ("divergingteal", ChartColor::DivergingTeal),
155 ("divergingyellow", ChartColor::DivergingYellow),
156 ("divergingpeach", ChartColor::DivergingPeach),
157 ("diverginglightred", ChartColor::DivergingLightRed),
158 ("divergingred", ChartColor::DivergingRed),
159 ("divergingmaroon", ChartColor::DivergingMaroon),
160 ("diverginggray", ChartColor::DivergingGray),
161];
162
163const CATEGORICAL_ORDER: [ChartColor; 9] = [
164 ChartColor::CategoricalBlue,
165 ChartColor::CategoricalTeal,
166 ChartColor::CategoricalMarigold,
167 ChartColor::CategoricalRed,
168 ChartColor::CategoricalPurple,
169 ChartColor::CategoricalGreen,
170 ChartColor::CategoricalLavender,
171 ChartColor::CategoricalLime,
172 ChartColor::CategoricalLightBlue,
173];
174
175const SEQUENTIAL_ORDER: [ChartColor; 8] = [
176 ChartColor::Sequential3,
177 ChartColor::Sequential5,
178 ChartColor::Sequential7,
179 ChartColor::Sequential1,
180 ChartColor::Sequential4,
181 ChartColor::Sequential6,
182 ChartColor::Sequential2,
183 ChartColor::Sequential8,
184];
185
186const DIVERGING_ORDER: [ChartColor; 10] = [
187 ChartColor::DivergingBlue,
188 ChartColor::DivergingRed,
189 ChartColor::DivergingTeal,
190 ChartColor::DivergingPeach,
191 ChartColor::DivergingLightBlue,
192 ChartColor::DivergingMaroon,
193 ChartColor::DivergingYellow,
194 ChartColor::DivergingCyan,
195 ChartColor::DivergingLightRed,
196 ChartColor::DivergingGray,
197];
198
199impl ChartColor {
200 pub fn from_name(name: &str) -> Option<ChartColor> {
201 let lowered = name.trim().to_ascii_lowercase();
202 NAMED_COLORS
203 .iter()
204 .find(|(candidate, _)| *candidate == lowered)
205 .map(|(_, color)| *color)
206 }
207}
208
209impl ChartColorSet {
210 pub fn from_name(name: Option<&str>) -> ChartColorSet {
211 let lowered = name.unwrap_or_default().to_ascii_lowercase();
212 if lowered.starts_with("sequential") {
213 ChartColorSet::Sequential
214 } else if lowered.starts_with("diverging") {
215 ChartColorSet::Diverging
216 } else {
217 ChartColorSet::Categorical
218 }
219 }
220
221 pub fn color_at(self, index: usize) -> ChartColor {
222 match self {
223 ChartColorSet::Categorical => CATEGORICAL_ORDER[index % CATEGORICAL_ORDER.len()],
224 ChartColorSet::Sequential => SEQUENTIAL_ORDER[index % SEQUENTIAL_ORDER.len()],
225 ChartColorSet::Diverging => DIVERGING_ORDER[index % DIVERGING_ORDER.len()],
226 }
227 }
228}
229
230struct ColorPlan {
231 color_set: ChartColorSet,
232 uniform: Option<ChartColor>,
233}
234
235impl ColorPlan {
236 fn new(value: &Value) -> ColorPlan {
237 ColorPlan {
238 color_set: ChartColorSet::from_name(string_field(value, "colorSet")),
239 uniform: named_color(value),
240 }
241 }
242
243 fn resolve(&self, entry: &Value, index: usize) -> ChartColor {
244 named_color(entry)
245 .or(self.uniform)
246 .unwrap_or_else(|| self.color_set.color_at(index))
247 }
248}
249
250pub fn is_chart_type(element_type: &str) -> bool {
251 element_type.starts_with(CHART_TYPE_PREFIX)
252}
253
254pub fn parse_chart(value: &Value, element_type: &str) -> Option<CardChart> {
255 let plan = ColorPlan::new(value);
256 let kind = match element_type {
257 "Chart.Donut" => ChartKind::Donut(parse_slices(value, &plan)),
258 "Chart.Pie" => ChartKind::Pie(parse_slices(value, &plan)),
259 "Chart.Gauge" => ChartKind::Gauge(parse_gauge(value, &plan)),
260 "Chart.Line" => ChartKind::Line(parse_series(value, &plan)),
261 "Chart.VerticalBar" => ChartKind::VerticalBar(parse_xy_points(value, &plan)),
262 "Chart.VerticalBar.Grouped" => ChartKind::GroupedBar {
263 series: parse_series(value, &plan),
264 stacked: bool_field(value, "stacked", false),
265 },
266 "Chart.HorizontalBar" => ChartKind::HorizontalBar {
267 bars: parse_xy_points(value, &plan),
268 mode: parse_display_mode(string_field(value, "displayMode")),
269 },
270 "Chart.HorizontalBar.Stacked" => {
271 ChartKind::StackedHorizontalBar(parse_stacked_rows(value, &plan))
272 }
273 _ => return None,
274 };
275 Some(CardChart {
276 title: text_field(value, "title"),
277 x_axis_title: text_field(value, "xAxisTitle"),
278 y_axis_title: text_field(value, "yAxisTitle"),
279 show_legend: bool_field(value, "showLegend", true),
280 show_values: bool_field(value, "showBarValues", false),
281 kind,
282 })
283}
284
285impl CardChart {
286 pub fn legend_entries(&self) -> Vec<(String, ChartColor)> {
287 match &self.kind {
288 ChartKind::Donut(points) | ChartKind::Pie(points) => {
289 points.iter().map(point_legend).collect()
290 }
291 ChartKind::Gauge(gauge) => gauge
292 .segments
293 .iter()
294 .filter(|segment| !segment.legend.is_empty())
295 .map(|segment| (segment.legend.clone(), segment.color))
296 .collect(),
297 ChartKind::Line(series) | ChartKind::GroupedBar { series, .. } => series
298 .iter()
299 .map(|entry| (entry.legend.clone(), entry.color))
300 .collect(),
301 ChartKind::StackedHorizontalBar(rows) => {
302 let mut entries: Vec<(String, ChartColor)> = Vec::new();
303 for point in rows.iter().flat_map(|row| &row.points) {
304 if !entries.iter().any(|(legend, _)| *legend == point.label) {
305 entries.push(point_legend(point));
306 }
307 }
308 entries
309 }
310 ChartKind::VerticalBar(_) | ChartKind::HorizontalBar { .. } => Vec::new(),
311 }
312 }
313}
314
315fn point_legend(point: &ChartPoint) -> (String, ChartColor) {
316 (point.label.clone(), point.color)
317}
318
319fn parse_slices(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
320 array_field(value, "data")
321 .iter()
322 .enumerate()
323 .map(|(index, entry)| ChartPoint {
324 label: text_field(entry, "legend").unwrap_or_default(),
325 value: number_field(entry, "value").unwrap_or(0.),
326 color: plan.resolve(entry, index),
327 })
328 .collect()
329}
330
331fn parse_xy_points(value: &Value, plan: &ColorPlan) -> Vec<ChartPoint> {
332 array_field(value, "data")
333 .iter()
334 .enumerate()
335 .map(|(index, entry)| ChartPoint {
336 label: label_field(entry, "x"),
337 value: number_field(entry, "y").unwrap_or(0.),
338 color: plan.resolve(entry, index),
339 })
340 .collect()
341}
342
343fn parse_series(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
344 array_field(value, "data")
345 .iter()
346 .enumerate()
347 .map(|(index, entry)| {
348 let color = plan.resolve(entry, index);
349 ChartSeries {
350 legend: text_field(entry, "legend").unwrap_or_default(),
351 color,
352 points: array_field(entry, "values")
353 .iter()
354 .map(|point| ChartPoint {
355 label: label_field(point, "x"),
356 value: number_field(point, "y").unwrap_or(0.),
357 color,
358 })
359 .collect(),
360 }
361 })
362 .collect()
363}
364
365fn parse_stacked_rows(value: &Value, plan: &ColorPlan) -> Vec<ChartSeries> {
366 array_field(value, "data")
367 .iter()
368 .enumerate()
369 .map(|(index, row)| ChartSeries {
370 legend: text_field(row, "title").unwrap_or_default(),
371 color: plan.resolve(row, index),
372 points: parse_slices(row, plan),
373 })
374 .collect()
375}
376
377fn parse_gauge(value: &Value, plan: &ColorPlan) -> ChartGauge {
378 let segments: Vec<GaugeSegment> = array_field(value, "segments")
379 .iter()
380 .enumerate()
381 .map(|(index, entry)| GaugeSegment {
382 legend: text_field(entry, "legend").unwrap_or_default(),
383 size: number_field(entry, "size")
384 .or_else(|| number_field(entry, "value"))
385 .unwrap_or(0.)
386 .max(0.),
387 color: plan.resolve(entry, index),
388 })
389 .collect();
390 let segment_total: f64 = segments.iter().map(|segment| segment.size).sum();
391 let minimum = number_field(value, "min").unwrap_or(0.);
392 let default_maximum = if segment_total > 0. {
393 minimum + segment_total
394 } else {
395 DEFAULT_GAUGE_MAX
396 };
397 let format = match string_field(value, "valueFormat") {
398 Some(format) if format.eq_ignore_ascii_case("fraction") => GaugeValueFormat::Fraction,
399 _ => GaugeValueFormat::Percentage,
400 };
401 ChartGauge {
402 minimum,
403 maximum: number_field(value, "max").unwrap_or(default_maximum),
404 value: number_field(value, "value").unwrap_or(0.),
405 segments,
406 sub_label: text_field(value, "subLabel"),
407 format,
408 show_min_max: bool_field(value, "showMinMax", true),
409 }
410}
411
412fn parse_display_mode(mode: Option<&str>) -> BarDisplayMode {
413 match mode.map(str::to_ascii_lowercase).as_deref() {
414 Some("absolutenoaxis") => BarDisplayMode::AbsoluteNoAxis,
415 Some("parttowhole") => BarDisplayMode::PartToWhole,
416 _ => BarDisplayMode::AbsoluteWithAxis,
417 }
418}
419
420fn array_field<'value>(value: &'value Value, key: &str) -> &'value [Value] {
421 value
422 .get(key)
423 .and_then(Value::as_array)
424 .map_or(&[], Vec::as_slice)
425}
426
427fn string_field<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
428 value.get(key)?.as_str()
429}
430
431fn text_field(value: &Value, key: &str) -> Option<String> {
432 string_field(value, key)
433 .map(str::trim)
434 .filter(|text| !text.is_empty())
435 .map(str::to_owned)
436}
437
438fn bool_field(value: &Value, key: &str, default: bool) -> bool {
439 value.get(key).and_then(Value::as_bool).unwrap_or(default)
440}
441
442fn number_field(value: &Value, key: &str) -> Option<f64> {
443 value.get(key)?.as_f64().filter(|number| number.is_finite())
444}
445
446fn label_field(value: &Value, key: &str) -> String {
447 match value.get(key) {
448 Some(Value::String(text)) => text.clone(),
449 Some(Value::Number(number)) => number.as_f64().map(format_chart_value).unwrap_or_default(),
450 _ => String::new(),
451 }
452}
453
454fn named_color(value: &Value) -> Option<ChartColor> {
455 ChartColor::from_name(string_field(value, "color")?)
456}
457
458pub fn format_chart_value(value: f64) -> String {
459 if (value - value.round()).abs() < 1e-9 {
460 format!("{}", value.round() as i64)
461 } else {
462 let formatted = format!("{value:.2}");
463 formatted
464 .trim_end_matches('0')
465 .trim_end_matches('.')
466 .to_owned()
467 }
468}
469
470pub fn slice_angles(values: &[f64]) -> Vec<(f32, f32)> {
471 let total: f64 = values.iter().map(|value| value.max(0.)).sum();
472 let mut start = -FRAC_PI_2;
473 values
474 .iter()
475 .map(|value| {
476 let sweep = if total > 0. {
477 (value.max(0.) / total) as f32 * TAU
478 } else {
479 0.
480 };
481 let angles = (start, start + sweep);
482 start += sweep;
483 angles
484 })
485 .collect()
486}
487
488pub fn unit_fraction(value: f64, minimum: f64, maximum: f64) -> f32 {
489 let range = maximum - minimum;
490 if range <= 0. {
491 return 0.;
492 }
493 ((value - minimum) / range).clamp(0., 1.) as f32
494}
495
496pub fn nice_scale(maximum_value: f64, target_steps: usize) -> AxisScale {
497 if maximum_value <= 0. || target_steps == 0 {
498 return AxisScale {
499 maximum: 1.,
500 step: 1.,
501 };
502 }
503 let rough_step = maximum_value / target_steps as f64;
504 let magnitude = 10f64.powf(rough_step.log10().floor());
505 let normalized = rough_step / magnitude;
506 let factor = [1., 2., 2.5, 5., 10.]
507 .into_iter()
508 .find(|candidate| *candidate >= normalized - 1e-9)
509 .unwrap_or(10.);
510 let step = factor * magnitude;
511 AxisScale {
512 maximum: (maximum_value / step - 1e-9).ceil().max(1.) * step,
513 step,
514 }
515}
516
517impl AxisScale {
518 pub fn ticks(&self) -> Vec<f64> {
519 let count = (self.maximum / self.step).round() as usize;
520 (0..=count).map(|index| index as f64 * self.step).collect()
521 }
522}
523
524pub fn label_stride(count: usize, slot_width: f32, label_width: f32) -> usize {
525 if count == 0 || slot_width <= 0. {
526 return 1;
527 }
528 (label_width / slot_width).ceil().max(1.) as usize
529}
530
531pub fn series_categories(series: &[ChartSeries]) -> Vec<String> {
532 let mut categories: Vec<String> = Vec::new();
533 for point in series.iter().flat_map(|entry| &entry.points) {
534 if !categories.contains(&point.label) {
535 categories.push(point.label.clone());
536 }
537 }
538 categories
539}
540
541pub fn series_value(series: &ChartSeries, category: &str) -> f64 {
542 series
543 .points
544 .iter()
545 .find(|point| point.label == category)
546 .map_or(0., |point| point.value)
547}
548
549pub fn series_maximum(series: &[ChartSeries], stacked: bool) -> f64 {
550 if stacked {
551 return series_categories(series)
552 .iter()
553 .map(|category| {
554 series
555 .iter()
556 .map(|entry| series_value(entry, category).max(0.))
557 .sum::<f64>()
558 })
559 .fold(0., f64::max);
560 }
561 series
562 .iter()
563 .flat_map(|entry| &entry.points)
564 .map(|point| point.value)
565 .fold(0., f64::max)
566}