1use crate::os_lib::dom::{Node, NodeType, COMMENT_TAG, DOCTYPE_TAG, NS_ATTR};
11use alloc::string::{String, ToString};
12use alloc::vec::Vec;
13
14pub fn is_void_element(name: &str) -> bool {
16 matches!(
17 name,
18 "area" | "base" | "basefont" | "bgsound" | "br" | "col" | "embed" | "frame" | "hr" | "img" | "input" | "keygen" | "link" | "meta" | "param" | "source" | "track" | "wbr"
19 )
20}
21
22pub fn is_raw_text_element(name: &str, scripting: bool) -> bool {
24 matches!(name, "style" | "script" | "xmp" | "iframe" | "noembed" | "noframes" | "plaintext") || (scripting && name == "noscript")
25}
26
27pub fn escape_text(s: &str, out: &mut String) {
29 for c in s.chars() {
30 match c {
31 '&' => out.push_str("&"),
32 '\u{a0}' => out.push_str(" "),
33 '<' => out.push_str("<"),
34 '>' => out.push_str(">"),
35 c => out.push(c),
36 }
37 }
38}
39
40pub fn escape_attr_value(s: &str, quote: Option<char>, out: &mut String) {
42 for c in s.chars() {
43 match c {
44 '&' => out.push_str("&"),
45 '\u{a0}' => out.push_str(" "),
46 '<' => out.push_str("<"),
47 '>' => out.push_str(">"),
48 '"' if quote == Some('"') => out.push_str("""),
49 '\'' if quote == Some('\'') => out.push_str("'"),
50 c => out.push(c),
51 }
52 }
53}
54
55fn push_doctype(name: &str, out: &mut String) {
56 out.push_str("<!DOCTYPE ");
57 out.push_str(name);
58 out.push('>');
59}
60
61fn push_start_tag(node_tag: &str, attrs: &alloc::collections::BTreeMap<String, String>, out: &mut String) {
62 out.push('<');
63 out.push_str(node_tag);
64 for (k, v) in attrs {
65 if k == NS_ATTR || (k.starts_with('#') && k != "#") {
66 continue;
67 }
68 out.push(' ');
69 out.push_str(k);
70 out.push_str("=\"");
71 escape_attr_value(v, Some('"'), out);
72 out.push('"');
73 }
74 out.push('>');
75}
76
77enum Frame<'a> {
78 Node(&'a Node),
79 Close(&'a str),
80}
81
82pub fn serialize_children(node: &Node, scripting: bool) -> String {
84 let mut out = String::new();
85 serialize_into(node, true, scripting, &mut out);
86 out
87}
88
89pub fn serialize_outer(node: &Node, scripting: bool) -> String {
91 let mut out = String::new();
92 serialize_into(node, false, scripting, &mut out);
93 out
94}
95
96fn serialize_into(root: &Node, children_only: bool, scripting: bool, out: &mut String) {
97 let mut stack: Vec<Frame> = Vec::new();
98 if children_only {
99 for c in root.children.iter().rev() {
100 stack.push(Frame::Node(c));
101 }
102 } else {
103 stack.push(Frame::Node(root));
104 }
105 let mut raw_depth: Vec<bool> = Vec::new();
107 let root_raw = match &root.node_type {
108 NodeType::Element { tag_name, attributes, .. } if children_only => !attributes.contains_key(NS_ATTR) && is_raw_text_element(tag_name, scripting),
109 _ => false,
110 };
111 raw_depth.push(root_raw);
112 while let Some(f) = stack.pop() {
113 match f {
114 Frame::Close(name) => {
115 raw_depth.pop();
116 out.push_str("</");
117 out.push_str(name);
118 out.push('>');
119 }
120 Frame::Node(n) => match &n.node_type {
121 NodeType::Text(t) => {
122 if raw_depth.last().copied().unwrap_or(false) {
123 out.push_str(t);
124 } else {
125 escape_text(t, out);
126 }
127 }
128 NodeType::Element { tag_name, attributes, .. } => {
129 if tag_name == COMMENT_TAG {
130 out.push_str("<!--");
131 out.push_str(attributes.get("data").map(String::as_str).unwrap_or(""));
132 out.push_str("-->");
133 } else if tag_name == DOCTYPE_TAG {
134 push_doctype(attributes.get("name").map(String::as_str).unwrap_or(""), out);
135 } else if tag_name == "#document" || tag_name == "#document-fragment" {
136 for c in n.children.iter().rev() {
137 stack.push(Frame::Node(c));
138 }
139 } else {
140 let foreign = attributes.contains_key(NS_ATTR);
141 push_start_tag(tag_name, attributes, out);
142 if !foreign && is_void_element(tag_name) {
143 continue;
144 }
145 raw_depth.push(!foreign && is_raw_text_element(tag_name, scripting));
146 stack.push(Frame::Close(tag_name));
147 for c in n.children.iter().rev() {
148 stack.push(Frame::Node(c));
149 }
150 }
151 }
152 },
153 }
154 }
155}
156
157#[derive(Debug, Clone, PartialEq)]
163pub enum SerToken {
164 Doctype { name: String, public_id: Option<String>, system_id: Option<String> },
165 StartTag { name: String, attrs: Vec<(String, String)> },
166 EmptyTag { name: String, attrs: Vec<(String, String)> },
167 EndTag { name: String },
168 Characters(String),
169 SpaceCharacters(String),
170 Comment(String),
171}
172
173#[derive(Debug, Clone)]
175pub struct SerializeOptions {
176 pub quote_attr_values: bool,
178 pub quote_char: char,
179 pub use_best_quote_char: bool,
181 pub omit_optional_tags: bool,
182 pub minimize_boolean_attributes: bool,
183 pub use_trailing_solidus: bool,
184 pub space_before_trailing_solidus: bool,
185 pub escape_rcdata: bool,
187 pub alphabetical_attributes: bool,
188 pub inject_meta_charset: bool,
189 pub strip_whitespace: bool,
190 pub scripting: bool,
191 pub encoding: Option<String>,
193}
194
195impl Default for SerializeOptions {
196 fn default() -> Self {
197 SerializeOptions {
198 quote_attr_values: false,
199 quote_char: '"',
200 use_best_quote_char: true,
201 omit_optional_tags: true,
202 minimize_boolean_attributes: true,
203 use_trailing_solidus: false,
204 space_before_trailing_solidus: true,
205 escape_rcdata: false,
206 alphabetical_attributes: false,
207 inject_meta_charset: true,
208 strip_whitespace: false,
209 scripting: true,
210 encoding: None,
211 }
212 }
213}
214
215fn is_space_char(c: char) -> bool {
216 matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' ')
217}
218
219fn is_boolean_attribute(tag: &str, attr: &str) -> bool {
220 if matches!(attr, "irrelevant" | "itemscope") {
221 return true;
222 }
223 let list: &[&str] = match tag {
224 "style" => &["scoped"],
225 "img" => &["ismap"],
226 "audio" | "video" => &["autoplay", "controls"],
227 "script" => &["defer", "async"],
228 "details" => &["open"],
229 "datagrid" => &["multiple", "disabled"],
230 "command" => &["hidden", "disabled", "checked", "default"],
231 "hr" => &["noshade"],
232 "menu" => &["autosubmit"],
233 "fieldset" | "optgroup" | "output" => &["disabled", "readonly"],
234 "option" => &["disabled", "readonly", "selected"],
235 "button" => &["disabled", "autofocus"],
236 "input" => &["disabled", "readonly", "required", "autofocus", "checked", "ismap"],
237 "select" => &["disabled", "readonly", "autofocus", "multiple"],
238 "iframe" => &["seamless"],
239 _ => &[],
240 };
241 list.contains(&attr)
242}
243
244fn split_text(data: &str, out: &mut Vec<SerToken>) {
245 let chars: Vec<char> = data.chars().collect();
246 let first = chars.iter().position(|&c| !is_space_char(c));
247 let Some(first) = first else {
248 if !chars.is_empty() {
249 out.push(SerToken::SpaceCharacters(data.to_string()));
250 }
251 return;
252 };
253 let last = chars.iter().rposition(|&c| !is_space_char(c)).unwrap_or(first);
254 if first > 0 {
255 out.push(SerToken::SpaceCharacters(chars.iter().take(first).collect()));
256 }
257 out.push(SerToken::Characters(chars.iter().skip(first).take(last + 1 - first).collect()));
258 if last + 1 < chars.len() {
259 out.push(SerToken::SpaceCharacters(chars.iter().skip(last + 1).collect()));
260 }
261}
262
263fn inject_meta(tokens: Vec<SerToken>, enc: &str) -> Vec<SerToken> {
264 let mut out: Vec<SerToken> = Vec::new();
265 let mut in_head = false;
266 let mut meta_found = false;
267 let mut pending: Vec<SerToken> = Vec::new();
268 let meta = |enc: &str| SerToken::EmptyTag { name: "meta".to_string(), attrs: alloc::vec![("charset".to_string(), enc.to_string())] };
269 for mut token in tokens {
270 match &mut token {
271 SerToken::StartTag { name, .. } if name.eq_ignore_ascii_case("head") => in_head = true,
272 SerToken::EmptyTag { name, attrs } => {
273 if name.eq_ignore_ascii_case("meta") {
274 let mut has_http_equiv = false;
275 let mut replaced = false;
276 for (k, v) in attrs.iter_mut() {
277 if k.eq_ignore_ascii_case("charset") {
278 *v = enc.to_string();
279 meta_found = true;
280 replaced = true;
281 break;
282 } else if k == "http-equiv" && v.eq_ignore_ascii_case("content-type") {
283 has_http_equiv = true;
284 }
285 }
286 if !replaced && has_http_equiv {
287 if let Some((_, v)) = attrs.iter_mut().find(|(k, _)| k == "content") {
288 *v = alloc::format!("text/html; charset={}", enc);
289 meta_found = true;
290 }
291 }
292 } else if name.eq_ignore_ascii_case("head") && !meta_found {
293 out.push(SerToken::StartTag { name: "head".to_string(), attrs: attrs.clone() });
294 out.push(meta(enc));
295 out.push(SerToken::EndTag { name: "head".to_string() });
296 meta_found = true;
297 continue;
298 }
299 }
300 SerToken::EndTag { name } if name.eq_ignore_ascii_case("head") && !pending.is_empty() => {
301 out.push(pending.remove(0));
302 if !meta_found {
303 out.push(meta(enc));
304 }
305 out.append(&mut pending);
306 meta_found = true;
307 in_head = false;
308 }
309 _ => {}
310 }
311 if in_head {
312 pending.push(token);
313 } else {
314 out.push(token);
315 }
316 }
317 out.append(&mut pending);
318 out
319}
320
321fn strip_ws(tokens: Vec<SerToken>, scripting: bool) -> Vec<SerToken> {
322 let mut out = Vec::new();
323 let mut preserve = 0usize;
324 for token in tokens {
325 match token {
326 SerToken::StartTag { ref name, .. } if preserve > 0 || name == "pre" || name == "textarea" || is_raw_text_element(name, scripting) => {
327 preserve += 1;
328 out.push(token);
329 }
330 SerToken::EndTag { .. } if preserve > 0 => {
331 preserve -= 1;
332 out.push(token);
333 }
334 SerToken::SpaceCharacters(ref d) if preserve == 0 && !d.is_empty() => out.push(SerToken::SpaceCharacters(" ".to_string())),
335 SerToken::Characters(d) if preserve == 0 => {
336 let mut s = String::new();
337 let mut prev_space = false;
338 for c in d.chars() {
339 if is_space_char(c) {
340 if !prev_space {
341 s.push(' ');
342 }
343 prev_space = true;
344 } else {
345 s.push(c);
346 prev_space = false;
347 }
348 }
349 out.push(SerToken::Characters(s));
350 }
351 t => out.push(t),
352 }
353 }
354 out
355}
356
357#[derive(Clone, Copy, PartialEq)]
358enum Kind {
359 Start,
360 Empty,
361 End,
362 Space,
363 Comment,
364 Other,
365 None,
366}
367
368fn kind_name(t: Option<&SerToken>) -> (Kind, &str) {
369 match t {
370 Some(SerToken::StartTag { name, .. }) => (Kind::Start, name.as_str()),
371 Some(SerToken::EmptyTag { name, .. }) => (Kind::Empty, name.as_str()),
372 Some(SerToken::EndTag { name }) => (Kind::End, name.as_str()),
373 Some(SerToken::SpaceCharacters(_)) => (Kind::Space, ""),
374 Some(SerToken::Comment(_)) => (Kind::Comment, ""),
375 Some(_) => (Kind::Other, ""),
376 None => (Kind::None, ""),
377 }
378}
379
380fn is_optional_start(tag: &str, prev: Option<&SerToken>, next: Option<&SerToken>) -> bool {
381 let (k, n) = kind_name(next);
382 let (pk, pn) = kind_name(prev);
383 match tag {
384 "html" => !matches!(k, Kind::Comment | Kind::Space),
385 "head" => match k {
386 Kind::Start | Kind::Empty => true,
387 Kind::End => n == "head",
388 _ => false,
389 },
390 "body" => match k {
391 Kind::Comment | Kind::Space => false,
392 Kind::Start => !matches!(n, "script" | "style"),
393 _ => true,
394 },
395 "colgroup" => matches!(k, Kind::Start | Kind::Empty) && n == "col",
396 "tbody" => k == Kind::Start && n == "tr" && !(pk == Kind::End && matches!(pn, "tbody" | "thead" | "tfoot")),
397 _ => false,
398 }
399}
400
401fn is_optional_end(tag: &str, next: Option<&SerToken>) -> bool {
402 let (k, n) = kind_name(next);
403 let end_or_none = matches!(k, Kind::End | Kind::None);
404 match tag {
405 "html" | "head" | "body" => !matches!(k, Kind::Comment | Kind::Space),
406 "li" | "optgroup" | "tr" => {
407 if k == Kind::Start {
408 n == tag
409 } else {
410 end_or_none
411 }
412 }
413 "dt" | "dd" => {
414 if k == Kind::Start {
415 matches!(n, "dt" | "dd")
416 } else if tag == "dd" {
417 end_or_none
418 } else {
419 false
420 }
421 }
422 "p" => {
423 if matches!(k, Kind::Start | Kind::Empty) {
424 matches!(
425 n,
426 "address" | "article" | "aside" | "blockquote" | "datagrid" | "dialog" | "dir" | "div" | "dl" | "fieldset" | "footer" | "form" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "header" | "hr" | "menu" | "nav" | "ol" | "p" | "pre" | "section" | "table" | "ul"
427 )
428 } else {
429 end_or_none
430 }
431 }
432 "option" => {
433 if k == Kind::Start {
434 matches!(n, "option" | "optgroup")
435 } else {
436 end_or_none
437 }
438 }
439 "rt" | "rp" => {
440 if k == Kind::Start {
441 matches!(n, "rt" | "rp")
442 } else {
443 end_or_none
444 }
445 }
446 "colgroup" => match k {
447 Kind::Comment | Kind::Space => false,
448 Kind::Start => n != "colgroup",
449 _ => true,
450 },
451 "thead" | "tbody" => {
452 if k == Kind::Start {
453 matches!(n, "tbody" | "tfoot")
454 } else if tag == "tbody" {
455 end_or_none
456 } else {
457 false
458 }
459 }
460 "tfoot" => {
461 if k == Kind::Start {
462 n == "tbody"
463 } else {
464 end_or_none
465 }
466 }
467 "td" | "th" => {
468 if k == Kind::Start {
469 matches!(n, "td" | "th")
470 } else {
471 end_or_none
472 }
473 }
474 _ => false,
475 }
476}
477
478fn omit_optional(tokens: Vec<SerToken>) -> Vec<SerToken> {
479 let mut out = Vec::new();
480 for i in 0..tokens.len() {
481 let next = tokens.get(i + 1);
482 let Some(token) = tokens.get(i) else { break };
483 match token {
484 SerToken::StartTag { name, attrs } if attrs.is_empty() && is_optional_start(name, i.checked_sub(1).and_then(|j| tokens.get(j)), next) => {}
485 SerToken::EndTag { name } if is_optional_end(name, next) => {}
486 t => out.push(t.clone()),
487 }
488 }
489 out
490}
491
492fn push_attrs(name: &str, attrs: &[(String, String)], opts: &SerializeOptions, out: &mut String) {
493 let mut list: Vec<&(String, String)> = attrs.iter().collect();
494 if opts.alphabetical_attributes {
495 list.sort_by(|a, b| a.0.cmp(&b.0));
496 }
497 for (k, v) in list {
498 out.push(' ');
499 out.push_str(k);
500 if opts.minimize_boolean_attributes && is_boolean_attribute(name, k) {
501 continue;
502 }
503 out.push('=');
504 let quote = opts.quote_attr_values || v.is_empty() || v.chars().any(|c| is_space_char(c) || matches!(c, '"' | '\'' | '=' | '>' | '`'));
505 if quote {
506 let mut q = opts.quote_char;
507 if opts.use_best_quote_char {
508 if v.contains('\'') && !v.contains('"') {
509 q = '"';
510 } else if v.contains('"') && !v.contains('\'') {
511 q = '\'';
512 }
513 }
514 out.push(q);
515 escape_attr_value(v, Some(q), out);
516 out.push(q);
517 } else {
518 escape_attr_value(v, None, out);
519 }
520 }
521}
522
523pub fn serialize_tokens(tokens: &[SerToken], opts: &SerializeOptions) -> String {
525 let mut toks: Vec<SerToken> = Vec::new();
527 for t in tokens {
528 match t {
529 SerToken::Characters(d) => split_text(d, &mut toks),
530 t => toks.push(t.clone()),
531 }
532 }
533 if opts.inject_meta_charset {
534 if let Some(enc) = &opts.encoding {
535 toks = inject_meta(toks, enc);
536 }
537 }
538 if opts.strip_whitespace {
539 toks = strip_ws(toks, opts.scripting);
540 }
541 if opts.omit_optional_tags {
542 toks = omit_optional(toks);
543 }
544 let mut out = String::new();
545 let mut in_cdata = false;
546 for t in &toks {
547 match t {
548 SerToken::Doctype { name, public_id, system_id } => {
549 out.push_str("<!DOCTYPE ");
550 out.push_str(name);
551 let pub_nonempty = public_id.as_deref().is_some_and(|s| !s.is_empty());
552 let sys_nonempty = system_id.as_deref().is_some_and(|s| !s.is_empty());
553 if pub_nonempty {
554 out.push_str(" PUBLIC \"");
555 out.push_str(public_id.as_deref().unwrap_or(""));
556 out.push('"');
557 } else if sys_nonempty {
558 out.push_str(" SYSTEM");
559 }
560 if let Some(s) = system_id.as_deref().filter(|s| !s.is_empty()) {
561 let q = if s.contains('"') { '\'' } else { '"' };
562 out.push(' ');
563 out.push(q);
564 out.push_str(s);
565 out.push(q);
566 }
567 out.push('>');
568 }
569 SerToken::SpaceCharacters(d) => out.push_str(d),
570 SerToken::Characters(d) => {
571 if in_cdata {
572 out.push_str(d);
573 } else {
574 escape_text(d, &mut out);
575 }
576 }
577 SerToken::StartTag { name, attrs } | SerToken::EmptyTag { name, attrs } => {
578 out.push('<');
579 out.push_str(name);
580 if is_raw_text_element(name, opts.scripting) && !opts.escape_rcdata {
581 in_cdata = true;
582 }
583 push_attrs(name, attrs, opts, &mut out);
584 if is_void_element(name) && opts.use_trailing_solidus {
585 out.push_str(if opts.space_before_trailing_solidus { " /" } else { "/" });
586 }
587 out.push('>');
588 }
589 SerToken::EndTag { name } => {
590 if is_raw_text_element(name, opts.scripting) {
591 in_cdata = false;
592 }
593 out.push_str("</");
594 out.push_str(name);
595 out.push('>');
596 }
597 SerToken::Comment(d) => {
598 out.push_str("<!--");
599 out.push_str(d);
600 out.push_str("-->");
601 }
602 }
603 }
604 out
605}