chartlet 0.1.0-alpha.3

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
mod error;
mod layout;
mod metrics;
mod render;
mod scene;
mod spec;

use std::fmt::Write as _;

pub use error::{ChartError, ChartWarning};
pub use metrics::{BuiltinMetrics, TextMetrics};
use spec::Dataset;
pub use spec::{
    CategoryAxisSpec, ChartSpec, ChartType, DataPoint, Orientation, SeriesSpec, ValueAxisSpec,
    ValueFormat, ZoomStep,
};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenderFormat {
    Svg,
    Html,
}

#[derive(Debug, Clone, Default)]
pub struct RenderOptions {
    pub id_prefix: Option<String>,
    pub table_mode: TableMode,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TableMode {
    #[default]
    Details,
    Visible,
}

#[derive(Debug, Clone)]
pub struct RenderOutput {
    pub content: String,
    pub warnings: Vec<ChartWarning>,
}

/// Parses and renders a chart specification.
///
/// # Errors
///
/// Returns a structured error when parsing, validation, or rendering fails.
pub fn render_json(
    input: &str,
    format: RenderFormat,
    options: &RenderOptions,
) -> Result<RenderOutput, ChartError> {
    let spec = ChartSpec::from_json(input)?;
    render(&spec, format, options)
}

/// Validates and renders an already parsed chart specification.
///
/// # Errors
///
/// Returns a structured error when the specification or render context is invalid.
pub fn render(
    spec: &ChartSpec,
    format: RenderFormat,
    options: &RenderOptions,
) -> Result<RenderOutput, ChartError> {
    render_with_metrics(spec, format, options, &BuiltinMetrics)
}

/// Renders with caller-provided deterministic text metrics.
///
/// # Errors
///
/// Returns a structured error when the specification or render context is invalid.
pub fn render_with_metrics(
    spec: &ChartSpec,
    format: RenderFormat,
    options: &RenderOptions,
    metrics: &impl TextMetrics,
) -> Result<RenderOutput, ChartError> {
    let mut warnings = spec.validate()?;
    let id_prefix = match &options.id_prefix {
        Some(id_prefix) => {
            validate_id_prefix(id_prefix)?;
            id_prefix.clone()
        }
        None => default_id_prefix(spec)?,
    };

    // Zoom steps render as pre-computed variants switched by radio buttons, which only the
    // HTML profile can carry. The pure SVG profile stays a single static chart.
    if format == RenderFormat::Html && spec.zoom_steps.len() > 1 {
        let mut panels = Vec::new();
        for (index, step) in spec.zoom_steps.iter().enumerate() {
            let sliced = spec.sliced(step.from, step.to);
            let panel_prefix = format!("{id_prefix}-z{index}");
            let svg = render_panel(&sliced, &panel_prefix, metrics, &mut warnings);
            panels.push((step.label.clone(), svg));
        }
        dedupe_warnings(&mut warnings);
        return Ok(RenderOutput {
            content: render::html_zoom(&panels, spec, options.table_mode, &id_prefix),
            warnings,
        });
    }

    let svg = render_panel(spec, &id_prefix, metrics, &mut warnings);
    let content = match format {
        RenderFormat::Svg => svg,
        RenderFormat::Html => render::html(&svg, spec, options.table_mode),
    };
    Ok(RenderOutput { content, warnings })
}

/// Lays out and serializes one chart, using its explicit description or a generated one.
fn render_panel(
    spec: &ChartSpec,
    id_prefix: &str,
    metrics: &impl TextMetrics,
    warnings: &mut Vec<ChartWarning>,
) -> String {
    let description = spec
        .description
        .clone()
        .unwrap_or_else(|| automatic_description(spec));
    let scene = layout::layout(spec, warnings, metrics);
    render::svg(&scene, spec, &description, id_prefix)
}

/// Zoom panels repeat the same data, so identical warnings would otherwise appear once per panel.
fn dedupe_warnings(warnings: &mut Vec<ChartWarning>) {
    let mut seen = std::collections::BTreeSet::new();
    warnings.retain(|warning| seen.insert((warning.code, warning.path.clone())));
}

fn validate_id_prefix(value: &str) -> Result<(), ChartError> {
    let mut characters = value.chars();
    let valid_start = characters
        .next()
        .is_some_and(|character| character.is_ascii_alphabetic());
    let valid_rest = characters
        .all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'));
    if !valid_start || !valid_rest || value.len() > 64 {
        return Err(ChartError::new(
            "invalid_id_prefix",
            "/render/idPrefix",
            "use 1–64 ASCII letters, digits, hyphens, or underscores, starting with a letter",
        ));
    }
    Ok(())
}

fn default_id_prefix(spec: &ChartSpec) -> Result<String, ChartError> {
    let canonical = serde_json::to_vec(spec).map_err(|error| {
        ChartError::new(
            "serialization_failed",
            "/",
            format!("could not canonicalize the chart specification: {error}"),
        )
    })?;
    let hash = canonical
        .iter()
        .fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
            (hash ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3)
        });
    Ok(format!("chartlet-{hash:016x}"))
}

fn automatic_description(spec: &ChartSpec) -> String {
    let dataset = spec.dataset();
    let chart = chart_type_name(spec.chart_type);
    let show = |value| layout::format_value(value, spec.value_axis.format);
    let highest_value = dataset
        .values()
        .max_by(f64::total_cmp)
        .expect("validated charts contain data");
    let lowest_value = dataset
        .values()
        .min_by(f64::total_cmp)
        .expect("validated charts contain data");
    let categories = dataset.categories.len();
    let grouped = dataset.series.len() > 1;
    let equal = highest_value.total_cmp(&lowest_value).is_eq();

    if !grouped && equal {
        return format!(
            "{chart} with {categories} equal values: {} each.",
            show(highest_value)
        );
    }
    let mut description = if grouped {
        let names = dataset
            .series
            .iter()
            .filter_map(|series| series.name)
            .collect::<Vec<_>>()
            .join(", ");
        format!(
            "{chart} with {categories} categories and {} series ({names}).",
            dataset.series.len()
        )
    } else {
        format!("{chart} with {categories} categories.")
    };
    if equal {
        write!(description, " All values: {}.", show(highest_value))
    } else {
        write!(
            description,
            " Highest: {} ({}). Lowest: {} ({}).",
            show(highest_value),
            labels_at_value(&dataset, highest_value),
            show(lowest_value),
            labels_at_value(&dataset, lowest_value)
        )
    }
    .expect("writing to String cannot fail");
    if grouped {
        let missing = dataset
            .series
            .iter()
            .flat_map(|series| &series.values)
            .filter(|value| value.is_none())
            .count();
        match missing {
            0 => {}
            1 => description.push_str(" 1 value is missing."),
            missing => write!(description, " {missing} values are missing.")
                .expect("writing to String cannot fail"),
        }
    }
    description
}

fn labels_at_value(dataset: &Dataset<'_>, value: f64) -> String {
    let grouped = dataset.series.len() > 1;
    dataset
        .categories
        .iter()
        .enumerate()
        .flat_map(|(index, category)| {
            dataset
                .series
                .iter()
                .filter(move |series| {
                    series.values[index]
                        .is_some_and(|series_value| series_value.total_cmp(&value).is_eq())
                })
                .map(move |series| match series.name {
                    Some(name) if grouped => format!("{name} in {category}"),
                    _ => (*category).to_owned(),
                })
        })
        .collect::<Vec<_>>()
        .join(", ")
}

const fn chart_type_name(chart_type: ChartType) -> &'static str {
    match chart_type {
        ChartType::Bar => "Bar chart",
        ChartType::Line => "Line chart",
    }
}

#[cfg(test)]
mod tests {
    use super::{RenderFormat, RenderOptions, render_json};

    const SPEC: &str = r#"{
        "schemaVersion": 1,
        "type": "bar",
        "title": "Profit & loss",
        "data": [
            {"label": "North <East>", "value": 12},
            {"label": "South", "value": -4}
        ]
    }"#;

    #[test]
    fn renders_accessible_deterministic_svg() {
        let first = render_json(SPEC, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        let second = render_json(SPEC, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        assert_eq!(first.content, second.content);
        assert!(first.content.contains("role=\"img\""));
        assert!(first.content.contains("<title id="));
        assert!(first.content.contains("<desc id="));
        assert!(first.content.contains("North &lt;East&gt;"));
        assert!(first.content.contains("height=\""));
    }

    #[test]
    fn html_contains_complete_data_table() {
        let output = render_json(SPEC, RenderFormat::Html, &RenderOptions::default()).unwrap();
        assert!(output.content.contains("<figure"));
        assert!(output.content.contains("<details"));
        assert!(output.content.contains("<table>"));
        assert!(output.content.contains("<td>-4</td>"));
    }

    #[test]
    fn deserialization_errors_use_json_pointers() {
        for (input, code, path) in [
            (
                SPEC.replace("\"title\"", "\"colour\": 1, \"title\""),
                "invalid_spec",
                "/colour",
            ),
            (
                SPEC.replace("12}", "\"12\"}"),
                "invalid_spec",
                "/data/0/value",
            ),
            (
                SPEC.replace("\"title\": \"Profit & loss\",", ""),
                "invalid_spec",
                "/",
            ),
            ("{\"schemaVersion\": 1,".to_owned(), "invalid_json", "/"),
        ] {
            let error =
                render_json(&input, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
            assert_eq!((error.code, error.path.as_str()), (code, path), "{input}");
        }
    }

    #[test]
    fn rejects_duplicate_labels_with_path() {
        let duplicate = SPEC.replace("South", "North <East>");
        let error =
            render_json(&duplicate, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "duplicate_label");
        assert_eq!(error.path, "/data/1/label");
    }

    #[test]
    fn explicit_prefix_prevents_duplicate_ids() {
        let first = render_json(
            SPEC,
            RenderFormat::Svg,
            &RenderOptions {
                id_prefix: Some("first".to_owned()),
                ..RenderOptions::default()
            },
        )
        .unwrap();
        let second = render_json(
            SPEC,
            RenderFormat::Svg,
            &RenderOptions {
                id_prefix: Some("second".to_owned()),
                ..RenderOptions::default()
            },
        )
        .unwrap();
        assert!(first.content.contains("first-title"));
        assert!(second.content.contains("second-title"));
    }

    #[test]
    fn preserves_small_values_in_every_text_alternative() {
        let small = SPEC.replace("12}", "0.001}");
        let output = render_json(&small, RenderFormat::Html, &RenderOptions::default()).unwrap();
        assert!(output.content.contains("<td>0.001</td>"));
        assert!(output.content.contains("0.001"));
    }

    #[test]
    fn rejects_values_outside_the_supported_scale_range() {
        let extreme = SPEC.replace("12}", "1e308}");
        let error =
            render_json(&extreme, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "unsupported_numeric_range");
        assert_eq!(error.path, "/data/0/value");
    }

    #[test]
    fn rejects_xml_control_characters() {
        let invalid = SPEC.replace("Profit & loss", "Bad\\u0000title");
        let error =
            render_json(&invalid, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "invalid_xml_character");
        assert_eq!(error.path, "/title");
    }

    #[test]
    fn equal_values_do_not_invent_extrema() {
        let tied = SPEC.replace("-4", "12");
        let output = render_json(&tied, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        assert!(
            output
                .content
                .contains("Bar chart with 2 equal values: 12 each.")
        );
    }

    #[test]
    fn visible_table_mode_omits_details_disclosure() {
        let output = render_json(
            SPEC,
            RenderFormat::Html,
            &RenderOptions {
                table_mode: super::TableMode::Visible,
                ..RenderOptions::default()
            },
        )
        .unwrap();
        assert!(output.content.contains("<div class=\"chartlet-data\">"));
        assert!(!output.content.contains("<details"));
    }

    #[test]
    fn line_chart_preserves_missing_values_as_gaps() {
        let specification = include_str!("../examples/monthly-trend.json");
        let output =
            render_json(specification, RenderFormat::Html, &RenderOptions::default()).unwrap();
        assert_eq!(output.content.matches("<polyline").count(), 2);
        assert_eq!(output.content.matches("<circle").count(), 5);
        assert!(output.content.contains("<td>Missing</td>"));
    }

    const GROUPED: &str = r#"{
        "schemaVersion": 1,
        "type": "bar",
        "title": "Budget and actual",
        "categories": ["Jan", "Feb", "Mar"],
        "series": [
            {"name": "Budget", "values": [120, 150, 140]},
            {"name": "Actual", "values": [130, 145, null]}
        ]
    }"#;

    #[test]
    fn grouped_bars_render_legend_bars_and_series_table() {
        let output = render_json(GROUPED, RenderFormat::Html, &RenderOptions::default()).unwrap();
        // Every bar plus one legend swatch per series.
        assert_eq!(
            output
                .content
                .matches("class=\"chartlet-bar chartlet-series-1\"")
                .count(),
            4
        );
        assert_eq!(
            output
                .content
                .matches("class=\"chartlet-bar chartlet-series-2\"")
                .count(),
            3
        );
        assert!(
            output
                .content
                .contains("<th scope=\"col\">Budget</th><th scope=\"col\">Actual</th>")
        );
        assert!(
            output
                .content
                .contains("<th scope=\"row\">Mar</th><td>140</td><td>Missing</td>")
        );
        assert!(output.content.contains(
            "Bar chart with 3 categories and 2 series (Budget, Actual). Highest: 150 (Budget in Feb). Lowest: 120 (Budget in Jan). 1 value is missing."
        ));
    }

    #[test]
    fn grouped_bars_reject_mismatched_series_length() {
        let short = GROUPED.replace("[130, 145, null]", "[130, 145]");
        let error = render_json(&short, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "series_length_mismatch");
        assert_eq!(error.path, "/series/1/values");
    }

    #[test]
    fn data_and_series_are_mutually_exclusive() {
        let both = GROUPED.replace(
            "\"categories\"",
            "\"data\": [{\"label\": \"Jan\", \"value\": 1}], \"categories\"",
        );
        let error = render_json(&both, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "conflicting_data_shape");
        assert_eq!(error.path, "/data");
    }

    #[test]
    fn line_charts_do_not_accept_series_yet() {
        let line = GROUPED.replace("\"bar\"", "\"line\"");
        let error = render_json(&line, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "option_not_supported");
        assert_eq!(error.path, "/series");
    }

    #[test]
    fn single_series_output_carries_no_series_styles() {
        let output = render_json(SPEC, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        assert!(!output.content.contains("chartlet-series-"));
    }

    #[test]
    fn short_negative_bar_keeps_its_label_readable() {
        let specification = r#"{
            "schemaVersion": 1,
            "type": "bar",
            "orientation": "horizontal",
            "title": "Change",
            "valueAxis": {"format": "percent"},
            "data": [
                {"label": "A", "value": 0.3},
                {"label": "B", "value": -0.005}
            ]
        }"#;
        let output =
            render_json(specification, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        assert!(
            output
                .content
                .contains("text-anchor=\"end\" class=\"chartlet-value\">-0.5%</text>")
        );
        assert!(!output.content.contains("class=\"chartlet-value-inverse\""));
    }

    #[test]
    fn bar_chart_rejects_missing_values() {
        let missing = SPEC.replace("12}", "null}");
        let error =
            render_json(&missing, RenderFormat::Svg, &RenderOptions::default()).unwrap_err();
        assert_eq!(error.code, "missing_bar_value");
        assert_eq!(error.path, "/data/0/value");
    }

    #[test]
    fn grouped_bars_render_series_filter_checkboxes() {
        let output = render_json(GROUPED, RenderFormat::Html, &RenderOptions::default()).unwrap();
        assert!(
            output
                .content
                .contains("<fieldset class=\"chartlet-filter\">")
        );
        assert!(output.content.contains("class=\"series-0\" checked"));
        assert!(output.content.contains("data-series=\"0\""));
        assert!(output.content.contains("<text data-series=\"0\""));
        assert!(output.content.contains("<title>Jan – Budget: 120</title>"));
    }

    #[test]
    fn single_series_bars_carry_native_tooltips() {
        let output = render_json(SPEC, RenderFormat::Svg, &RenderOptions::default()).unwrap();
        assert!(
            output
                .content
                .contains("<title>North &lt;East&gt;: 12</title>")
        );
        assert!(!output.content.contains("data-series"));
    }

    #[test]
    fn zoom_steps_render_radio_selectable_panels() {
        let specification = r#"{
            "schemaVersion": 1,
            "type": "bar",
            "title": "Quarterly revenue",
            "data": [
                {"label": "Q1", "value": 320},
                {"label": "Q2", "value": 345},
                {"label": "Q3", "value": 380},
                {"label": "Q4", "value": 410}
            ],
            "zoomSteps": [
                {"label": "First half", "from": 0, "to": 1},
                {"label": "All", "from": 0, "to": 3}
            ]
        }"#;
        let output =
            render_json(specification, RenderFormat::Html, &RenderOptions::default()).unwrap();
        assert!(
            output
                .content
                .contains("<fieldset class=\"chartlet-zoom\">")
        );
        assert!(
            output
                .content
                .contains("class=\"chartlet-panel chartlet-panel-0\"")
        );
        assert!(
            output
                .content
                .contains("class=\"chartlet-panel chartlet-panel-1\"")
        );
        assert!(output.content.contains("class=\"zoom-0\" checked"));
        // Every panel gets its own non-colliding accessibility IDs.
        assert_eq!(output.content.matches("<title id=").count(), 2);
    }

    #[test]
    fn a_single_zoom_step_is_rejected() {
        let specification = r#"{
            "schemaVersion": 1,
            "type": "bar",
            "title": "Quarterly revenue",
            "data": [
                {"label": "Q1", "value": 320},
                {"label": "Q2", "value": 345}
            ],
            "zoomSteps": [
                {"label": "All", "from": 0, "to": 1}
            ]
        }"#;
        let error = render_json(specification, RenderFormat::Svg, &RenderOptions::default())
            .expect_err("one zoom step cannot provide a choice");
        assert_eq!(error.code, "not_enough_zoom_steps");
        assert_eq!(error.path, "/zoomSteps");
    }
}