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
/*
 * @author Mike 'PhiSyX' S. (https://github.com/PhiSyX)
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use core::fmt;
use std::collections::HashMap;
use std::path;
use std::sync::Mutex;

mod comment;
mod doctype;
mod element;
mod fragment;
mod text;

// ------ //
// Static //
// ------ //

lazy_static::lazy_static! {
	pub static ref MEMOIZE_FILE: Mutex<
		HashMap<path::PathBuf, String>
	> = Mutex::new(HashMap::default());
}

// ----------- //
// Énumération //
// ----------- //

pub enum Node {
	/// Commentaire HTML.
	Comment(comment::CommentNode),
	/// Type de document HTML.
	Doctype(doctype::DoctypeNode),
	/// Fragments HTML.
	Fragment(fragment::FragmentNode),
	/// Elements HTML.
	Element(element::ElementNode),
	/// Noeud texte.
	Text(text::TextNode),
	/// Noeud texte (json).
	Json(text::JsonTextNode),
	/// Noeud texte non sûr
	UnsafeHtml(text::DangerousTextNode),
}

// -------------- //
// Implémentation //
// -------------- //

// Comment
impl Node {
	pub fn create_comment(comment: impl ToString) -> Self {
		Self::Comment(comment::CommentNode {
			content: comment.to_string(),
		})
	}
}

// Doctype
impl Node {
	pub fn create_doctype(public_identifier: impl ToString) -> Self {
		Self::Doctype(doctype::DoctypeNode {
			public_identifier: public_identifier.to_string(),
		})
	}
}

// Fragment
impl Node {
	pub fn create_fragment(children: Vec<Node>) -> Self {
		Self::Fragment(fragment::FragmentNode { children })
	}
}

// Element
impl Node {
	pub fn create_element(
		tag_name: String,
		attributes: Vec<(String, Option<String>)>,
		children: Option<Vec<Node>>,
	) -> Self {
		Self::Element(element::ElementNode {
			tag_name,
			attributes,
			children,
		})
	}
}

// Text
impl Node {
	pub fn create_text(text: impl ToString) -> Self {
		Self::Text(text::TextNode {
			text: text.to_string(),
		})
	}

	pub fn create_json(text: impl ToString) -> Self {
		Self::Json(text::JsonTextNode {
			text: text.to_string(),
		})
	}
}

// Unsafe HTML
impl Node {
	pub fn create_unsafe_html(raw_text: impl ToString) -> Self {
		Self::UnsafeHtml(text::DangerousTextNode {
			raw_text: raw_text.to_string(),
		})
	}

	pub fn create_unsafe_html_from_file(file: impl AsRef<path::Path>) -> Self {
		let mut memoize = MEMOIZE_FILE.lock().expect("cache guard");

		if let Some(content_of_file) = memoize.get(file.as_ref()) {
			return Self::UnsafeHtml(text::DangerousTextNode {
				raw_text: content_of_file.to_owned(),
			});
		}

		let raw_text = std::fs::read_to_string(&file).unwrap_or_else(|_| {
			panic!("le fichier « {} » n'existe pas.", file.as_ref().display())
		});
		memoize.insert(file.as_ref().to_owned(), raw_text.clone());
		Self::UnsafeHtml(text::DangerousTextNode { raw_text })
	}
}

// -------- //
// Fonction //
// -------- //

fn with_children(
	f: &mut fmt::Formatter<'_>,
	children: &[Node],
	is_fragment: bool,
) -> fmt::Result {
	if f.alternate() {
		let mut children = children.iter();

		if is_fragment {
			if let Some(first_child) = children.next() {
				write!(f, "{first_child:#}")?;

				for child in children {
					write!(f, "\n{child:#}")?;
				}
			}
		} else {
			for child in children.map(|child| format!("{child:#}")) {
				for line in child.lines() {
					write!(f, "\n\t{line}")?;
				}
			}
			writeln!(f)?;
		}
	} else {
		use std::fmt::Display;

		for child in children {
			child.fmt(f)?;
		}
	}

	Ok(())
}

// -------------- //
// Implémentation // -> Interface
// -------------- //

impl Default for Node {
	fn default() -> Self {
		Self::create_fragment(vec![])
	}
}

impl fmt::Display for Node {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match &self {
			| Self::Comment(comment) => comment.fmt(f),
			| Self::Doctype(doctype) => doctype.fmt(f),
			| Self::Fragment(fragment) => fragment.fmt(f),
			| Self::Element(element) => element.fmt(f),
			| Self::Text(text) => text.fmt(f),
			| Self::Json(text) => text.fmt(f),
			| Self::UnsafeHtml(danger) => danger.fmt(f),
		}
	}
}

impl<It, F> From<It> for Node
where
	It: IntoIterator<Item = F>,
	F: Into<Self>,
{
	fn from(it: It) -> Self {
		Self::Fragment(it.into())
	}
}

impl From<comment::CommentNode> for Node {
	fn from(comment_node: comment::CommentNode) -> Self {
		Self::Comment(comment_node)
	}
}

impl From<doctype::DoctypeNode> for Node {
	fn from(doctype_node: doctype::DoctypeNode) -> Self {
		Self::Doctype(doctype_node)
	}
}

impl From<fragment::FragmentNode> for Node {
	fn from(fragment_node: fragment::FragmentNode) -> Self {
		Self::Fragment(fragment_node)
	}
}

impl From<element::ElementNode> for Node {
	fn from(element_node: element::ElementNode) -> Self {
		Self::Element(element_node)
	}
}

impl From<text::TextNode> for Node {
	fn from(text_node: text::TextNode) -> Self {
		Self::Text(text_node)
	}
}