Skip to main content

takumi_core/html/
mod.rs

1//! Parse HTML markup into a takumi [`Node`] tree.
2//!
3//! The `style`, `tw` (Tailwind classes), `class`, `id`, `dir`, and `lang` attributes carry
4//! over. Elements get Chromium's default styles unless [`FromHtmlOptions`] sets other presets.
5//! `<style>` and `<script>` elements are dropped, so pass CSS to the renderer as a stylesheet.
6//! [`parse_html`] returns that CSS, along with each `<link rel="stylesheet">` for the host to
7//! fetch and the `<base>` URL to resolve it against.
8//!
9//! In the `takumi` crate, enable the `from-html` feature and call `takumi::from_html`.
10//!
11//! ```rust
12//! use takumi_core::html::{FromHtml, FromHtmlOptions};
13//! use takumi_core::layout::node::Node;
14//!
15//! # fn main() -> Result<(), takumi_core::html::HtmlError> {
16//! let node = Node::from_html("<div style=\"color:red\">Hi</div>", FromHtmlOptions::default())?;
17//! # Ok(())
18//! # }
19//! ```
20#![deny(clippy::indexing_slicing, clippy::string_slice)]
21#![cfg_attr(test, allow(clippy::indexing_slicing, clippy::string_slice))]
22pub(crate) mod dom;
23mod entities;
24pub(crate) mod markup;
25mod named_references;
26
27use std::{
28  borrow::Cow,
29  cell::{Cell, RefCell},
30  collections::{BTreeMap, HashMap},
31  str::FromStr,
32  sync::{Arc, LazyLock},
33};
34
35#[cfg(feature = "html-svg-nodes")]
36use crate::resources::image::SvgSource;
37use crate::{
38  form_control::InputType,
39  layout::node::{
40    ImageData, ImageSourceInput, MAXIMUM_DOM_TREE_DEPTH, Names, Node, NodeKind, size_attribute,
41  },
42  resources::{image::ImageSource, image_buffer::ImageBuffer},
43  style::{Direction, FromCssStr, Lang, Length, Style, StyleDeclarationBlock, TailwindValues},
44};
45use typed_builder::TypedBuilder;
46
47#[cfg(feature = "html-svg-nodes")]
48use self::dom::{Attribute, AttributeNamespace};
49use self::dom::{Namespace, NodeData, NodeRef};
50
51/// Tags whose subtree never reaches the tree, unlike the `display: none` presets.
52const UNRENDERED_TAGS: [&str; 5] = ["head", "meta", "link", "style", "script"];
53
54/// `dir=auto`, which a `bdi` without a valid `dir` also has. Approximate: `plaintext` takes each
55/// paragraph's direction from its first strong character, where `dir=auto` takes one direction for
56/// the element and also sets its `direction` and `:dir()`, which here keep the parent's.
57const AUTO_DIRECTION: &str = "unicode-bidi:plaintext";
58
59const DEFAULT_PRESETS: &[(&str, &str)] = &[
60  ("html", "display:block"),
61  ("head", "display:none"),
62  ("meta", "display:none"),
63  ("title", "display:none"),
64  ("link", "display:none"),
65  ("style", "display:none"),
66  ("script", "display:none"),
67  ("noscript", "display:none"),
68  ("datalist", "display:none"),
69  ("template", "display:none"),
70  ("body", "margin:8px;display:block"),
71  ("p", "margin-top:1em;margin-bottom:1em;display:block"),
72  (
73    "blockquote",
74    "margin-top:1em;margin-bottom:1em;margin-left:40px;margin-right:40px;display:block",
75  ),
76  (
77    "figure",
78    "margin-top:1em;margin-bottom:1em;margin-left:40px;margin-right:40px;display:block",
79  ),
80  ("figcaption", "display:block"),
81  ("address", "font-style:italic;display:block"),
82  ("article", "display:block"),
83  ("aside", "display:block"),
84  ("footer", "display:block"),
85  ("header", "display:block"),
86  ("hgroup", "display:block"),
87  ("main", "display:block"),
88  ("nav", "display:block"),
89  ("section", "display:block"),
90  ("center", "text-align:center;display:block"),
91  (
92    "hr",
93    "margin-top:0.5em;margin-bottom:0.5em;margin-left:auto;margin-right:auto;border-width:1px;display:block",
94  ),
95  (
96    "ul",
97    "margin-top:1em;margin-bottom:1em;padding-inline-start:40px;display:block;list-style-type:disc",
98  ),
99  (
100    "ol",
101    "margin-top:1em;margin-bottom:1em;padding-inline-start:40px;display:block;list-style-type:decimal",
102  ),
103  (
104    "menu",
105    "margin-top:1em;margin-bottom:1em;padding-inline-start:40px;display:block;list-style-type:disc",
106  ),
107  ("li", "display:list-item"),
108  ("dl", "margin-top:1em;margin-bottom:1em;display:block"),
109  ("dt", "display:block"),
110  ("dd", "margin-left:40px;display:block"),
111  ("form", "display:block"),
112  (
113    "fieldset",
114    "margin-left:2px;margin-right:2px;padding-top:0.35em;padding-right:0.75em;padding-bottom:0.625em;padding-left:0.75em;border-width:2px;display:block",
115  ),
116  ("legend", "padding-left:2px;padding-right:2px;display:block"),
117  ("details", "display:block"),
118  ("summary", "display:block"),
119  ("search", "display:block"),
120  (
121    "h1",
122    "font-size:2em;margin-top:0.67em;margin-bottom:0.67em;margin-left:0;margin-right:0;font-weight:bold;display:block",
123  ),
124  (
125    "h2",
126    "font-size:1.5em;margin-top:0.83em;margin-bottom:0.83em;margin-left:0;margin-right:0;font-weight:bold;display:block",
127  ),
128  (
129    "h3",
130    "font-size:1.17em;margin-top:1em;margin-bottom:1em;margin-left:0;margin-right:0;font-weight:bold;display:block",
131  ),
132  (
133    "h4",
134    "margin-top:1.33em;margin-bottom:1.33em;margin-left:0;margin-right:0;font-weight:bold;display:block",
135  ),
136  (
137    "h5",
138    "font-size:0.83em;margin-top:1.67em;margin-bottom:1.67em;margin-left:0;margin-right:0;font-weight:bold;display:block",
139  ),
140  (
141    "h6",
142    "font-size:0.67em;margin-top:2.33em;margin-bottom:2.33em;margin-left:0;margin-right:0;font-weight:bold;display:block",
143  ),
144  ("bdi", "unicode-bidi:isolate"),
145  ("bdo", "unicode-bidi:isolate-override"),
146  ("u", "text-decoration:underline"),
147  ("ins", "text-decoration:underline"),
148  ("strong", "font-weight:bolder"),
149  ("b", "font-weight:bolder"),
150  ("i", "font-style:italic"),
151  ("em", "font-style:italic"),
152  ("cite", "font-style:italic"),
153  ("dfn", "font-style:italic"),
154  ("code", "font-family:monospace"),
155  ("kbd", "font-family:monospace"),
156  ("samp", "font-family:monospace"),
157  (
158    "pre",
159    "font-family:monospace;white-space:pre;margin:1em 0;display:block",
160  ),
161  ("mark", "background-color:yellow;color:black"),
162  ("big", "font-size:larger"),
163  ("small", "font-size:smaller"),
164  ("s", "text-decoration:line-through"),
165  ("del", "text-decoration:line-through"),
166  ("sub", "font-size:smaller;vertical-align:sub"),
167  ("sup", "font-size:smaller;vertical-align:super"),
168  ("div", "display:block"),
169  (
170    "table",
171    "display:table;box-sizing:border-box;border-spacing:2px",
172  ),
173  (
174    "thead",
175    "display:table-header-group;vertical-align:middle;break-inside:avoid",
176  ),
177  ("tbody", "display:table-row-group;vertical-align:middle"),
178  (
179    "tfoot",
180    "display:table-footer-group;vertical-align:middle;break-inside:avoid",
181  ),
182  ("tr", "display:table-row;vertical-align:inherit"),
183  (
184    "td",
185    "display:table-cell;padding:1px;vertical-align:inherit",
186  ),
187  (
188    "th",
189    "display:table-cell;padding:1px;vertical-align:inherit;font-weight:bold;text-align:center",
190  ),
191  ("caption", "display:table-caption;text-align:center"),
192  ("colgroup", "display:table-column-group"),
193  ("col", "display:table-column"),
194  // `html.css` for a text field, which `input_preset` picks by the element's `type`.
195  // Approximate: Blink's `-webkit-small-control` resolves to Arial, which a document rarely loads,
196  // so this names `system-ui`, and a document that loads Arial still draws its fields without it.
197  (
198    "input",
199    "margin:0;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:13.333333px;font-family:system-ui;color:#000;letter-spacing:0;word-spacing:0;line-height:normal;text-transform:none;text-indent:0;text-shadow:none;display:inline-block;text-align:start;box-sizing:content-box;padding:1px 2px;border:2px inset #767676;background-color:#fff",
200  ),
201  ("input[type=search]", "box-sizing:border-box"),
202  // `html.css` for `<button>`, with Chromium's light `ButtonFace`, `ButtonBorder`, and `ButtonText`.
203  (
204    "button",
205    "margin:0;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:13.333333px;font-family:system-ui;color:#000;letter-spacing:0;word-spacing:0;line-height:normal;text-transform:none;text-indent:0;text-shadow:none;display:inline-block;text-align:center;box-sizing:border-box;padding:1px 6px;border:2px outset #767676;background-color:#efefef",
206  ),
207  (
208    "button:disabled",
209    "color:rgba(16,16,16,0.3);background-color:rgba(239,239,239,0.3);border-color:rgba(118,118,118,0.3)",
210  ),
211  ("input[type=tel]", "direction:ltr"),
212  (
213    "input:disabled",
214    "background-color:rgba(239,239,239,0.3);color:#545454;border-color:rgba(118,118,118,0.3)",
215  ),
216  // HTML's rendering section hides a hidden input, which Blink gives no box.
217  ("input[type=hidden]", "display:none"),
218  (
219    "textarea",
220    "margin:0;font-style:normal;font-variant:normal;font-weight:normal;font-stretch:normal;font-size:13.333333px;font-family:monospace;color:#000;letter-spacing:0;word-spacing:0;line-height:normal;text-transform:none;text-indent:0;text-shadow:none;display:inline-block;text-align:start;box-sizing:content-box;white-space:pre-wrap;overflow-wrap:break-word;border:1px solid #767676;background-color:#fff;padding:2px",
221  ),
222  (
223    "textarea:disabled",
224    "background-color:rgba(239,239,239,0.3);color:#545454;border-color:rgba(118,118,118,0.3)",
225  ),
226  // Blink's `HTMLTextAreaElement::CollectStyleForPresentationAttribute` for `wrap="off"`.
227  ("textarea[wrap=off]", "white-space:pre;overflow-wrap:normal"),
228];
229
230static DEFAULT_STYLE_PRESETS: LazyLock<HashMap<Box<str>, Arc<Style>>> = LazyLock::new(|| {
231  DEFAULT_PRESETS
232    .iter()
233    .map(|&(tag, css)| {
234      (
235        tag.into(),
236        Arc::new(Style::from(StyleDeclarationBlock::parse_loosy(css))),
237      )
238    })
239    .collect()
240});
241
242/// Errors raised while parsing HTML into a node tree.
243#[derive(Debug, thiserror::Error)]
244#[non_exhaustive]
245pub enum HtmlError {
246  /// Element nesting exceeded [`FromHtmlOptions::max_depth`].
247  #[error("element nesting exceeded the maximum depth of {0}")]
248  MaxDepthExceeded(usize),
249}
250
251/// Per-tag default styles applied at the lowest cascade layer.
252///
253/// [`StylePresets::chromium`] is the built-in table, borrowed from a shared
254/// static at no allocation cost. Supply your own with [`From`]; disable presets
255/// with [`StylePresets::empty`].
256#[derive(Debug, Clone)]
257pub struct StylePresets(Cow<'static, HashMap<Box<str>, Arc<Style>>>);
258
259impl StylePresets {
260  /// Built-in Chromium element presets.
261  pub fn chromium() -> Self {
262    Self(Cow::Borrowed(&DEFAULT_STYLE_PRESETS))
263  }
264
265  /// Empty presets — every element keeps its bare style.
266  pub fn empty() -> Self {
267    Self(Cow::Owned(HashMap::new()))
268  }
269
270  /// The preset of `tag`, shared until an element changes its copy.
271  fn get(&self, tag: &str) -> Option<&Arc<Style>> {
272    self.0.get(tag)
273  }
274}
275
276impl Default for StylePresets {
277  fn default() -> Self {
278    Self::chromium()
279  }
280}
281
282impl From<HashMap<Box<str>, Style>> for StylePresets {
283  fn from(presets: HashMap<Box<str>, Style>) -> Self {
284    Self(Cow::Owned(
285      presets
286        .into_iter()
287        .map(|(tag, style)| (tag, Arc::new(style)))
288        .collect(),
289    ))
290  }
291}
292
293/// Options for [`from_html`]. Construct via [`FromHtmlOptions::builder`], or
294/// [`default`](Self::default) for the defaults.
295#[derive(Debug, Clone, TypedBuilder)]
296#[non_exhaustive]
297pub struct FromHtmlOptions {
298  /// Default element styles. Use [`StylePresets::empty`] to disable.
299  #[builder(default)]
300  pub(crate) presets: StylePresets,
301  /// Attribute name carrying Tailwind classes. `None` means `tw`.
302  #[builder(default, setter(into, strip_option))]
303  pub(crate) tailwind_property: Option<Box<str>>,
304  /// Maximum element nesting depth before [`HtmlError::MaxDepthExceeded`].
305  /// Defaults to [`MAXIMUM_DOM_TREE_DEPTH`].
306  #[builder(default = MAXIMUM_DOM_TREE_DEPTH)]
307  pub(crate) max_depth: usize,
308  /// Parses any source as a whole document, as a browser opens an HTML file. Off by default.
309  #[builder(default)]
310  pub(crate) document: bool,
311  /// Parses the source as a fragment even when it opens with a doctype or `<html>`, dropping the
312  /// `html`, `head`, and `body` tags as Chromium does when it inserts a header template into an
313  /// element. Ignored when `document` is set.
314  #[builder(default)]
315  pub(crate) fragment: bool,
316}
317
318impl Default for FromHtmlOptions {
319  fn default() -> Self {
320    Self::builder().build()
321  }
322}
323
324/// Parse HTML markup into a node tree.
325///
326/// `tw`, `style`, `class`, `id`, `dir`, and `lang` attributes become the
327/// corresponding node styling and metadata; `<style>` blocks and other
328/// unrendered elements are dropped, and [`parse_html`] returns the CSS they hold. A single root element is returned as-is; multiple
329/// roots are wrapped in a full-size container.
330///
331/// A source that starts with a doctype or an `<html>` element is parsed as a
332/// document, so the tree has an `<html>` root along with `<head>` and `<body>`,
333/// as a browser builds them. Anything else is parsed as a fragment and gains no
334/// wrappers of its own.
335///
336/// The parser covers the tokenizer but only part of the tree builder's error recovery: it
337/// closes `p`, `li`, `dt`, `dd`, `option`, and table rows and cells implicitly, but does not
338/// reconstruct misnested formatting elements or foster-parent table content.
339pub fn from_html(source: &str, options: FromHtmlOptions) -> Result<Node, HtmlError> {
340  parse_html(source, options).map(|parsed| parsed.node)
341}
342
343/// A node tree, the CSS of its `<style>` elements, and the style sheets it links.
344#[derive(Debug, Clone)]
345pub struct ParsedHtml {
346  /// The node tree, as [`from_html`] returns it.
347  pub node: Node,
348  /// The [CSS](StyleElement::css) of each entry in [`styles`](Self::styles).
349  pub css: Vec<String>,
350  /// Each non-empty `<style>` element the preferred style sheet set keeps, in document order.
351  pub styles: Vec<StyleElement>,
352  /// Each `<link rel="stylesheet">` the preferred style sheet set keeps, in document order.
353  pub links: Vec<StyleSheetLink>,
354  /// The `href` of the first `<base>` element that has one, which relative URLs resolve against.
355  pub base_href: Option<String>,
356}
357
358impl ParsedHtml {
359  /// Each [`css`](Self::css) entry and the text `fetch` loads for each link, in document order.
360  pub fn css_with_links(
361    &self,
362    mut fetch: impl FnMut(&StyleSheetLink) -> Option<String>,
363  ) -> Vec<String> {
364    let mut links = self.links.iter().peekable();
365    let mut css = Vec::with_capacity(self.css.len() + self.links.len());
366
367    for index in 0..=self.css.len() {
368      while let Some(link) = links.next_if(|link| link.css_index == index) {
369        if let Some(text) = fetch(link) {
370          css.push(in_media(link.media.as_deref(), text));
371        }
372      }
373
374      if let Some(text) = self.css.get(index) {
375        css.push(text.clone());
376      }
377    }
378
379    css
380  }
381}
382
383/// A CSS `<style>` element outside `<svg>` and `<math>`.
384#[derive(Debug, Clone, PartialEq, Eq)]
385#[non_exhaustive]
386pub struct StyleElement {
387  /// The element's text.
388  pub text: String,
389  /// The `media` attribute, none when it is absent or empty.
390  pub media: Option<String>,
391}
392
393impl StyleElement {
394  /// The text, inside an `@media` rule when the element has a `media` attribute.
395  pub fn css(&self) -> String {
396    in_media(self.media.as_deref(), self.text.clone())
397  }
398}
399
400/// A `<link rel="stylesheet">`, which the document loads from `href`.
401#[derive(Debug, Clone, PartialEq, Eq)]
402#[non_exhaustive]
403pub struct StyleSheetLink {
404  /// The `href` as written, to resolve against [`ParsedHtml::base_href`] and the document's URL.
405  pub href: String,
406  /// The `media` attribute, none when it is absent or empty.
407  pub media: Option<String>,
408  /// How many [`ParsedHtml::css`] entries come before the link in document order.
409  pub css_index: usize,
410}
411
412/// Parse HTML markup into a node tree, its `<style>` elements, and the style sheets it links.
413pub fn parse_html(source: &str, options: FromHtmlOptions) -> Result<ParsedHtml, HtmlError> {
414  // Decoding drops a leading byte order mark: https://encoding.spec.whatwg.org/#decode
415  let source = source.strip_prefix('\u{feff}').unwrap_or(source);
416  let builder = NodeBuilder {
417    presets: &options.presets,
418    tw_property: options.tailwind_property.as_deref().unwrap_or("tw"),
419    max_depth: options.max_depth,
420    styles: RefCell::default(),
421    names: Names::default(),
422    disabling_fieldsets: Cell::new(0),
423  };
424  let dom = markup::parse(
425    source,
426    options.document || (!options.fragment && is_document(source)),
427  );
428  let mut nodes = Vec::new();
429
430  builder.build_nodes(dom.document(), 0, &mut nodes)?;
431
432  let mut parsed = ParsedHtml {
433    node: collapse(nodes),
434    css: Vec::new(),
435    styles: Vec::new(),
436    links: Vec::new(),
437    base_href: None,
438  };
439
440  parsed.read_style_sheets(dom.document());
441
442  Ok(parsed)
443}
444
445impl ParsedHtml {
446  /// Reads the `<style>`, `<link rel="stylesheet">`, and `<base>` elements under `document`,
447  /// keeping the style sheets Blink's `CSSStyleSheet::CanBeActivated` would.
448  fn read_style_sheets(&mut self, document: NodeRef<'_>) {
449    let mut sheets = Vec::new();
450    let mut preferred_set: Option<&str> = None;
451    let mut pending: Vec<_> = document.children().rev().collect();
452
453    while let Some(node) = pending.pop() {
454      let NodeData::Element { name, .. } = node.data() else {
455        continue;
456      };
457
458      if name.ns != Namespace::Html {
459        pending.extend(node.children().rev());
460        continue;
461      }
462
463      let sheet = match &*name.local {
464        "style" => style_element(node).map(DocumentStyleSheet::Inline),
465        "link" => stylesheet_href(node).map(|href| {
466          DocumentStyleSheet::Link(StyleSheetLink {
467            href: href.to_owned(),
468            media: media_attribute(node).map(str::to_owned),
469            css_index: 0,
470          })
471        }),
472        "base" => {
473          if self.base_href.is_none() {
474            self.base_href = node.attribute("href").map(str::to_owned);
475          }
476          None
477        }
478        "meta" => {
479          if node
480            .attribute("http-equiv")
481            .is_some_and(|equiv| equiv.eq_ignore_ascii_case("default-style"))
482          {
483            preferred_set =
484              preferred_set.or(node.attribute("content").filter(|name| !name.is_empty()));
485          }
486          None
487        }
488        _ => {
489          pending.extend(node.children().rev());
490          None
491        }
492      };
493
494      if let Some(sheet) = sheet {
495        let title = node.attribute("title").filter(|title| !title.is_empty());
496        let is_alternate = &*name.local == "link" && has_rel(node, "alternate");
497
498        if !is_alternate {
499          preferred_set = preferred_set.or(title);
500        }
501        sheets.push((sheet, title, is_alternate));
502      }
503    }
504
505    for (sheet, title, is_alternate) in sheets {
506      let can_be_activated = match title {
507        Some(title) => preferred_set == Some(title),
508        None => !is_alternate,
509      };
510
511      if !can_be_activated {
512        continue;
513      }
514
515      match sheet {
516        DocumentStyleSheet::Inline(style) if style.text.is_empty() => {}
517        DocumentStyleSheet::Inline(style) => {
518          self.css.push(style.css());
519          self.styles.push(style);
520        }
521        DocumentStyleSheet::Link(link) => self.links.push(StyleSheetLink {
522          css_index: self.css.len(),
523          ..link
524        }),
525      }
526    }
527  }
528}
529
530/// A style sheet an element holds or links, before the document picks the ones it applies.
531enum DocumentStyleSheet {
532  Inline(StyleElement),
533  Link(StyleSheetLink),
534}
535
536/// A `<style>` element with no type or `text/css`. An empty one still takes part in picking the
537/// preferred style sheet set, as in Blink.
538fn style_element(style: NodeRef<'_>) -> Option<StyleElement> {
539  if !is_css_type(style.attribute("type")) {
540    return None;
541  }
542
543  let text: String = style
544    .children()
545    .filter_map(|child| match child.data() {
546      NodeData::Text(text) => Some(&**text),
547      _ => None,
548    })
549    .collect();
550
551  Some(StyleElement {
552    text,
553    media: media_attribute(style).map(str::to_owned),
554  })
555}
556
557/// The `href` a `<link>` loads a style sheet from, as Blink's
558/// `LinkStyle::LoadStylesheetIfNeeded` gates it: a `stylesheet` relation, not `disabled`, and of
559/// no type or `text/css` apart from its parameters.
560fn stylesheet_href(link: NodeRef<'_>) -> Option<&str> {
561  let essence = link
562    .attribute("type")
563    .map(|kind| kind.split(';').next().unwrap_or_default().trim());
564
565  if !has_rel(link, "stylesheet") || link.attribute("disabled").is_some() || !is_css_type(essence) {
566    return None;
567  }
568
569  link
570    .attribute("href")
571    .filter(|href| !href.trim().is_empty())
572}
573
574/// Whether the element's `rel` attribute holds `token`, in any case.
575fn has_rel(element: NodeRef<'_>, token: &str) -> bool {
576  element.attribute("rel").is_some_and(|rel| {
577    rel
578      .split_ascii_whitespace()
579      .any(|word| word.eq_ignore_ascii_case(token))
580  })
581}
582
583/// Whether a `type` attribute names CSS: absent, empty, or `text/css` in any case.
584fn is_css_type(kind: Option<&str>) -> bool {
585  kind.is_none_or(|kind| kind.is_empty() || kind.eq_ignore_ascii_case("text/css"))
586}
587
588/// The trimmed `media` attribute, none when it is absent or empty.
589fn media_attribute(element: NodeRef<'_>) -> Option<&str> {
590  element
591    .attribute("media")
592    .map(str::trim)
593    .filter(|media| !media.is_empty())
594}
595
596/// `css` inside an `@media` rule for `media`, or as it is without one.
597fn in_media(media: Option<&str>, css: String) -> String {
598  match media {
599    Some(media) => format!("@media {media} {{{css}}}"),
600    None => css,
601  }
602}
603
604/// Whether the source opens with a doctype or an `<html>` tag, after white space and comments.
605fn is_document(source: &str) -> bool {
606  let mut rest = source.trim_start();
607
608  loop {
609    if rest
610      .get(..9)
611      .is_some_and(|prefix| prefix.eq_ignore_ascii_case("<!doctype"))
612    {
613      return true;
614    }
615
616    if rest.starts_with("<!--") {
617      let Some((_, after)) = rest.split_once("-->") else {
618        return false;
619      };
620      rest = after.trim_start();
621      continue;
622    }
623
624    return rest
625      .split_at_checked("<html".len())
626      .filter(|(prefix, _)| prefix.eq_ignore_ascii_case("<html"))
627      .is_some_and(|(_, after)| {
628        after.starts_with(['>', '/']) || after.starts_with(char::is_whitespace)
629      });
630  }
631}
632
633/// Adds [`Node::from_html`](FromHtml::from_html) when this crate is in scope.
634pub trait FromHtml: Sized {
635  /// Parse HTML markup into a node tree. See [`from_html`].
636  fn from_html(source: &str, options: FromHtmlOptions) -> Result<Self, HtmlError>;
637}
638
639impl FromHtml for Node {
640  fn from_html(source: &str, options: FromHtmlOptions) -> Result<Self, HtmlError> {
641    from_html(source, options)
642  }
643}
644
645fn is_whitespace_only_text(node: &Node) -> bool {
646  matches!(&node.kind, NodeKind::Text(data) if data.text.trim().is_empty())
647}
648
649/// Apply the root-collapse rule shared with the JS `fromHtml`.
650fn collapse(mut nodes: Vec<Node>) -> Node {
651  // Trim whitespace-only roots so a newline-wrapped single element stays one root.
652  while nodes.first().is_some_and(is_whitespace_only_text) {
653    nodes.remove(0);
654  }
655  while nodes.last().is_some_and(is_whitespace_only_text) {
656    nodes.pop();
657  }
658
659  match nodes.len() {
660    0 => Node::container([]),
661    1 => nodes.pop().unwrap_or_default(),
662    _ => Node::container(nodes).with_style(Style::from(StyleDeclarationBlock::parse_loosy(
663      "display:block;width:100%;height:100%",
664    ))),
665  }
666}
667
668/// Turns parsed DOM handles into nodes under one set of options.
669struct NodeBuilder<'a> {
670  presets: &'a StylePresets,
671  tw_property: &'a str,
672  max_depth: usize,
673  /// Parsed `style` attributes, by source text.
674  styles: RefCell<HashMap<Box<str>, Style>>,
675  /// The element and attribute names built so far.
676  names: Names,
677  /// How many `<fieldset disabled>` hold the element being built outside their first `<legend>`.
678  disabling_fieldsets: Cell<usize>,
679}
680
681impl NodeBuilder<'_> {
682  fn build_nodes(
683    &self,
684    handle: NodeRef<'_>,
685    depth: usize,
686    out: &mut Vec<Node>,
687  ) -> Result<(), HtmlError> {
688    match handle.data() {
689      NodeData::Comment(_) | NodeData::Doctype { .. } => {}
690      NodeData::Document => {
691        for child in handle.children() {
692          self.build_nodes(child, depth, out)?;
693        }
694      }
695      NodeData::Text(contents) => {
696        if !contents.is_empty() {
697          out.push(Node::text(contents.clone()));
698        }
699      }
700      NodeData::Element { name, .. } => {
701        if let Some(node) = self.build_element(handle, &name.local, depth)? {
702          out.push(node);
703        }
704      }
705    }
706
707    Ok(())
708  }
709
710  fn build_element(
711    &self,
712    handle: NodeRef<'_>,
713    tag: &str,
714    depth: usize,
715  ) -> Result<Option<Node>, HtmlError> {
716    if depth >= self.max_depth {
717      return Err(HtmlError::MaxDepthExceeded(self.max_depth));
718    }
719
720    let node = match tag {
721      "br" => Node::text("\n"),
722      "img" => match handle.attribute("src").filter(|src| !src.trim().is_empty()) {
723        Some(src) => Node::image(ImageData {
724          src: ImageSourceInput::Url(src.into()),
725          width: pixels(handle, tag, "width"),
726          height: pixels(handle, tag, "height"),
727        }),
728        // An `<img>` that represents nothing is a replaced element with natural dimensions of 0:
729        // https://html.spec.whatwg.org/multipage/rendering.html#images-3
730        None => Node::image(ImageData {
731          src: ImageSourceInput::Loaded(ImageSource::from(ImageBuffer::empty())),
732          width: pixels(handle, tag, "width"),
733          height: pixels(handle, tag, "height"),
734        }),
735      },
736      _ if UNRENDERED_TAGS.contains(&tag) => return Ok(None),
737      "svg" => Node::image(ImageData {
738        src: self.inline_svg(handle, depth)?,
739        width: pixels(handle, tag, "width"),
740        height: pixels(handle, tag, "height"),
741      }),
742      _ => match text_only_contents(handle) {
743        Some(text) => Node::text(text),
744        None => Node::container(self.build_children(handle, tag, depth)?),
745      },
746    };
747
748    Ok(Some(self.apply_metadata(node, handle, tag)))
749  }
750
751  fn build_children(
752    &self,
753    handle: NodeRef<'_>,
754    tag: &str,
755    depth: usize,
756  ) -> Result<Vec<Node>, HtmlError> {
757    let disables = tag == "fieldset" && handle.attribute("disabled").is_some();
758    let first_legend = handle.children().position(
759      |child| matches!(child.data(), NodeData::Element { name, .. } if &*name.local == "legend"),
760    );
761    let mut children = Vec::new();
762
763    if disables {
764      self.disabling_fieldsets.update(|count| count + 1);
765    }
766
767    for (index, child) in handle.children().enumerate() {
768      // HTML exempts the first `<legend>` of a disabled fieldset.
769      let exempts = disables && Some(index) == first_legend;
770
771      if exempts {
772        self.disabling_fieldsets.update(|count| count - 1);
773      }
774
775      let built = self.build_nodes(child, depth + 1, &mut children);
776
777      if exempts {
778        self.disabling_fieldsets.update(|count| count + 1);
779      }
780
781      built?;
782    }
783
784    if disables {
785      self.disabling_fieldsets.update(|count| count - 1);
786    }
787
788    Ok(children)
789  }
790
791  /// The presets of an `<input>`, `<textarea>`, or `<button>`, which `html.css` picks by its `type`
792  /// and whether it is disabled: those of a text field, a hidden input, a textarea, or a button.
793  /// Other input types take none yet.
794  fn form_control_preset(&self, handle: NodeRef<'_>, tag: &str) -> Option<Arc<Style>> {
795    let (keys, disabled_key): (&[&str], _) = if tag == "button" {
796      (&["button"], Some("button:disabled"))
797    } else if tag == "textarea" {
798      let wraps = !handle
799        .attribute("wrap")
800        .is_some_and(|wrap| wrap.eq_ignore_ascii_case("off"));
801
802      if wraps {
803        (&["textarea"], Some("textarea:disabled"))
804      } else {
805        (
806          &["textarea", "textarea[wrap=off]"],
807          Some("textarea:disabled"),
808        )
809      }
810    } else {
811      let input_type = InputType::parse(handle.attribute("type"));
812      let keys: &[&str] = match input_type {
813        InputType::Hidden => &["input[type=hidden]"],
814        InputType::Search => &["input", "input[type=search]"],
815        InputType::Tel => &["input", "input[type=tel]"],
816        _ if input_type.is_text_field() => &["input"],
817        _ => &[],
818      };
819
820      (keys, input_type.is_text_field().then_some("input:disabled"))
821    };
822    let is_disabled = self.disabling_fieldsets.get() > 0 || handle.attribute("disabled").is_some();
823    let mut presets = keys
824      .iter()
825      .copied()
826      .chain(disabled_key.filter(|_| is_disabled))
827      .filter_map(|key| self.presets.get(key));
828    let mut preset = presets.next()?.clone();
829
830    for extra in presets {
831      let preset = Arc::make_mut(&mut preset);
832
833      for declaration in extra.declarations.iter() {
834        preset.push(declaration.clone(), false);
835      }
836    }
837
838    Some(preset)
839  }
840
841  fn apply_metadata(&self, mut node: Node, handle: NodeRef<'_>, tag: &str) -> Node {
842    node = node.with_tag_name(self.names.get(tag));
843
844    let preset = if matches!(tag, "input" | "textarea" | "button") {
845      self.form_control_preset(handle, tag)
846    } else {
847      self.presets.get(tag).cloned()
848    };
849
850    if let Some(preset) = preset {
851      node = node.with_preset(preset);
852    }
853
854    let NodeData::Element { attrs, .. } = handle.data() else {
855      return node;
856    };
857
858    let mut attributes = BTreeMap::new();
859    let mut auto_direction = tag == "bdi";
860
861    for attr in attrs {
862      let name = &*attr.local;
863      let value = &*attr.value;
864
865      // Read Tailwind independently of reserved names so it can alias `class`
866      // without dropping the class name.
867      if name == self.tw_property
868        && let Ok(tw) = TailwindValues::from_str(value)
869      {
870        node = node.with_tw(tw);
871      }
872
873      match name {
874        "class" => node = node.with_class_name(value),
875        "id" => node = node.with_id(value),
876        "lang" => {
877          if let Ok(lang) = Lang::parse(value) {
878            node = node.with_lang(lang);
879          }
880        }
881        "dir" if value.eq_ignore_ascii_case("auto") => auto_direction = true,
882        "dir" => {
883          if let Ok(dir) = Direction::from_css_str(value) {
884            node = node.with_dir(dir);
885            auto_direction = false;
886          }
887        }
888        "style" => node = node.with_style(self.style(value)),
889        // Consumed into `ImageData`; re-emitted by serialization, so keep it out
890        // of the passthrough attributes to avoid duplicating on round-trip.
891        "src" if tag == "img" => {}
892        // Consumed above; keep out of the passthrough attributes.
893        _ if name == self.tw_property => {}
894        _ => {
895          attributes.insert(self.names.get(name), value.into());
896        }
897      }
898    }
899
900    if auto_direction {
901      node = node.with_presentation(Style::from(StyleDeclarationBlock::parse_loosy(
902        AUTO_DIRECTION,
903      )));
904    }
905
906    if !attributes.is_empty() {
907      node = node.with_named_attributes(attributes);
908    }
909
910    node
911  }
912
913  /// The source of an inline `<svg>`: its subtree as nodes, which the page's stylesheet reaches,
914  /// or its markup when the nodes do not form a document.
915  #[cfg(feature = "html-svg-nodes")]
916  fn inline_svg(&self, handle: NodeRef<'_>, depth: usize) -> Result<ImageSourceInput, HtmlError> {
917    let markup = handle.outer_html();
918    let root = self.svg_node(handle, depth)?;
919    let source = str::from_utf8(&markup)
920      .ok()
921      .zip(root)
922      .and_then(|(markup, root)| SvgSource::from_inline_element(&root, markup).ok());
923
924    Ok(match source {
925      Some(source) => ImageSourceInput::Loaded(ImageSource::from(source)),
926      None => ImageSourceInput::Buffer(markup),
927    })
928  }
929
930  #[cfg(not(feature = "html-svg-nodes"))]
931  fn inline_svg(&self, handle: NodeRef<'_>, _depth: usize) -> Result<ImageSourceInput, HtmlError> {
932    Ok(ImageSourceInput::Buffer(handle.outer_html()))
933  }
934
935  /// An inline `<svg>` element with its attributes under their qualified names, or a text.
936  #[cfg(feature = "html-svg-nodes")]
937  fn svg_node(&self, handle: NodeRef<'_>, depth: usize) -> Result<Option<Node>, HtmlError> {
938    if depth >= self.max_depth {
939      return Err(HtmlError::MaxDepthExceeded(self.max_depth));
940    }
941
942    Ok(match handle.data() {
943      NodeData::Text(contents) => Some(Node::text(contents.clone())),
944      NodeData::Element { name, attrs, .. } => {
945        let attributes = attrs
946          .iter()
947          .map(|attr| (self.names.get(&qualified_name(attr)), attr.value.clone()))
948          .collect();
949        let mut children = Vec::new();
950
951        for child in handle.children() {
952          children.extend(self.svg_node(child, depth + 1)?);
953        }
954
955        Some(
956          Node::container(children)
957            .with_tag_name(self.names.get(&name.local))
958            .with_named_attributes(attributes),
959        )
960      }
961      _ => None,
962    })
963  }
964
965  /// The style a `style` attribute of `css` sets.
966  fn style(&self, css: &str) -> Style {
967    if let Some(style) = self.styles.borrow().get(css) {
968      return style.clone();
969    }
970
971    let style = Style::from(StyleDeclarationBlock::parse_loosy(css));
972
973    self.styles.borrow_mut().insert(css.into(), style.clone());
974    style
975  }
976}
977
978/// Concatenated text if every child is a text node and not all of it is white space, else `None`.
979/// Comments are ignored, mirroring the JS markup walker.
980fn text_only_contents(handle: NodeRef<'_>) -> Option<String> {
981  let mut text = String::new();
982
983  for child in handle.children() {
984    match child.data() {
985      NodeData::Comment(_) => continue,
986      NodeData::Text(contents) => text.push_str(contents),
987      _ => return None,
988    }
989  }
990
991  text
992    .chars()
993    .any(|ch| !ch.is_ascii_whitespace())
994    .then_some(text)
995}
996
997/// The [`size_attribute`] when it is a number of pixels, which `ImageData` holds.
998fn pixels(handle: NodeRef<'_>, tag: &str, name: &str) -> Option<f32> {
999  match size_attribute(tag, handle.attribute(name)?)? {
1000    Length::Px(pixels) => Some(pixels),
1001    _ => None,
1002  }
1003}
1004
1005/// An attribute's name as SVG markup writes it, its namespace prefix included, as fragment
1006/// serialization names it. <https://html.spec.whatwg.org/multipage/parsing.html#attribute's-serialized-name>
1007#[cfg(feature = "html-svg-nodes")]
1008fn qualified_name(attr: &Attribute) -> Cow<'_, str> {
1009  let local = &*attr.local;
1010
1011  match attr.ns {
1012    AttributeNamespace::Xlink => format!("xlink:{local}").into(),
1013    AttributeNamespace::Xml => format!("xml:{local}").into(),
1014    AttributeNamespace::Xmlns if local != "xmlns" => format!("xmlns:{local}").into(),
1015    AttributeNamespace::None | AttributeNamespace::Xmlns => local.into(),
1016  }
1017}
1018
1019#[cfg(test)]
1020mod tests {
1021  use super::*;
1022  use crate::style::StyleDeclaration;
1023
1024  fn parse(source: &str) -> Node {
1025    from_html(source, FromHtmlOptions::default()).unwrap()
1026  }
1027
1028  /// An `<img>` takes a percentage `width` the way HTML parses a dimension, and an `<svg>` any
1029  /// CSS length, as Chrome maps them to style; a number of pixels stays in `ImageData`.
1030  #[test]
1031  fn image_size_attributes_in_other_units_style_the_image() {
1032    let image = parse(r#"<img src="a.png" width="50%" height="20..5">"#);
1033    let fraction_only = parse(r#"<img src="a.png" width=".5">"#);
1034    let svg = parse(r#"<svg width="100%" height="2em" viewBox="0 0 1 1"></svg>"#);
1035
1036    assert!(matches!(
1037      image.kind,
1038      NodeKind::Image(ImageData {
1039        width: None,
1040        height: Some(20.0),
1041        ..
1042      })
1043    ));
1044    assert!(matches!(
1045      fraction_only.kind,
1046      NodeKind::Image(ImageData { width: None, .. })
1047    ));
1048    assert!(image.to_html().contains(r#"width="50%""#));
1049    assert_eq!(
1050      size_preset(image),
1051      [
1052        StyleDeclaration::width(Length::Percentage(50.0)),
1053        StyleDeclaration::height(Length::Px(20.0)),
1054      ]
1055    );
1056    assert_eq!(
1057      size_preset(svg),
1058      [
1059        StyleDeclaration::width(Length::Percentage(100.0)),
1060        StyleDeclaration::height(Length::Em(2.0)),
1061      ]
1062    );
1063  }
1064
1065  fn size_preset(mut node: Node) -> Vec<StyleDeclaration> {
1066    node
1067      .take_style_layers()
1068      .preset
1069      .map(|preset| preset.declarations.iter().cloned().collect())
1070      .unwrap_or_default()
1071  }
1072
1073  #[cfg(feature = "html-svg-nodes")]
1074  #[test]
1075  fn an_svg_attribute_keeps_its_namespace_prefix() {
1076    let attribute = |ns, local: &str| Attribute {
1077      ns,
1078      local: local.into(),
1079      value: "".into(),
1080    };
1081
1082    assert_eq!(
1083      &*qualified_name(&attribute(AttributeNamespace::Xmlns, "xlink")),
1084      "xmlns:xlink"
1085    );
1086    assert_eq!(
1087      &*qualified_name(&attribute(AttributeNamespace::Xmlns, "xmlns")),
1088      "xmlns"
1089    );
1090    assert_eq!(
1091      &*qualified_name(&attribute(AttributeNamespace::Xlink, "href")),
1092      "xlink:href"
1093    );
1094    assert_eq!(
1095      &*qualified_name(&attribute(AttributeNamespace::None, "fill")),
1096      "fill"
1097    );
1098  }
1099
1100  /// A subtree of an inline `<svg>` past the depth limit fails as the rest of the document does,
1101  /// rather than drawing without its deepest elements.
1102  #[cfg(feature = "html-svg-nodes")]
1103  #[test]
1104  fn an_inline_svg_past_the_depth_limit_fails() {
1105    let options = FromHtmlOptions::builder().max_depth(2).build();
1106    let result = from_html(r#"<svg><g><rect width="1" height="1"/></g></svg>"#, options);
1107
1108    assert!(matches!(result, Err(HtmlError::MaxDepthExceeded(2))));
1109  }
1110
1111  /// A `style` attribute is a declaration list, and CSS drops only the declaration it
1112  /// cannot read. An unreadable width used to take the whole attribute down with it.
1113  #[test]
1114  fn an_unreadable_declaration_leaves_its_neighbours_alone() {
1115    let block = StyleDeclarationBlock::parse_loosy("font-size:64px;width:wider;color:red");
1116
1117    assert_eq!(block.len(), 2);
1118  }
1119
1120  #[test]
1121  fn builtin_presets_parse() {
1122    let presets = StylePresets::default();
1123    for (tag, _) in DEFAULT_PRESETS {
1124      let style = presets.get(tag).expect("preset present");
1125      assert!(
1126        !style.declarations.is_empty(),
1127        "preset `{tag}` produced no declarations",
1128      );
1129    }
1130  }
1131
1132  /// A list needs the counter style on the list and `display: list-item` on the
1133  /// item for the renderer to draw a marker.
1134  #[test]
1135  fn list_presets_carry_the_marker_styles() {
1136    for (tag, expected) in [
1137      ("ol", "list-style-type:decimal"),
1138      ("ul", "list-style-type:disc"),
1139      ("li", "display:list-item"),
1140    ] {
1141      let (_, css) = DEFAULT_PRESETS
1142        .iter()
1143        .find(|(name, _)| *name == tag)
1144        .expect("preset present");
1145
1146      assert!(
1147        css.contains(expected),
1148        "preset `{tag}` is missing `{expected}`"
1149      );
1150    }
1151  }
1152
1153  #[test]
1154  fn a_document_keeps_its_html_root() {
1155    let node = parse(
1156      r#"<!doctype html><html style="font-size:62.5%"><head><title>t</title></head><body><div>hi</div></body></html>"#,
1157    );
1158
1159    assert_eq!(node.tag_name(), Some("html"));
1160    assert!(node.to_html().contains("font-size: 62.5%"));
1161
1162    assert!(node.to_html().contains("<body"));
1163  }
1164
1165  /// A doctype makes a document even without an `<html>` tag, so the body and its margin are
1166  /// there as in a browser.
1167  #[test]
1168  fn a_doctype_makes_a_document() {
1169    let node = parse("<!DOCTYPE html><title>t</title><div>hi</div>");
1170
1171    assert_eq!(node.tag_name(), Some("html"));
1172    assert!(node.to_html().contains("<body"));
1173  }
1174
1175  #[test]
1176  fn a_leading_byte_order_mark_is_dropped() {
1177    assert_eq!(
1178      parse("\u{feff}<!doctype html><div>hi</div>").tag_name(),
1179      Some("html")
1180    );
1181    assert_eq!(parse("\u{feff}<div>hi</div>").tag_name(), Some("div"));
1182  }
1183
1184  #[test]
1185  fn a_fragment_gains_no_wrappers() {
1186    assert_eq!(parse("<div>hi</div>").tag_name(), Some("div"));
1187    assert_eq!(parse("<body><div>hi</div></body>").tag_name(), Some("div"));
1188    assert_eq!(parse("text <html> in content").tag_name(), None);
1189  }
1190
1191  #[test]
1192  fn the_document_option_wraps_a_fragment_in_html_and_body() {
1193    let options = FromHtmlOptions::builder().document(true).build();
1194    let node = parse_html("<style>p{}</style><p>hi</p>", options)
1195      .unwrap()
1196      .node;
1197
1198    assert_eq!(node.tag_name(), Some("html"));
1199    let html = node.to_html();
1200
1201    assert!(
1202      html.contains("<body ") && html.contains(">hi</p></body>"),
1203      "{html}"
1204    );
1205  }
1206
1207  #[test]
1208  fn the_fragment_option_drops_a_documents_html_and_body() {
1209    let options = FromHtmlOptions::builder().fragment(true).build();
1210    let node = parse_html(
1211      "<!doctype html><html><body><p>hi</p></body></html>",
1212      options,
1213    )
1214    .unwrap()
1215    .node;
1216
1217    assert_eq!(node.tag_name(), Some("p"));
1218  }
1219
1220  /// Tag names are ASCII case-insensitive, so a document is a document however
1221  /// its author spelled the root.
1222  #[test]
1223  fn a_document_root_is_matched_case_insensitively() {
1224    assert_eq!(
1225      parse("<Html><body>hi</body></Html>").tag_name(),
1226      Some("html")
1227    );
1228    assert_eq!(
1229      parse("<HTML><body>hi</body></HTML>").tag_name(),
1230      Some("html")
1231    );
1232  }
1233
1234  #[test]
1235  fn whitespace_around_single_root_is_trimmed() {
1236    let node = parse("\n  <div>x</div>\n");
1237    assert!(matches!(node.kind, NodeKind::Text(_)));
1238    assert!(node.to_html().starts_with("<div"));
1239  }
1240
1241  #[test]
1242  fn tailwind_property_can_alias_reserved_name() {
1243    let node = from_html(
1244      r#"<div class="flex">x</div>"#,
1245      FromHtmlOptions::builder()
1246        .presets(StylePresets::empty())
1247        .tailwind_property("class")
1248        .build(),
1249    )
1250    .unwrap();
1251    assert!(node.to_html().contains(r#"class="flex""#));
1252  }
1253
1254  #[test]
1255  fn tailwind_consumed_not_passthrough() {
1256    let node = parse(r#"<div tw="flex">x</div>"#);
1257    assert!(!node.to_html().contains("tw="));
1258  }
1259
1260  #[test]
1261  fn dir_is_case_insensitive() {
1262    let node = parse(r#"<div dir="RTL">x</div>"#);
1263    assert!(node.to_html().contains(r#"dir="rtl""#));
1264  }
1265
1266  #[test]
1267  fn an_img_without_a_source_is_a_replaced_element_with_no_pixels() {
1268    let node = parse(r#"<img src="" width="10" height="20">"#);
1269    let NodeKind::Image(data) = &node.kind else {
1270      panic!("expected image");
1271    };
1272
1273    assert!(matches!(data.src, ImageSourceInput::Loaded(_)));
1274    assert_eq!((data.width, data.height), (Some(10.0), Some(20.0)));
1275    assert!(node.to_html().contains(r#"width="10" height="20""#));
1276
1277    let reparsed = parse(&node.to_html());
1278    let NodeKind::Image(data) = &reparsed.kind else {
1279      panic!("expected image after a round trip");
1280    };
1281
1282    assert!(matches!(data.src, ImageSourceInput::Loaded(_)));
1283    assert_eq!((data.width, data.height), (Some(10.0), Some(20.0)));
1284  }
1285
1286  #[test]
1287  fn img_dimensions_parsed() {
1288    let node = parse(r#"<img src="a.png" width="10" height="20">"#);
1289    let NodeKind::Image(data) = &node.kind else {
1290      panic!("expected image");
1291    };
1292    assert_eq!(data.width, Some(10.0));
1293    assert_eq!(data.height, Some(20.0));
1294  }
1295
1296  #[test]
1297  fn text_only_element_becomes_text() {
1298    let node = parse("<p>hello</p>");
1299    let NodeKind::Text(data) = &node.kind else {
1300      panic!("expected text node");
1301    };
1302    assert_eq!(data.text, "hello");
1303    assert!(node.to_html().starts_with("<p"));
1304  }
1305
1306  #[test]
1307  fn multiple_roots_wrapped() {
1308    let node = parse("<div>a</div><div>b</div>");
1309    let NodeKind::Container { children } = &node.kind else {
1310      panic!("expected container");
1311    };
1312    assert_eq!(children.len(), 2);
1313    assert!(node.to_html().contains("100%"));
1314  }
1315
1316  #[test]
1317  fn a_repeated_inline_style_parses_like_the_first() {
1318    let node =
1319      parse(r#"<p style="color:red">a</p><p style="color:red">b</p><p style="color:blue">c</p>"#);
1320    let NodeKind::Container { children } = &node.kind else {
1321      panic!("expected container");
1322    };
1323    let alone = |source: &str| format!("{:?}", parse(source));
1324
1325    assert_eq!(
1326      format!("{:?}", children[1]),
1327      alone(r#"<p style="color:red">b</p>"#)
1328    );
1329    assert_eq!(
1330      format!("{:?}", children[2]),
1331      alone(r#"<p style="color:blue">c</p>"#)
1332    );
1333  }
1334
1335  #[test]
1336  fn inline_style_and_attributes() {
1337    let node = parse(r#"<div style="color:red" data-x="1">x</div>"#);
1338    let html = node.to_html();
1339    assert!(html.contains(r#"data-x="1""#));
1340    assert!(html.contains("color"));
1341  }
1342
1343  /// `html.css` styles a text field and a textarea, hides a hidden input, and greys a disabled
1344  /// one, including one inside a disabled fieldset outside its first legend.
1345  #[test]
1346  fn inputs_take_the_presets_of_their_type_and_state() {
1347    let node = parse(concat!(
1348      "<div>",
1349      r#"<input id="text">"#,
1350      r#"<input id="checkbox" type="checkbox">"#,
1351      r#"<input id="hidden" type="HIDDEN">"#,
1352      r#"<input id="disabled" disabled>"#,
1353      "<fieldset disabled>",
1354      r#"<legend><input id="in-legend"></legend>"#,
1355      r#"<legend><input id="in-second-legend"></legend>"#,
1356      r#"<input id="in-fieldset">"#,
1357      r#"<textarea id="textarea-in-fieldset"></textarea>"#,
1358      "</fieldset>",
1359      r#"<textarea id="textarea">x</textarea>"#,
1360      "</div>",
1361    ));
1362    let html = node.to_html();
1363    let style_of = |id: &str| {
1364      let id_at = html.find(&format!(r#"id="{id}""#)).unwrap();
1365      let start = html[..id_at].rfind('<').unwrap();
1366      let end = id_at + html[id_at..].find('>').unwrap();
1367
1368      html[start..end].to_owned()
1369    };
1370    let disabled_color = "color: rgb(84, 84, 84)";
1371
1372    assert!(style_of("text").contains("display: inline-block"));
1373    assert!(!style_of("text").contains(disabled_color));
1374    assert!(!style_of("checkbox").contains("style="));
1375    assert!(style_of("hidden").contains("display: none"));
1376    assert!(style_of("disabled").contains(disabled_color));
1377    assert!(!style_of("in-legend").contains(disabled_color));
1378    assert!(style_of("in-second-legend").contains(disabled_color));
1379    assert!(style_of("in-fieldset").contains(disabled_color));
1380    assert!(style_of("textarea").contains("white-space-collapse: preserve"));
1381    assert!(!style_of("textarea").contains(disabled_color));
1382    assert!(style_of("textarea-in-fieldset").contains(disabled_color));
1383  }
1384
1385  #[test]
1386  fn presets_disabled() {
1387    let node = from_html(
1388      "<p>x</p>",
1389      FromHtmlOptions::builder()
1390        .presets(StylePresets::empty())
1391        .build(),
1392    )
1393    .unwrap();
1394    assert!(!node.to_html().contains("style="));
1395  }
1396
1397  #[test]
1398  fn nesting_past_max_depth_is_rejected() {
1399    let src = format!("{}{}", "<div>".repeat(4), "</div>".repeat(4));
1400    let opts = FromHtmlOptions::builder().max_depth(2).build();
1401    assert!(matches!(
1402      from_html(&src, opts),
1403      Err(HtmlError::MaxDepthExceeded(2)),
1404    ));
1405  }
1406
1407  #[test]
1408  fn style_elements_become_css_in_document_order() {
1409    let parsed = parse_html(
1410      "<!doctype html><head><style>a{}</style></head><body><style></style><div><style>b{}</style></div><svg><style>c{}</style></svg></body>",
1411      FromHtmlOptions::default(),
1412    )
1413    .unwrap();
1414
1415    assert_eq!(parsed.css, ["a{}", "b{}"]);
1416  }
1417
1418  #[test]
1419  fn a_style_media_attribute_becomes_a_media_rule() {
1420    let parsed = parse_html(
1421      r#"<style media=" print ">a{}</style><style media="">b{}</style>"#,
1422      FromHtmlOptions::default(),
1423    )
1424    .unwrap();
1425
1426    assert_eq!(parsed.css, ["@media print {a{}}", "b{}"]);
1427    assert_eq!(
1428      parsed
1429        .styles
1430        .iter()
1431        .map(|style| (&*style.text, style.media.as_deref()))
1432        .collect::<Vec<_>>(),
1433      [("a{}", Some("print")), ("b{}", None)]
1434    );
1435  }
1436
1437  #[test]
1438  fn a_style_inside_an_svg_integration_point_becomes_css() {
1439    let parsed = parse_html(
1440      "<svg><style>a{}</style><foreignObject><div><style>b{}</style></div></foreignObject><desc><style>c{}</style></desc></svg>",
1441      FromHtmlOptions::default(),
1442    )
1443    .unwrap();
1444
1445    assert_eq!(parsed.css, ["b{}", "c{}"]);
1446  }
1447
1448  #[test]
1449  fn a_style_of_another_type_holds_no_css() {
1450    let parsed = parse_html(
1451      r#"<style type="text/plain">a{}</style><style type="TEXT/CSS">b{}</style><style type="">c{}</style>"#,
1452      FromHtmlOptions::default(),
1453    )
1454    .unwrap();
1455
1456    assert_eq!(parsed.css, ["b{}", "c{}"]);
1457  }
1458
1459  #[test]
1460  fn stylesheet_links_keep_their_place_among_the_style_elements() {
1461    let parsed = parse_html(
1462      r#"<!doctype html><head><link rel="stylesheet" href="a.css"><style>b{}</style><link rel="Preload StyleSheet" href="c.css" media=" print "></head><body><style>d{}</style><link rel=stylesheet href="e.css"></body>"#,
1463      FromHtmlOptions::default(),
1464    )
1465    .unwrap();
1466    let css =
1467      parsed.css_with_links(|link| (link.href != "c.css").then(|| format!("{}{{}}", link.href)));
1468
1469    assert_eq!(
1470      parsed
1471        .links
1472        .iter()
1473        .map(|link| (&*link.href, link.media.as_deref(), link.css_index))
1474        .collect::<Vec<_>>(),
1475      [
1476        ("a.css", None, 0),
1477        ("c.css", Some("print"), 1),
1478        ("e.css", None, 2)
1479      ]
1480    );
1481    assert_eq!(css, ["a.css{}", "b{}", "d{}", "e.css{}"]);
1482    assert_eq!(
1483      parsed.css_with_links(|link| Some(link.href.clone()))[2],
1484      "@media print {c.css}"
1485    );
1486  }
1487
1488  #[test]
1489  fn a_link_that_loads_no_style_sheet_is_left_out() {
1490    let parsed = parse_html(
1491      r#"<link rel="icon" href="a.css"><link rel="alternate stylesheet" href="b.css"><link rel="stylesheet" href="c.css" disabled><link rel="stylesheet" href="d.css" type="text/less"><link rel="stylesheet" href=" "><link rel="stylesheet"><link rel="stylesheet" href="e.css" type=" TEXT/CSS; charset=utf-8">"#,
1492      FromHtmlOptions::default(),
1493    )
1494    .unwrap();
1495
1496    assert_eq!(
1497      parsed
1498        .links
1499        .iter()
1500        .map(|link| &*link.href)
1501        .collect::<Vec<_>>(),
1502      ["e.css"]
1503    );
1504  }
1505
1506  #[test]
1507  fn only_the_preferred_style_sheet_set_applies() {
1508    let parsed = parse_html(
1509      r#"<style>a{}</style><style title="dark">b{}</style><style title="light">c{}</style><link rel="alternate stylesheet" title="dark" href="d.css"><link rel="alternate stylesheet" title="light" href="e.css"><link rel="stylesheet" title="light" href="f.css">"#,
1510      FromHtmlOptions::default(),
1511    )
1512    .unwrap();
1513
1514    assert_eq!(parsed.css, ["a{}", "b{}"]);
1515    assert_eq!(
1516      parsed
1517        .links
1518        .iter()
1519        .map(|link| &*link.href)
1520        .collect::<Vec<_>>(),
1521      ["d.css"]
1522    );
1523  }
1524
1525  #[test]
1526  fn an_empty_titled_style_still_picks_the_style_sheet_set() {
1527    let parsed = parse_html(
1528      r#"<style title="dark"></style><style title="light">a{}</style><style>b{}</style>"#,
1529      FromHtmlOptions::default(),
1530    )
1531    .unwrap();
1532
1533    assert_eq!(parsed.css, ["b{}"]);
1534  }
1535
1536  #[test]
1537  fn a_default_style_meta_picks_the_style_sheet_set() {
1538    let parsed = parse_html(
1539      r#"<meta http-equiv="Default-Style" content="light"><style title="dark">a{}</style><style title="light">b{}</style>"#,
1540      FromHtmlOptions::default(),
1541    )
1542    .unwrap();
1543
1544    assert_eq!(parsed.css, ["b{}"]);
1545  }
1546
1547  #[test]
1548  fn the_first_base_with_an_href_sets_the_base() {
1549    let parsed = parse_html(
1550      r#"<!doctype html><head><base target="_top"><base href="https://example.com/a/"><base href="/b/"></head>"#,
1551      FromHtmlOptions::default(),
1552    )
1553    .unwrap();
1554
1555    assert_eq!(parsed.base_href.as_deref(), Some("https://example.com/a/"));
1556  }
1557
1558  #[test]
1559  fn void_elements_dropped() {
1560    let node = parse("<style>.a{color:red}</style><div>x</div>");
1561    assert!(node.to_html().starts_with("<div"));
1562  }
1563}