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
//! Serialization of nodes to HTML, and of inline `<svg>` subtrees to SVG source for usvg.
use html_escape::{encode_quoted_attribute_to_string, encode_text_to_string};
use markup5ever::{QualName, ns};
use style_traits::values::ToCss;
use super::{Node, NodeData};
#[derive(Clone, Copy)]
enum OutputStyle {
Normal,
Pretty,
}
#[derive(Clone, Copy)]
struct SerializeOpts {
style: OutputStyle,
/// Replace `currentColor` in attribute values with the element's computed `color`
resolve_current_color: bool,
/// Declare the `xlink` prefix on the root element so that the output is well-formed XML
declare_xlink_ns: bool,
}
impl SerializeOpts {
const fn html(style: OutputStyle) -> Self {
Self {
style,
resolve_current_color: false,
declare_xlink_ns: false,
}
}
}
const XLINK_NS: &str = "http://www.w3.org/1999/xlink";
/// Writes an attribute's serialized name, per the HTML fragment serialization algorithm
fn write_attr_name(name: &QualName, writer: &mut String) {
match name.ns {
ns!() | ns!(html) => {}
ns!(xml) => writer.push_str("xml:"),
ns!(xmlns) if name.local.as_str() == "xmlns" => {}
ns!(xmlns) => writer.push_str("xmlns:"),
ns!(xlink) => writer.push_str("xlink:"),
_ => {
if let Some(prefix) = &name.prefix {
writer.push_str(prefix);
writer.push(':');
}
}
}
writer.push_str(&name.local);
}
fn is_xlink_ns_decl(name: &QualName) -> bool {
(name.ns == ns!(xmlns) && name.local.as_str() == "xlink")
|| name.local.as_str() == "xmlns:xlink"
}
impl Node {
/// Renders the HTML of this node and all its children as a `String` without extra whitespace.
///
/// Example output:
///
/// ```text
/// <html><head /><body><main id="main"><div class="arbitrary-class" /></main></body></html>
/// ```
pub fn outer_html(&self) -> String {
let mut output = String::new();
self.write_outer_html(&mut output);
output
}
/// Renders the HTML of this node and all its children as a `String` with whitespace for human
/// readability.
///
/// Example output:
///
/// ```text
/// <html>
/// <head />
/// <body>
/// <main id="main">
/// <div class="arbitrary-class" />
/// </main>
/// </body>
/// </html>
/// ```
pub fn outer_html_pretty(&self) -> String {
let mut output = String::new();
self.write_outer_html_pretty(&mut output);
output
}
pub fn write_outer_html(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, SerializeOpts::html(OutputStyle::Normal), 0);
}
pub fn write_outer_html_pretty(&self, writer: &mut String) {
self.write_outer_html_in_style(writer, SerializeOpts::html(OutputStyle::Pretty), 0);
}
/// Serializes this `<svg>` subtree as a standalone SVG document for usvg, with
/// `currentColor` resolved against each element's computed `color`.
#[cfg(feature = "svg")]
pub(crate) fn svg_source(&self) -> String {
let mut output = String::new();
let opts = SerializeOpts {
style: OutputStyle::Normal,
resolve_current_color: true,
declare_xlink_ns: true,
};
self.write_outer_html_in_style(&mut output, opts, 0);
output
}
fn write_outer_html_in_style(&self, writer: &mut String, opts: SerializeOpts, nesting: usize) {
const INDENT: &str = " ";
let style = opts.style;
let has_children = !self.children.is_empty();
let current_color = opts
.resolve_current_color
.then(|| self.primary_styles())
.flatten()
.map(|style| style.clone_color())
.map(|color| color.to_css_string());
match &self.data {
NodeData::Document(_) => {}
NodeData::Comment { .. } => {}
NodeData::AnonymousBlock(_) => {}
// NodeData::Doctype { name, .. } => write!(s, "DOCTYPE {name}"),
NodeData::Text(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
let in_raw_text_element = self
.parent
.and_then(|id| self.tree()[id].data.downcast_element())
.is_some_and(|el| {
// Documents are parsed with scripting disabled, so `<noscript>` is not raw text
el.name.ns == ns!(html)
&& matches!(
el.name.local.as_ref(),
"style"
| "script"
| "xmp"
| "iframe"
| "noembed"
| "noframes"
| "plaintext"
)
});
if in_raw_text_element {
writer.push_str(data.content.as_str());
} else {
encode_text_to_string(data.content.as_str(), writer);
}
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
}
NodeData::Element(data) => {
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push('<');
writer.push_str(&data.name.local);
if opts.declare_xlink_ns
&& nesting == 0
&& !data.attrs().iter().any(|attr| is_xlink_ns_decl(&attr.name))
{
writer.push_str(" xmlns:xlink=\"");
writer.push_str(XLINK_NS);
writer.push('"');
}
for attr in data.attrs() {
writer.push(' ');
write_attr_name(&attr.name, writer);
writer.push_str("=\"");
#[allow(clippy::unnecessary_unwrap)] // Convert to if-let chain once stabilised
if current_color.is_some() && attr.value.contains("currentColor") {
let value = attr
.value
.replace("currentColor", current_color.as_ref().unwrap());
encode_quoted_attribute_to_string(&value, writer);
} else {
encode_quoted_attribute_to_string(&attr.value, writer);
}
writer.push('"');
}
if !has_children {
writer.push_str(" /");
}
writer.push('>');
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
if has_children {
for &child_id in &self.children {
self.tree()[child_id].write_outer_html_in_style(writer, opts, nesting + 1);
}
if matches!(style, OutputStyle::Pretty) {
for _ in 0..nesting {
writer.push_str(INDENT);
}
}
writer.push_str("</");
writer.push_str(&data.name.local);
writer.push('>');
if matches!(style, OutputStyle::Pretty) {
writer.push('\n');
}
}
}
}
}
}