Skip to main content

plotting/
svg.rs

1//! SVG renderer. Uses plotters' `SVGBackend` and the shared `draw`
2//! dispatch in `draw.rs` so the canvas renderer produces identical
3//! layouts.
4
5use plotters::prelude::*;
6
7use crate::draw::{NEUTRAL, draw_on};
8use 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]
15pub fn render_svg(spec: &ChartSpec, width: u32, height: u32, text_px: u32) -> String {
16    let mut buf = String::new();
17    let ok = {
18        let backend = SVGBackend::with_string(&mut buf, (width, height));
19        let root = backend.into_drawing_area();
20        draw_on(&root, spec, text_px, NEUTRAL).is_ok()
21    };
22
23    if ok && !buf.is_empty() {
24        return buf;
25    }
26    fallback_svg(spec, width, height)
27}
28
29fn fallback_svg(spec: &ChartSpec, width: u32, height: u32) -> String {
30    let RGBColor(r, g, b) = NEUTRAL;
31    format!(
32        "<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             fill=\"#{r:02x}{g:02x}{b:02x}\">{}</text>\
36         </svg>",
37        escape_xml(&spec.title),
38        escape_xml(&spec.title),
39    )
40}
41
42fn escape_xml(s: &str) -> String {
43    s.replace('&', "&amp;")
44        .replace('<', "&lt;")
45        .replace('>', "&gt;")
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51    use crate::layout::DEFAULT_TEXT_PX;
52    use crate::spec::{ChartKind, Series, SeriesPoint};
53
54    fn sample(kind: ChartKind) -> ChartSpec {
55        ChartSpec {
56            title: "Test".to_string(),
57            kind,
58            x_label: "X".to_string(),
59            y_label: "Y".to_string(),
60            series: vec![Series {
61                label: "A".to_string(),
62                commodity_symbol: "USD".to_string(),
63                points: vec![
64                    SeriesPoint {
65                        x: "Jan".to_string(),
66                        y_num: 100,
67                        y_denom: 1,
68                    },
69                    SeriesPoint {
70                        x: "Feb".to_string(),
71                        y_num: 200,
72                        y_denom: 1,
73                    },
74                ],
75            }],
76            notes: vec![],
77        }
78    }
79
80    #[test]
81    fn render_svg_emits_non_empty_svg_for_each_kind() {
82        for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
83            let svg = render_svg(&sample(kind), 400, 300, DEFAULT_TEXT_PX);
84            assert!(svg.contains("<svg"), "missing <svg for {kind:?}");
85            assert!(svg.contains("Test"), "title missing for {kind:?}");
86        }
87    }
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    fn render_svg_draws_a_real_chart_not_the_fallback() {
95        for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
96            let svg = render_svg(&sample(kind), 400, 300, DEFAULT_TEXT_PX);
97            let texts = svg.matches("<text").count();
98            assert!(
99                texts >= 3,
100                "{kind:?}: {texts} <text> elements — this is the degraded fallback, \
101                 not a drawn chart (font registration or drawing failed)"
102            );
103            assert!(
104                svg.contains("<path") || svg.contains("<rect") || svg.contains("<polyline"),
105                "{kind:?}: no chart geometry in the SVG"
106            );
107        }
108    }
109
110    #[test]
111    fn the_fallback_text_is_neutral_not_black() {
112        let spec = ChartSpec {
113            title: "A & B".to_string(),
114            ..sample(ChartKind::Bar)
115        };
116        assert_eq!(
117            fallback_svg(&spec, 40, 30),
118            "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"30\">\
119             <title>A &amp; B</title>\
120             <text x=\"10\" y=\"20\" font-family=\"sans-serif\" font-size=\"14\" \
121             fill=\"#767676\">A &amp; B</text></svg>"
122        );
123    }
124
125    #[test]
126    fn render_svg_draws_no_background() {
127        let svg = render_svg(&sample(ChartKind::Bar), 400, 300, DEFAULT_TEXT_PX);
128        assert!(
129            !svg.contains("<rect x=\"0\" y=\"0\" width=\"400\" height=\"300\""),
130            "background rect present: {svg}"
131        );
132        assert!(!svg.contains("#FFFFFF"), "white fill present: {svg}");
133    }
134
135    #[test]
136    fn render_svg_includes_series_label() {
137        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        assert!(svg.contains('A'), "series label missing");
141    }
142
143    #[test]
144    fn render_svg_empty_spec_is_safe() {
145        let spec = ChartSpec {
146            title: "Empty".to_string(),
147            kind: ChartKind::Bar,
148            x_label: String::new(),
149            y_label: String::new(),
150            series: vec![],
151            notes: vec![],
152        };
153        let svg = render_svg(&spec, 400, 300, DEFAULT_TEXT_PX);
154        assert!(svg.contains("<svg"));
155    }
156}