1
//! SVG renderer. Uses plotters' `SVGBackend` and the shared `draw`
2
//! dispatch in `draw.rs` so the canvas renderer produces identical
3
//! layouts.
4

            
5
use plotters::prelude::*;
6

            
7
use crate::draw::{NEUTRAL, draw_on};
8
use crate::spec::ChartSpec;
9

            
10
/// Render `spec` to an SVG string of the given dimensions, its text `text_px`
11
/// high. Drawing
12
/// errors fall back to a minimal SVG with the chart title so a broken
13
/// chart never fails a page render.
14
#[must_use]
15
1537
pub fn render_svg(spec: &ChartSpec, width: u32, height: u32, text_px: u32) -> String {
16
1537
    let mut buf = String::new();
17
    let ok = {
18
1537
        let backend = SVGBackend::with_string(&mut buf, (width, height));
19
1537
        let root = backend.into_drawing_area();
20
1537
        draw_on(&root, spec, text_px, NEUTRAL).is_ok()
21
    };
22

            
23
1537
    if ok && !buf.is_empty() {
24
1537
        return buf;
25
    }
26
    fallback_svg(spec, width, height)
27
1537
}
28

            
29
1
fn fallback_svg(spec: &ChartSpec, width: u32, height: u32) -> String {
30
1
    let RGBColor(r, g, b) = NEUTRAL;
31
1
    format!(
32
1
        "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\">\
33
             <title>{}</title>\
34
             <text x=\"10\" y=\"20\" font-family=\"sans-serif\" font-size=\"14\" \
35
1
             fill=\"#{r:02x}{g:02x}{b:02x}\">{}</text>\
36
         </svg>",
37
1
        escape_xml(&spec.title),
38
1
        escape_xml(&spec.title),
39
    )
40
1
}
41

            
42
2
fn escape_xml(s: &str) -> String {
43
2
    s.replace('&', "&amp;")
44
2
        .replace('<', "&lt;")
45
2
        .replace('>', "&gt;")
46
2
}
47

            
48
#[cfg(test)]
49
mod tests {
50
    use super::*;
51
    use crate::layout::DEFAULT_TEXT_PX;
52
    use crate::spec::{ChartKind, Series, SeriesPoint};
53

            
54
9
    fn sample(kind: ChartKind) -> ChartSpec {
55
9
        ChartSpec {
56
9
            title: "Test".to_string(),
57
9
            kind,
58
9
            x_label: "X".to_string(),
59
9
            y_label: "Y".to_string(),
60
9
            series: vec![Series {
61
9
                label: "A".to_string(),
62
9
                commodity_symbol: "USD".to_string(),
63
9
                points: vec![
64
9
                    SeriesPoint {
65
9
                        x: "Jan".to_string(),
66
9
                        y_num: 100,
67
9
                        y_denom: 1,
68
9
                    },
69
9
                    SeriesPoint {
70
9
                        x: "Feb".to_string(),
71
9
                        y_num: 200,
72
9
                        y_denom: 1,
73
9
                    },
74
9
                ],
75
9
            }],
76
9
            notes: vec![],
77
9
        }
78
9
    }
79

            
80
    #[test]
81
1
    fn render_svg_emits_non_empty_svg_for_each_kind() {
82
1
        for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
83
3
            let svg = render_svg(&sample(kind), 400, 300, DEFAULT_TEXT_PX);
84
3
            assert!(svg.contains("<svg"), "missing <svg for {kind:?}");
85
3
            assert!(svg.contains("Test"), "title missing for {kind:?}");
86
        }
87
1
    }
88

            
89
    /// The title-only fallback also contains "<svg" and the title, so the tests
90
    /// above would pass with charts completely broken — which is exactly what
91
    /// happened when font lookup failed at runtime. Pin the real thing: axis
92
    /// ticks and labels mean text was actually shaped, not skipped.
93
    #[test]
94
1
    fn render_svg_draws_a_real_chart_not_the_fallback() {
95
1
        for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
96
3
            let svg = render_svg(&sample(kind), 400, 300, DEFAULT_TEXT_PX);
97
3
            let texts = svg.matches("<text").count();
98
3
            assert!(
99
3
                texts >= 3,
100
                "{kind:?}: {texts} <text> elements — this is the degraded fallback, \
101
                 not a drawn chart (font registration or drawing failed)"
102
            );
103
3
            assert!(
104
3
                svg.contains("<path") || svg.contains("<rect") || svg.contains("<polyline"),
105
                "{kind:?}: no chart geometry in the SVG"
106
            );
107
        }
108
1
    }
109

            
110
    #[test]
111
1
    fn the_fallback_text_is_neutral_not_black() {
112
1
        let spec = ChartSpec {
113
1
            title: "A & B".to_string(),
114
1
            ..sample(ChartKind::Bar)
115
1
        };
116
1
        assert_eq!(
117
1
            fallback_svg(&spec, 40, 30),
118
1
            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"30\">\
119
1
             <title>A &amp; B</title>\
120
1
             <text x=\"10\" y=\"20\" font-family=\"sans-serif\" font-size=\"14\" \
121
1
             fill=\"#767676\">A &amp; B</text></svg>"
122
        );
123
1
    }
124

            
125
    #[test]
126
1
    fn render_svg_draws_no_background() {
127
1
        let svg = render_svg(&sample(ChartKind::Bar), 400, 300, DEFAULT_TEXT_PX);
128
1
        assert!(
129
1
            !svg.contains("<rect x=\"0\" y=\"0\" width=\"400\" height=\"300\""),
130
            "background rect present: {svg}"
131
        );
132
1
        assert!(!svg.contains("#FFFFFF"), "white fill present: {svg}");
133
1
    }
134

            
135
    #[test]
136
1
    fn render_svg_includes_series_label() {
137
1
        let svg = render_svg(&sample(ChartKind::Line), 400, 300, DEFAULT_TEXT_PX);
138
        // Plotters escapes text; "A" should appear at least once in
139
        // the legend or axis.
140
1
        assert!(svg.contains('A'), "series label missing");
141
1
    }
142

            
143
    #[test]
144
1
    fn render_svg_empty_spec_is_safe() {
145
1
        let spec = ChartSpec {
146
1
            title: "Empty".to_string(),
147
1
            kind: ChartKind::Bar,
148
1
            x_label: String::new(),
149
1
            y_label: String::new(),
150
1
            series: vec![],
151
1
            notes: vec![],
152
1
        };
153
1
        let svg = render_svg(&spec, 400, 300, DEFAULT_TEXT_PX);
154
1
        assert!(svg.contains("<svg"));
155
1
    }
156
}