isis-report-lib 0.2.2

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
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
//! Dependency-free SVG charts and sparklines.
//!
//! Every interpolation is either numeric or escaped; the assembly helpers only
//! concatenate pre-built fragments. HTML rendering marks these strings safe,
//! so no report data can become markup.

use indexmap::IndexMap;

use crate::error::{Error, Result};
use crate::pyops;
use crate::value::Value;

/// Default chart palette.
pub const DEFAULT_COLORS: [&str; 6] = ["#0A2F46", "#1B7A3D", "#B8860B", "#8B3A3A", "#4A6FA5", "#6B4A8B"];

fn escape_text(value: &str) -> String {
    value.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
}

fn escape_attr(value: &str) -> String {
    escape_text(value).replace('"', "&quot;")
}

fn format_g(value: f64) -> String {
    if value == 0.0 {
        return "0".to_string();
    }
    if !value.is_finite() {
        return pyops::py_float_str(value);
    }
    let abs = value.abs();
    if abs >= 1e6 || abs < 1e-4 {
        let raw = format!("{value:.5e}");
        let (mantissa, exponent) = raw.split_once('e').unwrap_or((&raw, "0"));
        let mantissa = trim_zeros(mantissa);
        let exponent: i32 = exponent.parse().unwrap_or(0);
        format!("{mantissa}e{}{:02}", if exponent < 0 { '-' } else { '+' }, exponent.abs())
    } else {
        let digits_before = if abs >= 1.0 { abs.log10().floor() as i32 + 1 } else { 1 };
        let decimals = (6 - digits_before).max(0) as usize;
        trim_zeros(&format!("{value:.decimals$}"))
    }
}

fn trim_zeros(value: &str) -> String {
    if value.contains('.') {
        value.trim_end_matches('0').trim_end_matches('.').to_string()
    } else {
        value.to_string()
    }
}

fn check_series(labels: &[Value], values: &[Value]) -> Result<(Vec<String>, Vec<f64>)> {
    if labels.is_empty() || values.is_empty() {
        return Err(Error::option("Chart needs non-empty labels and values."));
    }
    if labels.len() != values.len() {
        return Err(Error::option(format!(
            "Chart labels ({}) and values ({}) must match in length.",
            labels.len(),
            values.len()
        )));
    }
    let mut numbers = Vec::with_capacity(values.len());
    for value in values {
        numbers.push(pyops::py_float(value).map_err(|_| Error::option("Chart values must be numeric"))?);
    }
    let labels = labels.iter().map(pyops::py_str).collect();
    Ok((labels, numbers))
}

/// Bar chart as an inline SVG string.
pub fn bar_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str, orientation: &str) -> Result<String> {
    if !matches!(orientation, "vertical" | "horizontal") {
        return Err(Error::option(format!(
            "Unknown bar orientation: {orientation:?} (expected vertical|horizontal)"
        )));
    }
    let color = escape_attr(color);
    if orientation == "horizontal" {
        return horizontal_bar_chart(labels, values, width, height, &color);
    }
    let (labels, numbers) = check_series(labels, values)?;
    let top = 22.0;
    let bottom = height as f64 - 30.0;
    let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let span = if max > 0.0 { max } else { 1.0 };
    let n = numbers.len() as f64;
    let slot = width as f64 / n;
    let bar_w = (slot * 0.6).min(60.0);
    let mut parts = vec![format!(
        r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
    )];
    for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
        let bar_h = ((value / span) * (bottom - top)).max(if *value != 0.0 { 2.0 } else { 0.0 });
        let x = slot * index as f64 + (slot - bar_w) / 2.0;
        let y = bottom - bar_h;
        parts.push(format!(
            r#"<rect x="{x:.1}" y="{y:.1}" width="{bar_w:.1}" height="{bar_h:.1}" fill="{color}"/>"#
        ));
        if *value != 0.0 {
            parts.push(format!(
                r#"<text x="{:.1}" y="{:.1}" text-anchor="middle" font-size="11">{}</text>"#,
                x + bar_w / 2.0,
                y - 4.0,
                format_g(*value)
            ));
        }
        parts.push(format!(
            r#"<text x="{:.1}" y="{}" text-anchor="middle" font-size="11">{}</text>"#,
            slot * index as f64 + slot / 2.0,
            height - 8,
            escape_text(label)
        ));
    }
    parts.push(format!(
        r##"<line x1="0" y1="{bottom}" x2="{width}" y2="{bottom}" stroke="#999"/>"##
    ));
    parts.push("</svg>".to_string());
    Ok(parts.concat())
}

/// Horizontal bar chart as an inline SVG string.
pub fn horizontal_bar_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str) -> Result<String> {
    let (labels, numbers) = check_series(labels, values)?;
    let left = 120.0;
    let right = 10.0;
    let row_h = 26.0;
    let gap = 10.0;
    let plot_w = width as f64 - left - right;
    let max = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let span = if max > 0.0 { max } else { 1.0 };
    let plot_h = numbers.len() as f64 * (row_h + gap);
    let total_h = (height as f64).max(plot_h + 20.0);
    let mut parts = vec![format!(
        r#"<svg width="{width}" height="{total_h}" viewBox="0 0 {width} {total_h}" xmlns="http://www.w3.org/2000/svg" role="img">"#
    )];
    for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
        let y = 10.0 + index as f64 * (row_h + gap);
        let bar_w = ((value / span) * plot_w).max(if *value != 0.0 { 2.0 } else { 0.0 });
        parts.push(format!(
            r#"<rect x="{left}" y="{y}" width="{bar_w:.1}" height="{row_h}" fill="{color}"/>"#
        ));
        if *value != 0.0 {
            parts.push(format!(
                r#"<text x="{:.1}" y="{}" font-size="11">{}</text>"#,
                left + bar_w + 4.0,
                y + 17.0,
                format_g(*value)
            ));
        }
        parts.push(format!(
            r#"<text x="{}" y="{}" text-anchor="end" font-size="11">{}</text>"#,
            left - 6.0,
            y + 17.0,
            escape_text(label)
        ));
    }
    parts.push("</svg>".to_string());
    Ok(parts.concat())
}

/// Line chart with dots as an inline SVG string.
pub fn line_chart(labels: &[Value], values: &[Value], width: u32, height: u32, color: &str) -> Result<String> {
    let color = escape_attr(color);
    let (labels, numbers) = check_series(labels, values)?;
    let top = 22.0;
    let bottom = height as f64 - 30.0;
    let left = 40.0;
    let right = width as f64 - 10.0;
    let lo = 0.0f64.min(numbers.iter().copied().fold(f64::INFINITY, f64::min));
    let hi = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let span = if (hi - lo) == 0.0 { 1.0 } else { hi - lo };
    let n = numbers.len();
    let step = if n > 1 { (right - left) / (n - 1) as f64 } else { 0.0 };
    let x = |index: usize| left + step * index as f64;
    let y = |value: f64| bottom - (value - lo) / span * (bottom - top);
    let mut parts = vec![format!(
        r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
    )];
    let points: Vec<String> = numbers
        .iter()
        .enumerate()
        .map(|(index, value)| format!("{:.1},{:.1}", x(index), y(*value)))
        .collect();
    parts.push(format!(
        r#"<polyline points="{}" fill="none" stroke="{color}" stroke-width="2"/>"#,
        points.join(" ")
    ));
    for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
        parts.push(format!(
            r#"<circle cx="{:.1}" cy="{:.1}" r="3" fill="{color}"/>"#,
            x(index),
            y(*value)
        ));
        parts.push(format!(
            r#"<text x="{:.1}" y="{:.1}" text-anchor="middle" font-size="11">{}</text>"#,
            x(index),
            y(*value) - 8.0,
            format_g(*value)
        ));
        parts.push(format!(
            r#"<text x="{:.1}" y="{}" text-anchor="middle" font-size="11">{}</text>"#,
            x(index),
            height - 8,
            escape_text(label)
        ));
    }
    parts.push(format!(
        r##"<line x1="{left}" y1="{bottom}" x2="{right}" y2="{bottom}" stroke="#999"/>"##
    ));
    parts.push("</svg>".to_string());
    Ok(parts.concat())
}

pub(crate) fn spark_numbers(value: &Value) -> Vec<f64> {
    let items: Vec<&Value> = match value {
        Value::Array(values) => values.iter().collect(),
        other => vec![other],
    };
    let mut numbers = Vec::new();
    for item in items {
        if item.is_null() || matches!(item, Value::Bool(_)) {
            continue;
        }
        if let Ok(number) = pyops::py_float(item) {
            numbers.push(number);
        }
    }
    numbers
}

/// Inline SVG nanoplot (`kind`: line or bar); `""` when there is no data.
pub fn sparkline(values: &Value, kind: &str, width: u32, height: u32, color: &str) -> Result<String> {
    if !matches!(kind, "line" | "bar") {
        return Err(Error::option(format!("Unknown sparkline kind: {kind:?} (expected line|bar)")));
    }
    let color = escape_attr(color);
    let numbers = spark_numbers(values);
    if numbers.is_empty() {
        return Ok(String::new());
    }
    let lo = numbers.iter().copied().fold(f64::INFINITY, f64::min);
    let hi = numbers.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    let span = if (hi - lo) == 0.0 { 1.0 } else { hi - lo };
    let pad = 2.0;
    let n = numbers.len();
    let mut parts = vec![format!(
        r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
    )];
    if kind == "line" {
        let step = if n > 1 { (width as f64 - 2.0 * pad) / (n - 1) as f64 } else { 0.0 };
        let point = |index: usize, value: f64| -> (f64, f64) {
            let x = if n == 1 { pad } else { pad + step * index as f64 };
            let y = height as f64 - pad - (value - lo) / span * (height as f64 - 2.0 * pad);
            (x, y)
        };
        if n == 1 {
            parts.push(format!(
                r#"<circle cx="{:.1}" cy="{:.1}" r="2.5" fill="{color}"/>"#,
                width as f64 / 2.0,
                height as f64 / 2.0
            ));
        } else {
            let points: Vec<String> = numbers
                .iter()
                .enumerate()
                .map(|(index, value)| {
                    let (x, y) = point(index, *value);
                    format!("{x:.1},{y:.1}")
                })
                .collect();
            parts.push(format!(
                r#"<polyline points="{}" fill="none" stroke="{color}" stroke-width="1.5"/>"#,
                points.join(" ")
            ));
            let (x, y) = point(n - 1, numbers[n - 1]);
            parts.push(format!(r#"<circle cx="{x:.1}" cy="{y:.1}" r="2" fill="{color}"/>"#));
        }
    } else {
        let slot = (width as f64 - 2.0 * pad) / n as f64;
        let bar_w = (slot * 0.7).max(1.0);
        for (index, value) in numbers.iter().enumerate() {
            let bar_h = (((value - lo) / span) * (height as f64 - 2.0 * pad)).max(if *value != lo || hi == lo { 1.0 } else { 0.0 });
            let left = pad + slot * index as f64 + (slot - bar_w) / 2.0;
            parts.push(format!(
                r#"<rect x="{left:.1}" y="{:.1}" width="{bar_w:.1}" height="{bar_h:.1}" fill="{color}"/>"#,
                height as f64 - pad - bar_h
            ));
        }
    }
    parts.push("</svg>".to_string());
    Ok(parts.concat())
}

/// Pie (or donut) chart with legend as an inline SVG string.
pub fn pie_chart(labels: &[Value], values: &[Value], width: u32, height: u32, colors: Option<&[String]>, donut: bool) -> Result<String> {
    let default_colors: Vec<String> = DEFAULT_COLORS.iter().map(|value| value.to_string()).collect();
    let colors: Vec<String> = colors
        .map(|colors| colors.iter().map(|color| escape_attr(color)).collect())
        .unwrap_or_else(|| default_colors.iter().map(|color| escape_attr(color)).collect());
    let (labels, numbers) = check_series(labels, values)?;
    let total: f64 = numbers.iter().sum();
    if total <= 0.0 {
        return Err(Error::option("Pie chart needs a positive total."));
    }
    let cx = 150.0;
    let cy = (height / 2) as f64;
    let radius = 140.0f64.min((height / 2) as f64 - 10.0);
    let legend_x = 320.0;
    let mut parts = vec![format!(
        r#"<svg width="{width}" height="{height}" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg" role="img">"#
    )];
    let mut angle = -90.0f64;
    for (index, (label, value)) in labels.iter().zip(&numbers).enumerate() {
        let frac = value / total;
        let sweep = frac * 360.0;
        let large = if sweep > 180.0 { 1 } else { 0 };
        let x1 = cx + radius * angle.to_radians().cos();
        let y1 = cy + radius * angle.to_radians().sin();
        let x2 = cx + radius * (angle + sweep).to_radians().cos();
        let y2 = cy + radius * (angle + sweep).to_radians().sin();
        let color = &colors[index % colors.len()];
        parts.push(format!(
            r#"<path d="M {cx},{cy} L {x1:.1},{y1:.1} A {radius},{radius} 0 {large},1 {x2:.1},{y2:.1} Z" fill="{color}"/>"#
        ));
        let ly = 30.0 + index as f64 * 24.0;
        parts.push(format!(
            r#"<rect x="{legend_x}" y="{:.1}" width="12" height="12" fill="{color}"/>"#,
            ly - 12.0
        ));
        parts.push(format!(
            r#"<text x="{}" y="{ly}" font-size="12">{} ({:.0}%)</text>"#,
            legend_x + 18.0,
            escape_text(label),
            frac * 100.0
        ));
        angle += sweep;
    }
    if donut {
        parts.push(format!(r#"<circle cx="{cx}" cy="{cy}" r="{}" fill="white"/>"#, radius / 2.0));
    }
    parts.push("</svg>".to_string());
    Ok(parts.concat())
}

fn values_array(spec: &IndexMap<String, Value>, key: &str) -> Vec<Value> {
    spec.get(key).and_then(Value::as_array).cloned().unwrap_or_default()
}

fn int_option(spec: &IndexMap<String, Value>, key: &str, default: i64) -> Result<u32> {
    match spec.get(key) {
        None | Some(Value::Null) => Ok(default as u32),
        Some(value) => {
            let value = pyops::py_int(value).map_err(|_| Error::option(format!("Invalid chart {key} (expected an integer)")))?;
            u32::try_from(value).map_err(|_| Error::option(format!("Invalid chart {key} (expected a positive integer)")))
        }
    }
}

/// Build a chart SVG from a section spec: `{kind, labels, values, ...}`.
pub fn build_chart(spec: &IndexMap<String, Value>) -> Result<String> {
    let kind = spec.get("kind").and_then(Value::as_str).unwrap_or("bar");
    let labels = values_array(spec, "labels");
    let values = values_array(spec, "values");
    let width = int_option(spec, "width", 600)?;
    let height = int_option(spec, "height", 300)?;
    let color = spec.get("color").and_then(Value::as_str).unwrap_or("#0A2F46");
    match kind {
        "bar" => bar_chart(
            &labels,
            &values,
            width,
            height,
            color,
            spec.get("orientation").and_then(Value::as_str).unwrap_or("vertical"),
        ),
        "line" => line_chart(&labels, &values, width, height, color),
        "pie" | "donut" => {
            let colors = spec.get("colors").and_then(Value::as_array).map(|colors| {
                colors
                    .iter()
                    .filter_map(|color| color.as_str().map(str::to_string))
                    .collect::<Vec<_>>()
            });
            pie_chart(&labels, &values, width, height, colors.as_deref(), kind == "donut")
        }
        other => Err(Error::option(format!(
            "Unknown chart kind: {other:?} (expected one of bar|line|pie|donut)"
        ))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn labels(values: &[&str]) -> Vec<Value> {
        values.iter().map(|value| Value::String((*value).to_string())).collect()
    }

    fn numbers(values: &[f64]) -> Vec<Value> {
        values.iter().map(|value| Value::Float(*value)).collect()
    }

    fn array(values: &[f64]) -> Value {
        Value::Array(numbers(values))
    }

    #[test]
    fn bar_chart_structure() {
        let svg = bar_chart(&labels(&["Jan", "Feb"]), &numbers(&[10.0, 20.0]), 600, 300, "#0A2F46", "vertical").unwrap();
        assert!(svg.starts_with("<svg"));
        assert_eq!(svg.matches("<rect").count(), 2);
        assert!(svg.contains("Jan") && svg.contains("Feb"));
    }

    #[test]
    fn bar_chart_scales_to_max() {
        let svg = bar_chart(&labels(&["A", "B"]), &numbers(&[5.0, 10.0]), 200, 100, "#0A2F46", "vertical").unwrap();
        assert!(svg.contains(r#"height="48.0""#));
    }

    #[test]
    fn line_chart_structure() {
        let svg = line_chart(&labels(&["Jan", "Feb", "Mar"]), &numbers(&[1.0, 3.0, 2.0]), 600, 300, "#0A2F46").unwrap();
        assert!(svg.contains("<polyline"));
        assert_eq!(svg.matches("<circle").count(), 3);
    }

    #[test]
    fn charts_escape_labels() {
        let svg = bar_chart(&labels(&["<b>&"]), &numbers(&[1.0]), 600, 300, "#0A2F46", "vertical").unwrap();
        assert!(svg.contains("&lt;b&gt;&amp;"));
        assert!(!svg.replace("<svg", "").replace("</svg>", "").contains("<b>"));
    }

    #[test]
    fn charts_reject_bad_series() {
        assert!(bar_chart(&[], &[], 600, 300, "#000", "vertical").is_err());
        assert!(line_chart(&labels(&["a", "b"]), &numbers(&[1.0]), 600, 300, "#000").is_err());
        assert!(bar_chart(&labels(&["a"]), &[Value::String("x".into())], 600, 300, "#000", "vertical").is_err());
    }

    #[test]
    fn pie_and_donut() {
        let svg = pie_chart(&labels(&["A", "B"]), &numbers(&[30.0, 70.0]), 600, 300, None, false).unwrap();
        assert_eq!(svg.matches("<path").count(), 2);
        assert!(svg.contains("30%") && svg.contains("70%"));
        let donut = pie_chart(&labels(&["A", "B"]), &numbers(&[1.0, 1.0]), 600, 300, None, true).unwrap();
        assert!(donut.contains("<circle"));
    }

    #[test]
    fn sparkline_line_and_bar() {
        let line = sparkline(&array(&[1.0, 2.0, 3.0, 2.0, 1.0]), "line", 96, 28, "#0A2F46").unwrap();
        assert!(line.starts_with("<svg") && line.contains("<polyline") && line.contains("<circle"));
        let bar = sparkline(&array(&[1.0, 2.0, 3.0]), "bar", 96, 28, "#0A2F46").unwrap();
        assert_eq!(bar.matches("<rect").count(), 3);
        assert!(sparkline(&Value::Array(vec![]), "line", 96, 28, "#000").unwrap().is_empty());
    }
}

#[cfg(test)]
mod extra_tests {
    use super::*;

    fn labels(values: &[&str]) -> Vec<Value> {
        values.iter().map(|value| Value::String((*value).to_string())).collect()
    }

    fn numbers(values: &[f64]) -> Vec<Value> {
        values.iter().map(|value| Value::Float(*value)).collect()
    }

    #[test]
    fn build_chart_dispatch_and_options() {
        let mut spec = indexmap::IndexMap::new();
        spec.insert("kind".into(), Value::String("bar".into()));
        spec.insert("labels".into(), Value::Array(labels(&["A"])));
        spec.insert("values".into(), Value::Array(numbers(&[1.0])));
        spec.insert("orientation".into(), Value::String("horizontal".into()));
        spec.insert("width".into(), Value::Int(400));
        spec.insert("height".into(), Value::Int(200));
        spec.insert("color".into(), Value::String("#123456".into()));
        assert!(build_chart(&spec).unwrap().contains("#123456"));

        spec.insert("kind".into(), Value::String("line".into()));
        assert!(build_chart(&spec).unwrap().contains("<polyline"));
        spec.insert("kind".into(), Value::String("pie".into()));
        assert!(build_chart(&spec).unwrap().contains("<path"));
        spec.insert("kind".into(), Value::String("donut".into()));
        assert!(build_chart(&spec).unwrap().contains("<circle"));
        spec.insert("kind".into(), Value::String("area".into()));
        assert!(build_chart(&spec).is_err());

        spec.insert("kind".into(), Value::String("bar".into()));
        spec.insert("orientation".into(), Value::String("sideways".into()));
        assert!(build_chart(&spec).is_err());
        spec.insert("orientation".into(), Value::String("vertical".into()));
        spec.insert("width".into(), Value::Int(-1));
        assert!(build_chart(&spec).is_err());
        spec.insert("width".into(), Value::String("wide".into()));
        assert!(build_chart(&spec).is_err());
    }

    #[test]
    fn pie_and_sparkline_edges() {
        assert!(pie_chart(&labels(&["A"]), &numbers(&[0.0]), 200, 100, None, false).is_err());
        assert!(pie_chart(&[], &[], 200, 100, None, false).is_err());
        let svg = pie_chart(
            &labels(&["A", "B"]),
            &numbers(&[1.0, 2.0]),
            200,
            100,
            Some(&["#111111".into(), "#222222".into()]),
            false,
        )
        .unwrap();
        assert!(svg.contains("#111111") && svg.contains("#222222"));

        let scalar = sparkline(&Value::Float(5.0), "line", 96, 28, "#000").unwrap();
        assert_eq!(scalar.matches("<circle").count(), 1);
        assert_eq!(sparkline(&Value::Array(vec![]), "bar", 96, 28, "#000").unwrap(), "");
        assert!(sparkline(&Value::Array(vec![Value::Int(1)]), "area", 96, 28, "#000").is_err());
        assert_eq!(
            sparkline(&Value::Array(vec![Value::Int(1)]), "bar", 96, 28, "#000")
                .unwrap()
                .matches("<rect")
                .count(),
            1
        );
    }

    #[test]
    fn horizontal_bar_structure() {
        let svg = horizontal_bar_chart(&labels(&["A", "B"]), &numbers(&[1.0, 2.0]), 400, 200, "#0A2F46").unwrap();
        assert!(svg.contains("A") && svg.contains("B"));
        assert_eq!(svg.matches("<rect").count(), 2);
        assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "horizontal").is_ok());
        assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "vertical").is_ok());
        assert!(bar_chart(&labels(&["A"]), &numbers(&[1.0]), 400, 200, "#0A2F46", "diagonal").is_err());
    }
}