Lines
97.94 %
Functions
84.62 %
Branches
100 %
//! SVG renderer. Uses plotters' `SVGBackend` and the shared `draw`
//! dispatch in `draw.rs` so the canvas renderer produces identical
//! layouts.
use plotters::prelude::*;
use crate::draw::{NEUTRAL, draw_on};
use crate::spec::ChartSpec;
/// Render `spec` to an SVG string of the given dimensions, its text `text_px`
/// high. Drawing
/// errors fall back to a minimal SVG with the chart title so a broken
/// chart never fails a page render.
#[must_use]
pub fn render_svg(spec: &ChartSpec, width: u32, height: u32, text_px: u32) -> String {
let mut buf = String::new();
let ok = {
let backend = SVGBackend::with_string(&mut buf, (width, height));
let root = backend.into_drawing_area();
draw_on(&root, spec, text_px, NEUTRAL).is_ok()
};
if ok && !buf.is_empty() {
return buf;
}
fallback_svg(spec, width, height)
fn fallback_svg(spec: &ChartSpec, width: u32, height: u32) -> String {
let RGBColor(r, g, b) = NEUTRAL;
format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\">\
<title>{}</title>\
<text x=\"10\" y=\"20\" font-family=\"sans-serif\" font-size=\"14\" \
fill=\"#{r:02x}{g:02x}{b:02x}\">{}</text>\
</svg>",
escape_xml(&spec.title),
)
fn escape_xml(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
#[cfg(test)]
mod tests {
use super::*;
use crate::layout::DEFAULT_TEXT_PX;
use crate::spec::{ChartKind, Series, SeriesPoint};
fn sample(kind: ChartKind) -> ChartSpec {
ChartSpec {
title: "Test".to_string(),
kind,
x_label: "X".to_string(),
y_label: "Y".to_string(),
series: vec![Series {
label: "A".to_string(),
commodity_symbol: "USD".to_string(),
points: vec![
SeriesPoint {
x: "Jan".to_string(),
y_num: 100,
y_denom: 1,
},
x: "Feb".to_string(),
y_num: 200,
],
}],
notes: vec![],
#[test]
fn render_svg_emits_non_empty_svg_for_each_kind() {
for kind in [ChartKind::Bar, ChartKind::StackedBar, ChartKind::Line] {
let svg = render_svg(&sample(kind), 400, 300, DEFAULT_TEXT_PX);
assert!(svg.contains("<svg"), "missing <svg for {kind:?}");
assert!(svg.contains("Test"), "title missing for {kind:?}");
/// The title-only fallback also contains "<svg" and the title, so the tests
/// above would pass with charts completely broken — which is exactly what
/// happened when font lookup failed at runtime. Pin the real thing: axis
/// ticks and labels mean text was actually shaped, not skipped.
fn render_svg_draws_a_real_chart_not_the_fallback() {
let texts = svg.matches("<text").count();
assert!(
texts >= 3,
"{kind:?}: {texts} <text> elements — this is the degraded fallback, \
not a drawn chart (font registration or drawing failed)"
);
svg.contains("<path") || svg.contains("<rect") || svg.contains("<polyline"),
"{kind:?}: no chart geometry in the SVG"
fn the_fallback_text_is_neutral_not_black() {
let spec = ChartSpec {
title: "A & B".to_string(),
..sample(ChartKind::Bar)
assert_eq!(
fallback_svg(&spec, 40, 30),
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"40\" height=\"30\">\
<title>A & B</title>\
fill=\"#767676\">A & B</text></svg>"
fn render_svg_draws_no_background() {
let svg = render_svg(&sample(ChartKind::Bar), 400, 300, DEFAULT_TEXT_PX);
!svg.contains("<rect x=\"0\" y=\"0\" width=\"400\" height=\"300\""),
"background rect present: {svg}"
assert!(!svg.contains("#FFFFFF"), "white fill present: {svg}");
fn render_svg_includes_series_label() {
let svg = render_svg(&sample(ChartKind::Line), 400, 300, DEFAULT_TEXT_PX);
// Plotters escapes text; "A" should appear at least once in
// the legend or axis.
assert!(svg.contains('A'), "series label missing");
fn render_svg_empty_spec_is_safe() {
title: "Empty".to_string(),
kind: ChartKind::Bar,
x_label: String::new(),
y_label: String::new(),
series: vec![],
let svg = render_svg(&spec, 400, 300, DEFAULT_TEXT_PX);
assert!(svg.contains("<svg"));