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
use flange_flat_tree::{Subtree, Tree};
use svg::node::Text;
use svg::Node;

use crate::svg_data::svg::SVGWithIDs;

use super::Tag;

fn build_element<'a, ST: Subtree<Node = (&'a Tag, &'a Option<String>)>>(
    svg: &ST,
) -> svg::node::element::Element {
    let tag = svg.value().0;
    let id = svg.value().1;
    let mut el = svg::node::element::Element::new(&tag.name);
    for (name, value) in &tag.args {
        el.assign(name, svg::node::Value::from(value.to_string()))
    }
    if let Some(id) = id {
        el.assign("id", id.clone());
    }
    for child in &svg.children() {
        el.append(build_element(child));
    }
    if !tag.text.is_empty() {
        el.append(Text::new(&tag.text))
    }
    el
}

fn build_doc(svg: &SVGWithIDs) -> svg::Document {
    let mut doc = svg::Document::new();
    let (root_tag, root_id) = svg.root().value();
    for (name, value) in &root_tag.args {
        doc.assign(name, svg::node::Value::from(value.to_string()))
    }
    if let Some(id) = root_id {
        doc.assign("id", id.clone());
    }
    for child in &svg.root().children() {
        doc.append(build_element(child));
    }
    if !root_tag.text.is_empty() {
        doc.append(Text::new(&root_tag.text))
    }
    doc
}

pub fn print_svg(svg: &SVGWithIDs, overwrite_view_box: Option<&svgtypes::ViewBox>) -> String {
    let mut doc = build_doc(svg);
    if let Some(view_box) = overwrite_view_box {
        doc.assign(
            "viewBox",
            format!(
                "{} {} {} {}",
                view_box.x, view_box.y, view_box.w, view_box.h
            ),
        );
    };
    doc.to_string()
}

pub fn print_svg_element<'a, ST: Subtree<Node = (&'a Tag, &'a Option<String>)>>(
    svg: &ST,
) -> String {
    let doc = build_element(svg);
    doc.to_string()
}