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
280
281
282
283
284
285
286
287
288
#![warn(
clippy::doc_markdown,
clippy::redundant_closure,
clippy::explicit_iter_loop,
clippy::match_same_arms,
clippy::needless_borrow,
clippy::print_stdout,
clippy::integer_arithmetic,
clippy::cast_possible_truncation,
clippy::result_unwrap_used,
clippy::result_map_unwrap_or_else,
clippy::option_unwrap_used,
clippy::option_map_unwrap_or_else,
clippy::option_map_unwrap_or,
clippy::trivially_copy_pass_by_ref,
clippy::needless_pass_by_value,
missing_docs,
missing_debug_implementations,
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
variant_size_differences
)]
use crate::parse::Declaration;
use kuchiki::traits::TendrilSink;
use kuchiki::{parse_html, ElementData, NodeDataRef, Selectors};
pub mod error;
mod parse;
pub use error::InlineError;
use std::collections::HashMap;
#[derive(Debug)]
struct Rule {
selectors: Selectors,
declarations: Vec<Declaration>,
}
impl Rule {
pub fn new(selectors: &str, declarations: Vec<Declaration>) -> Result<Rule, ()> {
Ok(Rule {
selectors: Selectors::compile(selectors)?,
declarations,
})
}
}
fn process_style_node(node: &NodeDataRef<ElementData>) -> Vec<Rule> {
let css = node.text_contents();
let mut parse_input = cssparser::ParserInput::new(css.as_str());
let mut parser = parse::CSSParser::new(&mut parse_input);
parser
.parse()
.filter_map(|r| {
r.map(|(selector, declarations)| Rule::new(&selector, declarations))
.ok()
})
.collect::<Result<Vec<_>, _>>()
.map_err(|_| error::InlineError::ParseError)
.expect("Parsing error")
}
pub fn inline(html: &str) -> Result<String, InlineError> {
let document = parse_html().one(html);
let rules = document
.select("style")
.map_err(|_| error::InlineError::ParseError)?
.map(|ref node| process_style_node(node))
.flatten();
for rule in rules {
let matching_elements = document
.inclusive_descendants()
.filter_map(|node| node.into_element_ref())
.filter(|element| rule.selectors.matches(element));
for matching_element in matching_elements {
let mut attributes = matching_element.attributes.borrow_mut();
let style = if let Some(existing_style) = attributes.get("style") {
merge_styles(existing_style, &rule.declarations)?
} else {
rule.declarations
.iter()
.map(|&(ref key, ref value)| format!("{}:{};", key, value))
.collect()
};
attributes.insert("style", style);
}
}
let mut out = vec![];
document
.select("html")
.map_err(|_| error::InlineError::ParseError)?
.next()
.expect("HTML tag should be present")
.as_node()
.serialize(&mut out)?;
Ok(String::from_utf8_lossy(&out).to_string())
}
fn merge_styles(existing_style: &str, new_styles: &[Declaration]) -> Result<String, InlineError> {
let mut input = cssparser::ParserInput::new(existing_style);
let mut parser = cssparser::Parser::new(&mut input);
let declarations =
cssparser::DeclarationListParser::new(&mut parser, parse::CSSDeclarationListParser);
let mut styles: HashMap<String, String> = HashMap::new();
for declaration in declarations.into_iter() {
let (property, value) = declaration?;
styles.insert(property.to_string(), value.to_string());
}
for (property, value) in new_styles.iter() {
styles.insert(property.to_string(), value.to_string());
}
Ok(styles
.iter()
.map(|(key, value)| format!("{}:{};", key, value))
.collect::<String>())
}
#[cfg(test)]
mod tests {
use crate::*;
const HTML: &str = r#"<html>
<head>
<title>Test</title>
<style>
h1, h2 { color:red; }
strong {
text-decoration:none
}
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1>Big Text</h1>
<p><strong>Yes!</strong></p>
<p class="footer">Foot notes</p>
</body>
</html>"#;
#[test]
fn test_inline() {
let inlined = inline(HTML).expect("Should be valid");
assert_eq!(
inlined,
r#"<html><head>
<title>Test</title>
<style>
h1, h2 { color:red; }
strong {
text-decoration:none
}
p { font-size:2px }
p.footer { font-size: 1px}
</style>
</head>
<body>
<h1 style="color:red;">Big Text</h1>
<p style="font-size:2px ;"><strong style="text-decoration:none
;">Yes!</strong></p>
<p class="footer" style="font-size: 1px;">Foot notes</p>
</body></html>"#
)
}
#[test]
fn test_merge_styles() {
let html = r#"<html>
<head>
<title>Test</title>
<style>
h1 { color:red; }
</style>
</head>
<body>
<h1 style="font-size: 1px">Big Text</h1>
</body>
</html>"#;
let inlined = inline(html).expect("Should be valid");
let valid = (inlined
== r#"<html><head>
<title>Test</title>
<style>
h1 { color:red; }
</style>
</head>
<body>
<h1 style="color:red;font-size: 1px;">Big Text</h1>
</body></html>"#)
|| (inlined
== r#"<html><head>
<title>Test</title>
<style>
h1 { color:red; }
</style>
</head>
<body>
<h1 style="font-size: 1px;color:red;">Big Text</h1>
</body></html>"#);
assert!(valid, inlined)
}
}