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
//! `html_editor` is a simple html parser and editor.
//!
//! Quick Start:
//! ```
//! use html_editor::operation::*;
//! use html_editor::{parse, Node};
//!
//! // You can create DOM nodes by parsing html string.
//! let html = r#"
//!     <!doctype html>
//!     <html>
//!         <head>
//!         </head>
//!         <body>
//!         </body>
//!     </html>
//! "#;
//! let mut dom = parse(html).unwrap();
//!
//! // Or you can create a node by some built-in methods like below.
//! let app: Node = Node::new_element("div", vec![("id", "app")], vec![]);
//!
//! // Here shows how to edit the nodes and turn it back to html.
//! let html = dom
//!     .remove_by(&Selector::from("head"))
//!     .insert_to(&Selector::from("body"), app)
//!     .trim()
//!     .html();
//!
//! assert_eq!(
//!     html,
//!     r#"<!DOCTYPE html><html><body><div id="app"></div></body></html>"#
//! );
//! ```

mod data;
mod parse;

pub mod operation;

pub use parse::parse;
pub use parse::try_parse;

/// Doctype of Html or Xml
#[derive(Clone, Debug)]
pub enum Doctype {
    Html,
    Xml { version: String, encoding: String },
}

/// Node of DOM
#[derive(Debug, Clone)]
pub enum Node {
    Element {
        name: String,
        attrs: Vec<(String, String)>,
        children: Vec<Node>,
    },
    Text(String),
    Comment(String),
    Doctype(Doctype),
}

impl Node {
    /// Check if it is an element node.
    ///
    /// ```
    /// use html_editor::Node;
    ///
    /// assert_eq!(Node::new_element("div", vec![("id", "app")], vec![]).is_element(), true);
    /// assert_eq!(Node::Text("Lorem Ipsum".to_string()).is_element(), false);
    /// ```
    pub fn is_element(&self) -> bool {
        matches!(self, Node::Element { .. })
    }

    /// Convert the node into an element.
    ///
    /// Warning: The program will panic if it fails to convert.
    /// So take care to use this method unless you are sure.
    ///
    /// Example:
    /// ```
    /// use html_editor::{Node, Element};
    ///
    /// let a: Node = Node::new_element("div", vec![("id", "app")], vec![]);
    /// let a: Element = a.into_element();
    ///
    /// let b: Node = Node::Text("hello".to_string());
    /// // The next line will panic at 'Text("hello") is not an element'
    /// // let b: Element = a.into_element();
    /// ```
    pub fn into_element(self) -> Element {
        match self {
            Node::Element {
                name,
                attrs,
                children,
            } => Element {
                name,
                attrs,
                children,
            },
            _ => panic!("{:?} is not an element", self),
        }
    }

    /// Create a new element node.
    ///
    /// ```
    /// use html_editor::Node;
    ///
    /// let node: Node = Node::new_element(
    ///     "h1",
    ///     vec![("class", "title")],
    ///     vec![
    ///         Node::Text("Hello, world!".to_string()),
    ///     ]
    /// );
    /// ```
    pub fn new_element(name: &str, attrs: Vec<(&str, &str)>, children: Vec<Node>) -> Node {
        Node::Element {
            name: name.to_string(),
            attrs: attrs
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            children,
        }
    }
}

/// HTML Element
#[derive(Debug)]
pub struct Element {
    pub name: String,
    pub attrs: Vec<(String, String)>,
    pub children: Vec<Node>,
}

impl Element {
    /// Create a new element.
    pub fn new(name: &str, attrs: Vec<(&str, &str)>, children: Vec<Node>) -> Self {
        Self {
            name: name.to_string(),
            attrs: attrs
                .into_iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect(),
            children,
        }
    }
}