use super::{Hue, Point, Shape};
const SPAN: f32 = 1000.0;
pub(super) fn document(shapes: &[Shape]) -> String {
let mut out = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {SPAN:.0} {SPAN:.0}\" \
width=\"{SPAN:.0}\" height=\"{SPAN:.0}\">\n"
);
for shape in shapes {
out.push_str(&element(shape));
out.push('\n');
}
out.push_str("</svg>\n");
out
}
fn element(shape: &Shape) -> String {
match shape {
Shape::Trace { path, width, fill } => format!(
" <path d=\"{}\" fill=\"none\" stroke=\"{}\" stroke-width=\"{}\" \
stroke-linecap=\"round\" stroke-linejoin=\"round\"/>",
polyline(path),
hex(*fill),
place(*width)
),
Shape::Lune { ribs, fill } => format!(
" <path d=\"{} Z\" fill=\"{}\"/>",
polyline(&Shape::outline(ribs)),
hex(*fill)
),
Shape::Disc {
cx,
cy,
radius,
fill,
} => format!(
" <circle cx=\"{}\" cy=\"{}\" r=\"{}\" fill=\"{}\"/>",
place(*cx),
place(*cy),
place(*radius),
hex(*fill)
),
}
}
fn polyline(path: &[Point]) -> String {
path.iter()
.enumerate()
.map(|(index, (x, y))| {
let verb = if index == 0 { 'M' } else { 'L' };
format!("{verb}{},{}", place(*x), place(*y))
})
.collect::<Vec<String>>()
.join(" ")
}
fn place(unit: f32) -> String {
format!("{:.1}", unit * SPAN)
}
fn hex(fill: Hue) -> String {
let [red, green, blue] = fill;
format!("#{red:02x}{green:02x}{blue:02x}")
}