chartlet 0.23.0

Compile structured data into deterministic, accessible static charts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
use std::collections::BTreeSet;

use serde::{Deserialize, Serialize};

use super::{
    ChartSpec, ChartType, MAX_DATA_POINTS, MAX_REFERENCES, MAX_SERIES, Stack, ZoomBound,
    validate_number, validate_text,
};
use crate::error::{ChartError, ChartWarning};

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DataPoint {
    pub label: String,
    pub value: Option<f64>,
    /// The group a bar belongs to: one palette color and one legend entry per group. Either every
    /// point names a group or none does. Bar charts only.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
    /// The lower end of an error bar through the end of the bar, such as a confidence interval.
    /// Bar charts of one series only; `upper` goes with it, and the value lies between them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lower: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upper: Option<f64>,
}

/// One named series with one value per category; `None` marks a missing value.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SeriesSpec {
    pub name: String,
    pub values: Vec<Option<f64>>,
    /// The lower and upper end of an error bar through each value, such as a confidence
    /// interval: both or neither, one entry per category, `null` where the value is missing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub lower: Vec<Option<f64>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub upper: Vec<Option<f64>>,
}

impl ChartSpec {
    /// The groups of a single-series bar chart in the order they first appear; empty without
    /// groups.
    pub(crate) fn data_groups(&self) -> Vec<&str> {
        let mut groups: Vec<&str> = Vec::new();
        for group in self.data.iter().filter_map(|point| point.group.as_deref()) {
            if !groups.contains(&group) {
                groups.push(group);
            }
        }
        groups
    }

    /// A bar chart whose points name groups, as the chart it is drawn as: one series per group,
    /// each with a value only where the group has a bar, stacked so that every category keeps one
    /// full-width bar and every group gets its color and legend entry. The description and the
    /// table keep the chart as it was written.
    pub(crate) fn group_view(&self) -> Option<Self> {
        let groups = self.data_groups();
        // One group is one color: the bars are drawn as they are.
        if groups.len() < 2 {
            return None;
        }
        let mut view = self.clone();
        view.categories = self.data.iter().map(|point| point.label.clone()).collect();
        view.series = groups
            .iter()
            .map(|group| SeriesSpec {
                lower: Vec::new(),
                upper: Vec::new(),
                name: (*group).to_owned(),
                values: self
                    .data
                    .iter()
                    .map(|point| {
                        if point.group.as_deref() == Some(*group) {
                            point.value
                        } else {
                            None
                        }
                    })
                    .collect(),
            })
            .collect();
        view.data.clear();
        view.stack = Some(Stack::Normal);
        Some(view)
    }

    /// Whether the bars or points carry error bars.
    pub(crate) fn has_error_bars(&self) -> bool {
        self.data.iter().any(|point| point.lower.is_some())
            || self.series.iter().any(|series| !series.lower.is_empty())
    }

    /// The error bar of the value of series `series_index` in category `index`: the data point of
    /// a single series, or the series' own bounds.
    pub(crate) fn error_bounds(&self, index: usize, series_index: usize) -> Option<(f64, f64)> {
        if self.series.is_empty() {
            return self
                .data
                .get(index)
                .and_then(|point| point.lower.zip(point.upper));
        }
        let series = self.series.get(series_index)?;
        (*series.lower.get(index)?).zip(*series.upper.get(index)?)
    }

    /// Every error bar limit of the chart, for the value scale.
    pub(crate) fn error_limits(&self) -> impl Iterator<Item = f64> + '_ {
        let single = self
            .data
            .iter()
            .flat_map(|point| [point.lower, point.upper].into_iter().flatten());
        let several = self
            .series
            .iter()
            .flat_map(|series| series.lower.iter().chain(&series.upper).flatten().copied());
        single.chain(several)
    }

    /// Error bars of the series of a chart with several: `lower` and `upper` together, one entry
    /// for every category, around every value, on a bar or a line chart without a stack.
    fn validate_series_bounds(&self) -> Result<(), ChartError> {
        for (series_index, series) in self.series.iter().enumerate() {
            if series.lower.is_empty() && series.upper.is_empty() {
                continue;
            }
            let path = format!("/series/{series_index}");
            if !matches!(self.chart_type, ChartType::Bar | ChartType::Line) || self.stack.is_some()
            {
                return Err(ChartError::new(
                    "option_not_supported",
                    format!("{path}/lower"),
                    "error bars belong to a bar chart or a line chart without a stack",
                ));
            }
            for (name, bounds) in [("lower", &series.lower), ("upper", &series.upper)] {
                if bounds.len() != self.categories.len() {
                    return Err(ChartError::new(
                        if bounds.is_empty() {
                            "missing_bounds"
                        } else {
                            "series_length_mismatch"
                        },
                        format!("{path}/{name}"),
                        format!(
                            "give lower and upper together, {} entries each, one per category",
                            self.categories.len()
                        ),
                    ));
                }
            }
            for (index, value) in series.values.iter().enumerate() {
                let bounds = (series.lower[index], series.upper[index]);
                let (Some(value), (Some(lower), Some(upper))) = (value, bounds) else {
                    if value.is_some() {
                        return Err(ChartError::new(
                            "missing_bounds",
                            format!("{path}/lower/{index}"),
                            "give every value both lower and upper, or null where the value is null",
                        ));
                    }
                    continue;
                };
                validate_number(lower, &format!("{path}/lower/{index}"))?;
                validate_number(upper, &format!("{path}/upper/{index}"))?;
                if !(lower..=upper).contains(value) {
                    return Err(ChartError::new(
                        "invalid_bounds",
                        format!("{path}/lower/{index}"),
                        "the value must lie between lower and upper",
                    ));
                }
            }
        }
        Ok(())
    }

    /// Error bars: `lower` and `upper` together on every point or on none, around the value, on
    /// a bar chart without groups.
    fn validate_error_bars(&self) -> Result<(), ChartError> {
        self.validate_series_bounds()?;
        let used = self
            .data
            .iter()
            .any(|point| point.lower.is_some() || point.upper.is_some());
        if !used {
            return Ok(());
        }
        for (index, point) in self.data.iter().enumerate() {
            let path = format!("/data/{index}");
            if !matches!(self.chart_type, ChartType::Bar | ChartType::Line) {
                return Err(ChartError::new(
                    "option_not_supported",
                    format!("{path}/lower"),
                    "error bars belong to a bar chart or a line chart",
                ));
            }
            if point.group.is_some() {
                return Err(ChartError::new(
                    "option_not_supported",
                    format!("{path}/group"),
                    "a bar chart takes error bars or groups, not both",
                ));
            }
            let (Some(lower), Some(upper)) = (point.lower, point.upper) else {
                return Err(ChartError::new(
                    "missing_bounds",
                    path,
                    "give every point both lower and upper, or none",
                ));
            };
            validate_number(lower, &format!("{path}/lower"))?;
            validate_number(upper, &format!("{path}/upper"))?;
            let Some(value) = point.value else {
                return Err(ChartError::new(
                    "invalid_bounds",
                    format!("{path}/value"),
                    "an error bar needs a value between lower and upper; give the value or remove lower and upper",
                ));
            };
            if !(lower..=upper).contains(&value) {
                return Err(ChartError::new(
                    "invalid_bounds",
                    format!("{path}/lower"),
                    "the value must lie between lower and upper",
                ));
            }
        }
        Ok(())
    }

    /// Either every point names a group or none does, and there are no more groups than palette
    /// colors; only bar charts have groups.
    fn validate_data_groups(&self) -> Result<(), ChartError> {
        let grouped = self.data.iter().any(|point| point.group.is_some());
        let mut groups: Vec<&str> = Vec::new();
        for (index, point) in self.data.iter().enumerate() {
            let path = format!("/data/{index}/group");
            let Some(group) = point.group.as_deref() else {
                if grouped {
                    return Err(ChartError::new(
                        "missing_group",
                        path,
                        "give every point a group, or none",
                    ));
                }
                continue;
            };
            if self.chart_type != ChartType::Bar {
                return Err(ChartError::new(
                    "option_not_supported",
                    path,
                    "groups color the bars of a bar chart",
                ));
            }
            validate_text(group, &path, 60)?;
            if !groups.contains(&group) {
                groups.push(group);
            }
            if groups.len() > MAX_SERIES {
                return Err(ChartError::new(
                    "too_many_series",
                    path,
                    format!("at most {MAX_SERIES} groups are supported, one per palette color"),
                ));
            }
        }
        Ok(())
    }

    pub(super) fn validate_bar_and_line(&self) -> Result<Vec<ChartWarning>, ChartError> {
        let warnings = self.validate_data()?;
        self.validate_references()?;
        self.validate_slope_and_rank()?;
        if self.chart_type == ChartType::Line
            && self.series.is_empty()
            && self.data.iter().all(|point| point.value.is_none())
        {
            return Err(ChartError::new(
                "empty_series",
                "/data",
                "line charts require at least one numeric value",
            ));
        }
        Ok(warnings)
    }

    /// A slope chart compares exactly two categories, a rank chart at least two series over at
    /// least two categories; both need a value in every category and take no error bars, zoom
    /// steps or, for ranks, value axis.
    fn validate_slope_and_rank(&self) -> Result<(), ChartError> {
        if !(self.slope || self.rank) || self.chart_type != ChartType::Line {
            return Ok(());
        }
        let field = if self.slope { "/slope" } else { "/rank" };
        let refuse = |code, path: &str, message: &str| Err(ChartError::new(code, path, message));
        if self.slope && self.rank {
            return refuse(
                "option_not_supported",
                "/rank",
                "a line chart is a slope chart or a rank chart, not both; remove one",
            );
        }
        if self.series.is_empty() {
            return refuse(
                "option_not_supported",
                field,
                "needs `categories` with `series`: every series is one line",
            );
        }
        if self.slope && self.categories.len() != 2 {
            return refuse(
                "invalid_categories",
                "/categories",
                "a slope chart compares exactly two categories; use `rank` or a plain line chart for more",
            );
        }
        if self.rank && (self.categories.len() < 2 || self.series.len() < 2) {
            return refuse(
                "invalid_categories",
                "/categories",
                "a rank chart needs at least two categories and two series",
            );
        }
        for (index, series) in self.series.iter().enumerate() {
            if let Some(gap) = series.values.iter().position(Option::is_none) {
                return refuse(
                    "missing_value",
                    &format!("/series/{index}/values/{gap}"),
                    "a slope or rank chart needs a value in every category",
                );
            }
            if !series.lower.is_empty() || !series.upper.is_empty() {
                return refuse(
                    "option_not_supported",
                    &format!("/series/{index}/lower"),
                    "a slope or rank chart has no error bars; remove them",
                );
            }
        }
        if !self.zoom_steps.is_empty() {
            return refuse(
                "option_not_supported",
                "/zoomSteps",
                "a slope or rank chart has no zoom steps; remove them",
            );
        }
        if self.rank && self.value_axis != super::ValueAxisSpec::default() {
            return refuse(
                "option_not_supported",
                "/valueAxis",
                "a rank chart plots ranks, not values; remove the value axis",
            );
        }
        Ok(())
    }

    /// Every reference line has a usable value and a label; a chart takes at most four.
    pub(super) fn validate_references(&self) -> Result<(), ChartError> {
        if self.references.len() > MAX_REFERENCES {
            return Err(ChartError::new(
                "too_many_references",
                "/references",
                format!("use at most {MAX_REFERENCES} reference lines"),
            ));
        }
        for (index, reference) in self.references.iter().enumerate() {
            validate_number(reference.value, &format!("/references/{index}/value"))?;
            validate_text(&reference.label, &format!("/references/{index}/label"), 60)?;
        }
        Ok(())
    }

    pub(super) fn validate_zoom_steps(&self) -> Result<(), ChartError> {
        // Zoom steps slice `data` or `categories`, which only bar and line charts have; every
        // other type rejects the field by name.
        if !matches!(self.chart_type, ChartType::Bar | ChartType::Line) {
            return Ok(());
        }
        if self.zoom_steps.len() == 1 {
            return Err(ChartError::new(
                "not_enough_zoom_steps",
                "/zoomSteps",
                "provide at least 2 zoom steps so the view can be switched",
            ));
        }
        for (i, step) in self.zoom_steps.iter().enumerate() {
            validate_text(&step.label, &format!("/zoomSteps/{i}/label"), 40)?;
            let index = |field: &str, bound: &ZoomBound| {
                bound.index().ok_or_else(|| {
                    ChartError::new(
                        "invalid_spec",
                        format!("/zoomSteps/{i}/{field}"),
                        "expected a category index, a whole number from 0",
                    )
                })
            };
            let from = index("from", &step.from)?;
            let to = index("to", &step.to)?;
            if from > to {
                return Err(ChartError::new(
                    "invalid_zoom_step",
                    format!("/zoomSteps/{i}/from"),
                    "from must not be greater than to",
                ));
            }
            let count = if self.data.is_empty() {
                self.categories.len()
            } else {
                self.data.len()
            };
            if to >= count {
                return Err(ChartError::new(
                    "zoom_out_of_range",
                    format!("/zoomSteps/{i}/to"),
                    format!("to must be less than the number of categories ({count})"),
                ));
            }
        }
        if self.zoom_steps.len() > 4 {
            return Err(ChartError::new(
                "too_many_zoom_steps",
                "/zoomSteps",
                "at most 4 zoom steps are supported",
            ));
        }
        Ok(())
    }

    pub(super) fn validate_data(&self) -> Result<Vec<ChartWarning>, ChartError> {
        self.validate_stack()?;
        if self.categories.is_empty() && self.series.is_empty() {
            self.validate_points()
        } else {
            self.validate_series()
        }
    }

    fn validate_series_shape(&self) -> Result<(), ChartError> {
        if !self.data.is_empty() {
            return Err(ChartError::new(
                "conflicting_data_shape",
                "/data",
                "use either data or categories with series, not both",
            ));
        }
        if self.categories.is_empty() {
            return Err(ChartError::new(
                "empty_data",
                "/categories",
                "provide at least one category",
            ));
        }
        if self.categories.len() > MAX_DATA_POINTS {
            return Err(ChartError::new(
                "too_many_data_points",
                "/categories",
                format!("at most {MAX_DATA_POINTS} categories are supported"),
            ));
        }
        if self.series.is_empty() {
            return Err(ChartError::new(
                "empty_data",
                "/series",
                "provide at least one series",
            ));
        }
        if self.series.len() > MAX_SERIES {
            return Err(ChartError::new(
                "too_many_series",
                "/series",
                format!("at most {MAX_SERIES} series are supported"),
            ));
        }
        Ok(())
    }

    /// A stack needs several series; a percent stack takes no negative values, since a share of
    /// a total cannot be negative.
    fn validate_stack(&self) -> Result<(), ChartError> {
        if self.stack.is_none() {
            return Ok(());
        }
        if self.series.len() < 2 {
            return Err(ChartError::new(
                "option_not_supported",
                "/stack",
                "stacking needs categories with at least two series",
            ));
        }
        if self.stack == Some(Stack::Stream) {
            return Err(ChartError::new(
                "option_not_supported",
                "/stack",
                "stream stacks the area layers of a time pane; bars use \"normal\" or \"percent\"",
            ));
        }
        if self.stack == Some(Stack::Percent) {
            for (series_index, series) in self.series.iter().enumerate() {
                if let Some(value_index) = series
                    .values
                    .iter()
                    .position(|value| value.is_some_and(|value| value < 0.0))
                {
                    return Err(ChartError::new(
                        "invalid_value",
                        format!("/series/{series_index}/values/{value_index}"),
                        "a percent stack shows shares of a total and takes no negative values",
                    ));
                }
            }
        }
        Ok(())
    }

    fn validate_series(&self) -> Result<Vec<ChartWarning>, ChartError> {
        self.validate_series_shape()?;
        let mut labels = BTreeSet::new();
        for (index, category) in self.categories.iter().enumerate() {
            let path = format!("/categories/{index}");
            validate_text(category, &path, 200)?;
            if !labels.insert(category.as_str()) {
                return Err(ChartError::new(
                    "duplicate_label",
                    path,
                    "categories must be unique",
                ));
            }
        }

        let mut names = BTreeSet::new();
        for (series_index, series) in self.series.iter().enumerate() {
            let name_path = format!("/series/{series_index}/name");
            validate_text(&series.name, &name_path, 100)?;
            if !names.insert(series.name.as_str()) {
                return Err(ChartError::new(
                    "duplicate_series",
                    name_path,
                    "series names must be unique",
                ));
            }
            if series.values.len() != self.categories.len() {
                return Err(ChartError::new(
                    "series_length_mismatch",
                    format!("/series/{series_index}/values"),
                    format!(
                        "expected {} values, one per category; use null for a missing value",
                        self.categories.len()
                    ),
                ));
            }
            for (value_index, value) in series.values.iter().enumerate() {
                if let Some(value) = value {
                    validate_number(
                        *value,
                        &format!("/series/{series_index}/values/{value_index}"),
                    )?;
                }
            }
        }
        self.validate_series_bounds()?;
        if self
            .series
            .iter()
            .flat_map(|series| &series.values)
            .all(Option::is_none)
        {
            return Err(ChartError::new(
                "empty_series",
                "/series",
                "provide at least one numeric value",
            ));
        }

        let mut warnings = Vec::new();
        if self.categories.len() > 16 {
            warnings.push(ChartWarning::new(
                "dense_chart",
                "/categories",
                "more than 16 categories can be difficult to read at the configured size",
            ));
        }
        Ok(warnings)
    }

    fn validate_points(&self) -> Result<Vec<ChartWarning>, ChartError> {
        if self.data.is_empty() {
            return Err(ChartError::new(
                "empty_data",
                "/data",
                "provide at least one data point",
            ));
        }
        if self.data.len() > MAX_DATA_POINTS {
            return Err(ChartError::new(
                "too_many_data_points",
                "/data",
                format!("at most {MAX_DATA_POINTS} data points are supported"),
            ));
        }

        let mut labels = BTreeSet::new();
        let mut warnings = Vec::new();
        for (index, point) in self.data.iter().enumerate() {
            let label_path = format!("/data/{index}/label");
            validate_text(&point.label, &label_path, 200)?;
            if let Some(value) = point.value {
                validate_number(value, &format!("/data/{index}/value"))?;
            } else if self.chart_type == ChartType::Bar {
                return Err(ChartError::new(
                    "missing_bar_value",
                    format!("/data/{index}/value"),
                    "bar charts require a numeric value for every category",
                ));
            }
            if !labels.insert(point.label.as_str()) {
                return Err(ChartError::new(
                    "duplicate_label",
                    label_path,
                    "labels must be unique in a single-series chart",
                ));
            }
        }

        self.validate_data_groups()?;
        self.validate_error_bars()?;
        if self.data.len() > 16 {
            warnings.push(ChartWarning::new(
                "dense_chart",
                "/data",
                "more than 16 categories can be difficult to read at the configured size",
            ));
        }
        Ok(warnings)
    }
}