rbatis_codegen/codegen/
loader_html.rs1use html_parser::{Dom, Node, Result};
2use std::collections::HashMap;
3use std::fmt::{Debug, Display, Formatter};
4
5#[derive(Clone, Eq, PartialEq, Debug)]
6pub struct Element {
7 pub tag: String,
8 pub data: String,
9 pub attrs: HashMap<String, String>,
10 pub childs: Vec<Element>,
11}
12
13impl Display for Element {
14 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
15 match self.tag.as_str() {
16 "" => {
17 f.write_str(&self.data)?;
18 }
19 _ => {
20 f.write_str("<")?;
21 f.write_str(&self.tag)?;
22 for (k, v) in &self.attrs {
23 f.write_str(" ")?;
24 f.write_str(k)?;
25 f.write_str("=\"")?;
26 f.write_str(v)?;
27 f.write_str("\"")?;
28 }
29 f.write_str(">")?;
30 for x in &self.childs {
31 std::fmt::Display::fmt(x, f)?;
32 }
33 f.write_str("</")?;
35 f.write_str(&self.tag)?;
36 f.write_str(">")?;
37 }
38 }
39 return Ok(());
40 }
41}
42
43pub fn as_element(args: &Vec<Node>) -> Vec<Element> {
44 let mut els = vec![];
45 for x in args {
46 let mut el = Element {
47 tag: "".to_string(),
48 data: "".to_string(),
49 attrs: HashMap::with_capacity(50),
50 childs: vec![],
51 };
52 match x {
53 Node::Text(txt) => {
54 if txt.is_empty() {
55 continue;
56 }
57 el.data = txt.to_string();
58 }
59 Node::Element(element) => {
60 el.tag = element.name.to_string();
61 if el.tag == "bk" {
62 el.tag = "break".to_string();
63 }
64 if element.id.is_some() {
65 el.attrs.insert(
66 "id".to_string(),
67 element.id.as_ref().unwrap_or(&String::new()).clone(),
68 );
69 }
70 for (k, v) in &element.attributes {
71 el.attrs
72 .insert(k.clone(), v.as_ref().unwrap_or(&String::new()).clone());
73 }
74 if !element.children.is_empty() {
75 let childs = as_element(&element.children);
76 el.childs = childs;
77 }
78 }
79 Node::Comment(_comment) => {
80 }
82 }
83 els.push(el);
84 }
85 els
86}
87
88pub fn load_html(html: &str) -> Result<Vec<Element>> {
89 let mut html = html.to_string();
90 html = html
91 .replace("<break>", "<bk>")
92 .replace("<break/>", "<bk/>")
93 .replace("</break>", "</bk>");
94 let dom = Dom::parse(&html)?;
95 let els = as_element(&dom.children);
96 return Ok(els);
97}
98
99impl Element {
100 pub fn child_strings(&self) -> Vec<&str> {
102 let mut elements = vec![];
103 for x in &self.childs {
104 if x.tag.eq("") {
105 elements.push(x.data.as_str());
106 }
107 let v = x.child_strings();
108 for x in v {
109 elements.push(x);
110 }
111 }
112 elements
113 }
114 pub fn child_string_cup(&self) -> usize {
116 let mut u = 0;
117 for x in self.child_strings() {
118 u += x.len();
119 }
120 u
121 }
122}