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
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! This module parses literal html returns sauron dom tree

use html5ever::{
    local_name, namespace_url, ns, parse_document, parse_fragment,
    tendril::TendrilSink, QualName,
};
use markup5ever_rcdom::{Handle, NodeData, RcDom};
use sauron_core::{
    html::{
        attributes,
        attributes::{
            AttributeValue, Style, HTML_ATTRS, HTML_ATTRS_SPECIAL, HTML_STYLES,
        },
        html_element_sc,
        tags::{
            HTML_SC_TAGS, HTML_TAGS, HTML_TAGS_NON_COMMON,
            HTML_TAGS_WITH_MACRO_NON_COMMON,
        },
        text,
    },
    mt_dom,
    svg::{
        attributes::{SVG_ATTRS, SVG_ATTRS_SPECIAL, SVG_ATTRS_XLINK},
        tags::{SVG_TAGS, SVG_TAGS_NON_COMMON, SVG_TAGS_SPECIAL},
        SVG_NAMESPACE,
    },
    Attribute, Node,
};
use std::{fmt, io};
use thiserror::Error;

/// all the possible error when parsing html string
#[derive(Debug, Error)]
pub enum ParseError {
    /// generic parser error, expressed in string
    #[error("Generic Error {0}")]
    Generic(String),
    /// io error
    #[error("{0}")]
    IoError(#[from] io::Error),
    /// formatting error
    #[error("{0}")]
    FmtError(#[from] fmt::Error),
}

fn match_tag(tag: &str) -> Option<&'static str> {
    HTML_TAGS
        .iter()
        .chain(HTML_SC_TAGS.iter())
        .chain(HTML_TAGS_NON_COMMON.iter())
        .chain(HTML_TAGS_WITH_MACRO_NON_COMMON.iter())
        .chain(SVG_TAGS.iter())
        .chain(SVG_TAGS_NON_COMMON.iter())
        .find(|item| item.eq_ignore_ascii_case(&tag))
        .map(|item| *item)
        .or_else(|| {
            SVG_TAGS_SPECIAL
                .iter()
                .find(|(_func, item)| item.eq_ignore_ascii_case(&tag))
                .map(|(func, _item)| *func)
        })
}

fn match_attribute(key: &str) -> Option<&'static str> {
    HTML_ATTRS
        .iter()
        .chain(SVG_ATTRS.iter())
        .find(|att| att.eq_ignore_ascii_case(&key))
        .map(|att| *att)
        .or_else(|| {
            HTML_ATTRS_SPECIAL
                .iter()
                .chain(SVG_ATTRS_SPECIAL.iter())
                .chain(SVG_ATTRS_XLINK.iter())
                .find(|(_func, att)| att.eq_ignore_ascii_case(&key))
                .map(|(func, _att)| *func)
        })
}

fn match_style_name(key: &str) -> Option<&'static str> {
    HTML_STYLES
        .iter()
        .find(|name| name.eq_ignore_ascii_case(&key))
        .map(|name| *name)
}

/// return the static str of this function name
pub fn match_attribute_function(key: &str) -> Option<&'static str> {
    HTML_ATTRS
        .iter()
        .chain(SVG_ATTRS.iter())
        .find(|att| att.eq_ignore_ascii_case(key))
        .map(|att| *att)
        .or_else(|| {
            HTML_ATTRS_SPECIAL
                .iter()
                .chain(SVG_ATTRS_SPECIAL.iter())
                .chain(SVG_ATTRS_XLINK.iter())
                .find(|(func, _att)| func.eq_ignore_ascii_case(key))
                .map(|(func, _att)| *func)
        })
}

/// Find the namespace of this tag
/// if the arg tag is an SVG tag, return the svg namespace
/// html tags don't need to have namespace while svg does, otherwise it will not be properly
/// mounted into the DOM
pub fn tag_namespace(tag: &str) -> Option<&'static str> {
    let find_svg_tag = SVG_TAGS
        .iter()
        .chain(SVG_TAGS_NON_COMMON.iter())
        .chain(
            SVG_TAGS_SPECIAL
                .iter()
                .map(|(_func, t)| t)
                .collect::<Vec<_>>()
                .into_iter(),
        )
        .find(|t| t.eq_ignore_ascii_case(tag));

    if find_svg_tag.is_some() {
        Some(SVG_NAMESPACE)
    } else {
        None
    }
}

fn extract_attributes<MSG>(
    attrs: &Vec<html5ever::Attribute>,
) -> Vec<Attribute<MSG>> {
    attrs
        .iter()
        .filter_map(|att| {
            let key = att.name.local.to_string();
            let value = att.value.to_string();
            if key == "style" {
                let styles = extract_styles(&value);
                Some(mt_dom::attr("style", AttributeValue::from_styles(styles)))
            } else if let Some(attr) = match_attribute(&key) {
                Some(attributes::attr(attr, value))
            } else {
                log::warn!("Not a standard html attribute: {}", key);
                None
            }
        })
        .collect()
}

/// extract the styles into an arry
/// example: display:flex; flex-direction: column;
fn extract_styles(style: &str) -> Vec<Style> {
    let mut extracted = vec![];
    println!("processing style: {}", style);
    let mut single_styles: Vec<&str> = style.split(";").collect();
    single_styles.retain(|item| !item.trim().is_empty());
    for single in single_styles {
        let key_value: Vec<&str> = single.split(":").collect();
        assert_eq!(key_value.len(), 2);
        let key = key_value[0].trim();
        let value = key_value[1].trim();
        println!("style   [{}] = [{}]", key, value);
        if let Some(match_style) = match_style_name(key) {
            extracted.push(Style::new(match_style, value.to_string().into()));
        }
    }
    extracted
}

fn process_children<MSG>(node: &Handle) -> Vec<Node<MSG>> {
    node.children
        .borrow()
        .iter()
        .filter_map(|child_node| process_node(child_node))
        .collect()
}

fn process_node<MSG>(node: &Handle) -> Option<Node<MSG>> {
    match &node.data {
        NodeData::Text { ref contents } => {
            let text_content = contents.borrow().to_string();
            if text_content.trim().is_empty() {
                None
            } else {
                Some(text(text_content))
            }
        }

        NodeData::Element {
            ref name,
            ref attrs,
            ..
        } => {
            let tag = name.local.to_string();
            if let Some(html_tag) = match_tag(&tag) {
                let children_nodes = process_children(node);
                let attributes = extract_attributes(&attrs.borrow());
                let is_self_closing = HTML_SC_TAGS.contains(&html_tag);
                Some(html_element_sc(
                    html_tag,
                    attributes,
                    children_nodes,
                    is_self_closing,
                ))
            } else {
                log::warn!("Invalid tag: {}", tag);
                None
            }
        }
        NodeData::Document => {
            let mut children_nodes = process_children(node);
            let children_len = children_nodes.len();
            if children_len == 1 {
                Some(children_nodes.remove(0))
            } else if children_len == 2 {
                Some(children_nodes.remove(1))
            } else {
                None
            }
        }
        _ => None,
    }
}

/// Parse html string and convert it into sauron Node
pub fn parse<MSG>(html: &str) -> Result<Option<Node<MSG>>, ParseError> {
    let html_start = html.trim_start();
    let parser = if html_start.starts_with("<html")
        || html_start.starts_with("<!DOCTYPE")
    {
        parse_document(RcDom::default(), Default::default())
    } else {
        parse_fragment(
            RcDom::default(),
            Default::default(),
            QualName::new(None, ns!(html), local_name!("div")),
            vec![],
        )
    };

    let dom = parser.one(html);
    let node = process_node(&dom.document);
    Ok(node)
}

/// the document is not wrapped with html
pub fn parse_simple<MSG>(html: &str) -> Result<Vec<Node<MSG>>, ParseError> {
    if let Some(html) = parse(html)? {
        if let Some(element) = html.take_element() {
            assert_eq!(*element.tag(), "html");
            Ok(element.take_children())
        } else {
            Ok(vec![])
        }
    } else {
        Ok(vec![])
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use sauron_core::{html::div, Render};

    #[test]
    fn test_html_child() {
        let html = r#"<article class="side-to-side">
    <div>
        This is div content1
    </div>
    <footer>
        This is footer
    </footer>
</article>"#;
        let node: Vec<Node<()>> = parse_simple(html).expect("must parse");
        println!("node: {:#?}", node);
        let one = div(vec![], node);
        println!("one: {}", one.render_to_string());
    }
}