Skip to main content

takumi_core/layout/node/
mod.rs

1mod container;
2mod image;
3mod input;
4
5use std::{cell::RefCell, collections::BTreeMap, mem::take, sync::Arc};
6
7use serde::Deserialize;
8use thin_vec::ThinVec;
9
10pub(crate) use self::image::is_image_reference;
11pub use self::image::resolve_image;
12#[cfg(feature = "html")]
13pub(crate) use self::image::size_attribute;
14use crate::{
15  Xxh3HashSet,
16  context::RenderContext,
17  layout::{inline::InlineContentKind, length_utils::NaturalSize},
18  resources::{
19    image::{ImageCacheMode, ImageError, ImageResult, ImageSource},
20    image_buffer::ImageBuffer,
21  },
22  style::{
23    Direction, IgnoredDeclaration, Lang, Style, StyleDeclaration, TailwindValues, ToCss, TwRule,
24    tw::TailwindCache,
25  },
26  viewport::Viewport,
27};
28
29/// The most levels a node tree nests when it arrives as data: layout and paint
30/// recurse once per level. Blink's `HTMLConstructionSite::kMaximumHTMLParserDOMTreeDepth`.
31pub const MAXIMUM_DOM_TREE_DEPTH: usize = 512;
32
33/// An element or attribute name, which the elements of a parsed document carrying it share.
34pub(crate) type Name = Arc<str>;
35
36/// An element's attributes as name and value pairs, in name order: a slice, since a `BTreeMap`
37/// leaf takes 368 bytes for even one attribute.
38pub(crate) type Attributes = Box<[(Name, Box<str>)]>;
39
40/// The names a document's elements carry so far, each stored once.
41#[derive(Default)]
42pub(crate) struct Names(RefCell<Xxh3HashSet<Name>>);
43
44impl Names {
45  /// `name`, shared with each element before it that carried the same name.
46  pub(crate) fn get(&self, name: &str) -> Name {
47    if let Some(shared) = self.0.borrow().get(name) {
48      return shared.clone();
49    }
50
51    let shared = Name::from(name);
52
53    self.0.borrow_mut().insert(shared.clone());
54    shared
55  }
56}
57
58/// Shared metadata stored by every renderable node.
59#[derive(Debug, Clone, Default)]
60pub(crate) struct NodeMetadata {
61  /// The element's tag name.
62  pub tag_name: Option<Name>,
63  /// The element's class name.
64  pub class_name: Option<Box<str>>,
65  /// The element's id.
66  pub id: Option<Box<str>>,
67  /// Additional element attributes for selector matching and serialization.
68  pub attributes: Option<Attributes>,
69  /// Default style presets from HTML element type (lowest priority).
70  pub preset: Option<Arc<Style>>,
71  /// Presentation attributes as declarations, which the cascade places between the preset and
72  /// author rules, as Blink's presentational hints.
73  pub presentation: Option<Box<Style>>,
74  /// The styling properties for this node.
75  pub style: Option<Box<Style>>,
76  /// The declarations parsing dropped from `style`, kept after the cascade takes it.
77  pub ignored: ThinVec<IgnoredDeclaration>,
78  /// The tailwind properties for this node.
79  pub tw: Option<TailwindValues>,
80  /// The text direction for this node.
81  pub dir: Option<Direction>,
82  /// The BCP-47 language tag for this node, equivalent to the `lang` attribute.
83  pub lang: Option<Lang>,
84}
85
86#[derive(Debug, Default, Clone, Deserialize)]
87#[serde(rename_all = "camelCase")]
88/// Variant-specific text node data.
89pub struct TextData {
90  /// The text content.
91  pub text: String,
92}
93
94#[derive(Debug, Clone, Deserialize)]
95#[serde(untagged)]
96/// An image source as received from input: URL, raw bytes, raw pixels, or
97/// already loaded.
98#[non_exhaustive]
99pub enum ImageSourceInput {
100  /// Source URL or path.
101  Url(Arc<str>),
102  /// Raw image bytes.
103  Buffer(#[serde(with = "serde_bytes")] Vec<u8>),
104  /// Raw RGBA pixels with explicit dimensions, used without decoding.
105  Rgba(RgbaImage),
106  /// Pre-resolved image source.
107  #[serde(skip_deserializing)]
108  Loaded(ImageSource),
109}
110
111/// Raw row-major RGBA pixels, converted to a premultiplied bitmap once at
112/// construction; resolving is a reference-count bump.
113#[derive(Debug, Clone, Deserialize)]
114#[serde(try_from = "RgbaImageData")]
115pub struct RgbaImage {
116  source: ImageSource,
117}
118
119impl RgbaImage {
120  /// Wraps raw RGBA pixels, premultiplying in place unless `premultiplied`
121  /// says the bytes already are. Errors if `data.len() != width * height * 4`.
122  pub fn new(
123    data: Vec<u8>,
124    width: u32,
125    height: u32,
126    premultiplied: bool,
127  ) -> Result<Self, ImageError> {
128    let buffer = if premultiplied {
129      ImageBuffer::from_premultiplied_rgba(data, width, height)
130    } else {
131      ImageBuffer::from_rgba_bytes(data, width, height)
132    };
133
134    buffer
135      .map(|buffer| Self {
136        source: ImageSource::from(buffer),
137      })
138      .ok_or(ImageError::MismatchedBufferSize)
139  }
140}
141
142/// The wire shape of [`RgbaImage`], straight alpha unless `premultiplied`.
143#[derive(Deserialize)]
144#[serde(rename_all = "camelCase")]
145struct RgbaImageData {
146  width: u32,
147  height: u32,
148  #[serde(with = "serde_bytes")]
149  data: Vec<u8>,
150  #[serde(default)]
151  premultiplied: Option<bool>,
152}
153
154impl TryFrom<RgbaImageData> for RgbaImage {
155  type Error = ImageError;
156
157  fn try_from(raw: RgbaImageData) -> Result<Self, Self::Error> {
158    Self::new(
159      raw.data,
160      raw.width,
161      raw.height,
162      raw.premultiplied.unwrap_or_default(),
163    )
164  }
165}
166
167impl ImageSourceInput {
168  /// Resolve this input to image bytes using the render context.
169  pub fn resolve(&self, context: &RenderContext) -> ImageResult {
170    match self {
171      Self::Url(src) => resolve_image(src, context),
172      Self::Buffer(data) => context.cache().decode_image(data, ImageCacheMode::Auto),
173      Self::Rgba(raw) => Ok(raw.source.clone()),
174      Self::Loaded(source) => Ok(source.clone()),
175    }
176  }
177}
178
179#[derive(Debug, Clone, Deserialize)]
180#[serde(rename_all = "camelCase")]
181/// Variant-specific image node data.
182pub struct ImageData {
183  /// The image source.
184  pub src: ImageSourceInput,
185  /// Override width in pixels.
186  pub width: Option<f32>,
187  /// Override height in pixels.
188  pub height: Option<f32>,
189}
190
191impl From<&str> for ImageData {
192  fn from(src: &str) -> Self {
193    Self::from((src, None, None))
194  }
195}
196
197impl From<String> for ImageData {
198  fn from(src: String) -> Self {
199    Self::from((src, None, None))
200  }
201}
202
203impl From<Arc<str>> for ImageData {
204  fn from(src: Arc<str>) -> Self {
205    Self::from((src, None, None))
206  }
207}
208
209impl From<Vec<u8>> for ImageData {
210  fn from(data: Vec<u8>) -> Self {
211    Self {
212      src: ImageSourceInput::Buffer(data),
213      width: None,
214      height: None,
215    }
216  }
217}
218
219impl From<&[u8]> for ImageData {
220  fn from(data: &[u8]) -> Self {
221    Self::from(data.to_vec())
222  }
223}
224
225impl From<ImageSource> for ImageData {
226  fn from(source: ImageSource) -> Self {
227    Self {
228      src: ImageSourceInput::Loaded(source),
229      width: None,
230      height: None,
231    }
232  }
233}
234
235impl From<ImageBuffer> for ImageData {
236  fn from(buffer: ImageBuffer) -> Self {
237    Self::from(ImageSource::from(buffer))
238  }
239}
240
241impl From<(&str, u32, u32)> for ImageData {
242  fn from((src, width, height): (&str, u32, u32)) -> Self {
243    Self::from((src, width as f32, height as f32))
244  }
245}
246
247impl From<(String, u32, u32)> for ImageData {
248  fn from((src, width, height): (String, u32, u32)) -> Self {
249    Self::from((src, width as f32, height as f32))
250  }
251}
252
253impl From<(Arc<str>, u32, u32)> for ImageData {
254  fn from((src, width, height): (Arc<str>, u32, u32)) -> Self {
255    Self::from((src, width as f32, height as f32))
256  }
257}
258
259impl From<(&str, f32, f32)> for ImageData {
260  fn from((src, width, height): (&str, f32, f32)) -> Self {
261    Self::from((src, Some(width), Some(height)))
262  }
263}
264
265impl From<(String, f32, f32)> for ImageData {
266  fn from((src, width, height): (String, f32, f32)) -> Self {
267    Self::from((src, Some(width), Some(height)))
268  }
269}
270
271impl From<(Arc<str>, f32, f32)> for ImageData {
272  fn from((src, width, height): (Arc<str>, f32, f32)) -> Self {
273    Self::from((src, Some(width), Some(height)))
274  }
275}
276
277impl From<(&str, Option<f32>, Option<f32>)> for ImageData {
278  fn from((src, width, height): (&str, Option<f32>, Option<f32>)) -> Self {
279    Self::from((Arc::from(src), width, height))
280  }
281}
282
283impl From<(String, Option<f32>, Option<f32>)> for ImageData {
284  fn from((src, width, height): (String, Option<f32>, Option<f32>)) -> Self {
285    Self::from((Arc::from(src), width, height))
286  }
287}
288
289impl From<(Arc<str>, Option<f32>, Option<f32>)> for ImageData {
290  fn from((src, width, height): (Arc<str>, Option<f32>, Option<f32>)) -> Self {
291    Self {
292      src: ImageSourceInput::Url(src),
293      width,
294      height,
295    }
296  }
297}
298
299#[derive(Debug, Clone)]
300/// A renderable node with shared metadata and variant-specific content.
301pub struct Node {
302  pub(crate) metadata: NodeMetadata,
303  /// The variant-specific content of this node.
304  pub kind: NodeKind,
305}
306
307/// Represents the nodes enum.
308#[derive(Debug, Clone)]
309#[non_exhaustive]
310pub enum NodeKind {
311  /// A node that contains other nodes.
312  Container {
313    /// The container child nodes.
314    children: Vec<Node>,
315  },
316  /// A node that displays an image.
317  Image(ImageData),
318  /// A node that displays text.
319  Text(TextData),
320}
321
322impl Default for Node {
323  fn default() -> Self {
324    Self::container([])
325  }
326}
327
328impl Drop for Node {
329  fn drop(&mut self) {
330    self.drop_children();
331  }
332}
333
334impl Node {
335  /// Creates a container node with the provided child nodes.
336  pub fn container(children: impl Into<Vec<Node>>) -> Self {
337    Self {
338      metadata: NodeMetadata::default(),
339      kind: NodeKind::Container {
340        children: children.into(),
341      },
342    }
343  }
344
345  /// Creates an image node from any supported image input shape.
346  pub fn image(data: impl Into<ImageData>) -> Self {
347    Self {
348      metadata: NodeMetadata::default(),
349      kind: NodeKind::Image(data.into()),
350    }
351  }
352
353  /// Creates a text node from the provided text.
354  pub fn text(text: impl Into<String>) -> Self {
355    Self {
356      metadata: NodeMetadata::default(),
357      kind: NodeKind::Text(TextData { text: text.into() }),
358    }
359  }
360
361  /// A copy with what styles the node and none of its children or selector attributes.
362  #[cfg(feature = "svg")]
363  pub(crate) fn styling_clone(&self) -> Self {
364    Self {
365      metadata: NodeMetadata {
366        tag_name: self.metadata.tag_name.clone(),
367        preset: self.metadata.preset.clone(),
368        presentation: self.metadata.presentation.clone(),
369        style: self.metadata.style.clone(),
370        dir: self.metadata.dir,
371        lang: self.metadata.lang,
372        ..NodeMetadata::default()
373      },
374      kind: NodeKind::Container {
375        children: Vec::new(),
376      },
377    }
378  }
379
380  /// Takes the node's own text, leaving an empty container behind.
381  pub(crate) fn take_text(&mut self) -> Option<String> {
382    let NodeKind::Text(data) = &mut self.kind else {
383      return None;
384    };
385
386    if data.text.is_empty() {
387      return None;
388    }
389
390    let text = take(&mut data.text);
391    self.kind = NodeKind::Container {
392      children: Vec::new(),
393    };
394
395    Some(text)
396  }
397
398  /// Blink's `IsBR`: a `<br>`, which takumi carries as a text node holding its line feed.
399  pub(crate) fn is_br(&self) -> bool {
400    matches!(self.kind, NodeKind::Text(_))
401      && self
402        .tag_name()
403        .is_some_and(|tag| tag.eq_ignore_ascii_case("br"))
404  }
405
406  /// Whether `display: contents` leaves the node out and renders its children, where the
407  /// [elements CSS Display ยง2.5 lists](https://drafts.csswg.org/css-display-3/#unbox-html) render
408  /// nothing. Blink's `AdjustStyleForHTMLElement`.
409  pub(crate) fn unboxes(&self) -> bool {
410    const BOXED: [&str; 15] = [
411      "audio", "br", "canvas", "embed", "iframe", "img", "input", "meter", "object", "progress",
412      "select", "svg", "textarea", "video", "wbr",
413    ];
414
415    !matches!(self.kind, NodeKind::Image(_))
416      && !self
417        .tag_name()
418        .is_some_and(|name| BOXED.into_iter().any(|tag| name.eq_ignore_ascii_case(tag)))
419  }
420
421  /// Whether the node is text alone, as a DOM text node is, and no element holding text.
422  pub(crate) fn is_text_run(&self) -> bool {
423    let NodeMetadata {
424      tag_name,
425      class_name,
426      id,
427      attributes,
428      preset,
429      presentation,
430      style,
431      ignored: _,
432      tw,
433      dir: _,
434      lang: _,
435    } = &self.metadata;
436
437    matches!(self.kind, NodeKind::Text(_))
438      && tag_name.is_none()
439      && class_name.is_none()
440      && id.is_none()
441      && attributes.is_none()
442      && preset.is_none()
443      && presentation.is_none()
444      && style.is_none()
445      && tw.is_none()
446  }
447
448  pub(crate) fn is_whitespace_only_text(&self) -> bool {
449    let NodeKind::Text(data) = &self.kind else {
450      return false;
451    };
452
453    if self.is_br() {
454      return false;
455    }
456    data
457      .text
458      .chars()
459      .all(|ch| matches!(ch, ' ' | '\t' | '\n' | '\r' | '\u{c}'))
460  }
461
462  /// Sets the tag name and returns the updated node.
463  pub fn with_tag_name(mut self, tag_name: impl Into<Arc<str>>) -> Self {
464    self.metadata.tag_name = Some(tag_name.into());
465    self
466  }
467
468  /// Sets the class name and returns the updated node.
469  pub fn with_class_name(mut self, class_name: impl Into<Box<str>>) -> Self {
470    self.metadata.class_name = Some(class_name.into());
471    self
472  }
473
474  /// Sets the element id and returns the updated node.
475  pub fn with_id(mut self, id: impl Into<Box<str>>) -> Self {
476    self.metadata.id = Some(id.into());
477    self
478  }
479
480  /// Sets the element attributes and returns the updated node.
481  pub fn with_attributes(mut self, attributes: BTreeMap<Box<str>, Box<str>>) -> Self {
482    self.metadata.attributes = Some(
483      attributes
484        .into_iter()
485        .map(|(name, value)| (Name::from(name), value))
486        .collect(),
487    );
488    self
489  }
490
491  /// Sets the element attributes under names the document's elements share.
492  #[cfg(any(feature = "html", feature = "svg"))]
493  pub(crate) fn with_named_attributes(mut self, attributes: BTreeMap<Name, Box<str>>) -> Self {
494    self.metadata.attributes = Some(attributes.into_iter().collect());
495    self
496  }
497
498  /// Sets the direction and returns the updated node.
499  pub fn with_dir(mut self, dir: Direction) -> Self {
500    self.metadata.dir = Some(dir);
501    self
502  }
503
504  /// Sets the BCP-47 language tag and returns the updated node.
505  pub fn with_lang(mut self, lang: Lang) -> Self {
506    self.metadata.lang = Some(lang);
507    self
508  }
509
510  /// Sets the preset style and returns the updated node.
511  pub fn with_preset(mut self, preset: impl Into<Arc<Style>>) -> Self {
512    self.metadata.preset = Some(preset.into());
513    self
514  }
515
516  /// Sets the presentation attributes' style and returns the updated node.
517  #[cfg(feature = "html")]
518  pub(crate) fn with_presentation(mut self, presentation: Style) -> Self {
519    self.metadata.presentation = Some(Box::new(presentation));
520    self
521  }
522
523  /// Sets the inline style and returns the updated node.
524  pub fn with_style(mut self, style: Style) -> Self {
525    self.metadata.style = Some(Box::new(style));
526    self
527  }
528
529  /// Sets the Tailwind-derived style input and returns the updated node.
530  pub fn with_tw(mut self, tw: TailwindValues) -> Self {
531    self.metadata.tw = Some(tw);
532    self
533  }
534
535  // Internal, do not use in production.
536  #[doc(hidden)]
537  pub fn to_html(&self) -> String {
538    let tag = self
539      .metadata
540      .tag_name
541      .as_deref()
542      .unwrap_or(match &self.kind {
543        NodeKind::Text(_) => "span",
544        NodeKind::Image(_) => "img",
545        NodeKind::Container { .. } => "div",
546      });
547
548    let escape_attr = |s: &str| s.replace('&', "&amp;").replace('"', "&quot;");
549
550    let mut attrs = Vec::new();
551    if let Some(id) = &self.metadata.id {
552      attrs.push(format!("id=\"{}\"", escape_attr(id)));
553    }
554    if let Some(class_name) = &self.metadata.class_name {
555      attrs.push(format!("class=\"{}\"", escape_attr(class_name)));
556    }
557    if let Some(dir) = &self.metadata.dir {
558      let dir_str = match dir {
559        Direction::Rtl => "rtl",
560        Direction::Ltr => "ltr",
561      };
562      attrs.push(format!("dir=\"{}\"", dir_str));
563    }
564    if let Some(lang) = &self.metadata.lang {
565      attrs.push(format!("lang=\"{}\"", escape_attr(lang.as_str())));
566    }
567    let image = match &self.kind {
568      NodeKind::Image(image) => Some(image),
569      _ => None,
570    };
571
572    if let Some(attributes) = &self.metadata.attributes {
573      for (k, v) in attributes.iter() {
574        // An image's own width and height win over an attribute of the same name.
575        let is_image_size = image.is_some_and(|image| match k.as_ref() {
576          "width" => image.width.is_some(),
577          "height" => image.height.is_some(),
578          _ => false,
579        });
580
581        if !is_image_size {
582          attrs.push(format!("{}=\"{}\"", k, escape_attr(v)));
583        }
584      }
585    }
586
587    if let Some(image) = image {
588      if let ImageSourceInput::Url(url) = &image.src {
589        attrs.push(format!("src=\"{}\"", escape_attr(url)));
590      }
591      // Adding zero writes a negative zero as `0`.
592      if let Some(width) = image.width {
593        attrs.push(format!("width=\"{}\"", width + 0.0));
594      }
595      if let Some(height) = image.height {
596        attrs.push(format!("height=\"{}\"", height + 0.0));
597      }
598    }
599
600    // Each entry is (prefix_len, css_string) where css_string[..prefix_len] is the property name.
601    // Inline overwrites preset for the same property โ€” no extra key allocation needed.
602    let mut inline_styles: Vec<(usize, String)> = Vec::new();
603    let mut push_decl = |decl: &StyleDeclaration| {
604      let mut buf = String::new();
605      if decl.to_css(&mut buf).is_ok() && !buf.is_empty() {
606        let prop_len = buf.find(':').unwrap_or(buf.len());
607        if let Some(pos) = inline_styles
608          .iter()
609          .position(|(len, s)| s.get(..*len) == buf.get(..prop_len))
610        {
611          inline_styles[pos].1 = buf;
612        } else {
613          inline_styles.push((prop_len, buf));
614        }
615      }
616    };
617    if let Some(preset) = &self.metadata.preset {
618      for decl in preset.declarations.iter() {
619        push_decl(decl);
620      }
621    }
622    if let Some(style) = &self.metadata.style {
623      for decl in style.declarations.iter() {
624        push_decl(decl);
625      }
626    }
627
628    if !inline_styles.is_empty() {
629      let joined = inline_styles
630        .iter()
631        .map(|(_, css)| css.as_str())
632        .collect::<Vec<_>>()
633        .join(" ");
634      attrs.push(format!("style=\"{}\"", escape_attr(&joined)));
635    }
636
637    let attrs_str = if attrs.is_empty() {
638      "".to_string()
639    } else {
640      format!(" {}", attrs.join(" "))
641    };
642
643    match &self.kind {
644      NodeKind::Text(text) => {
645        let escaped = text
646          .text
647          .replace('&', "&amp;")
648          .replace('<', "&lt;")
649          .replace('>', "&gt;")
650          .replace('"', "&quot;")
651          .replace('\'', "&#x27;");
652        format!("<{}{}>{}</{}>", tag, attrs_str, escaped, tag)
653      }
654      NodeKind::Image(_) => {
655        format!("<{}{} />", tag, attrs_str)
656      }
657      NodeKind::Container { children } => {
658        let mut children_html = String::new();
659        for child in children {
660          children_html.push_str(&child.to_html());
661        }
662        format!("<{}{}>{}</{}>", tag, attrs_str, children_html, tag)
663      }
664    }
665  }
666
667  pub(crate) fn take_style_layers(&mut self) -> NodeStyleLayers {
668    let mut preset = self.metadata.preset.take();
669
670    self.push_image_size_preset(&mut preset);
671
672    let mut inline = self.metadata.style.take();
673
674    if let Some(inline) = &mut inline {
675      self.metadata.ignored = take(&mut inline.declarations.ignored);
676    }
677
678    NodeStyleLayers {
679      preset,
680      presentation: self.metadata.presentation.take(),
681      inline,
682      dir: self.metadata.dir.take(),
683      lang: self.metadata.lang.take(),
684    }
685  }
686
687  pub(crate) fn inline_content(&self) -> Option<InlineContentKind<'_>> {
688    match &self.kind {
689      NodeKind::Container { .. } => None,
690      NodeKind::Image(_) => Some(InlineContentKind::Box),
691      NodeKind::Text(text) => Some(InlineContentKind::Text(text.text.as_str().into())),
692    }
693  }
694
695  /// The natural size of the replaced content it lays out, none for other content.
696  pub(crate) fn natural_size(&self, context: &RenderContext) -> NaturalSize {
697    match &self.kind {
698      NodeKind::Image(image) => image.natural_size(context),
699      NodeKind::Container { .. } | NodeKind::Text(_) => NaturalSize::default(),
700    }
701  }
702
703  /// Collects resource URLs referenced by this node tree.
704  pub(crate) fn metadata_image_urls<'a>(&'a self, urls: &mut Xxh3HashSet<&'a str>) {
705    match &self.kind {
706      NodeKind::Container { children } => {
707        for child in children {
708          child.metadata_image_urls(urls);
709        }
710      }
711      NodeKind::Image(image) => {
712        if let Some(url) = image.url() {
713          urls.insert(url);
714        }
715      }
716      NodeKind::Text(_) => {}
717    }
718  }
719
720  /// Collects resource URLs referenced by this node tree's styles.
721  pub(crate) fn style_image_urls<'a>(&'a self, urls: &mut Xxh3HashSet<&'a str>) {
722    if let Some(preset) = self.metadata.preset.as_ref() {
723      urls.extend(preset.image_urls());
724    }
725
726    if let Some(author_tw) = self.metadata.tw.as_ref() {
727      urls.extend(author_tw.image_urls(Viewport::default(), &Default::default()));
728    }
729
730    if let Some(inline) = self.metadata.style.as_ref() {
731      urls.extend(inline.image_urls());
732    }
733
734    let Some(children) = self.children() else {
735      return;
736    };
737
738    for child in children {
739      child.style_image_urls(urls);
740    }
741  }
742
743  /// Collects unique resource URLs referenced by this node tree and styles.
744  pub fn image_urls(&self) -> impl Iterator<Item = &str> {
745    let mut urls = Xxh3HashSet::default();
746    self.metadata_image_urls(&mut urls);
747    self.style_image_urls(&mut urls);
748
749    urls.into_iter()
750  }
751
752  pub(crate) fn is_replaced_element(&self) -> bool {
753    matches!(self.kind, NodeKind::Image(_))
754  }
755
756  /// The element's `href` attribute, when present and non-empty.
757  pub fn href(&self) -> Option<&str> {
758    self.attribute("href").filter(|href| !href.is_empty())
759  }
760
761  /// The element's `alt` attribute, when present. An explicitly empty value
762  /// marks a decorative image, distinct from a missing attribute.
763  pub fn alt(&self) -> Option<&str> {
764    self.attribute("alt")
765  }
766
767  /// The element's `scope` attribute, when present.
768  pub fn scope(&self) -> Option<&str> {
769    self.attribute("scope")
770  }
771
772  /// `id` and `class` resolve to the structured metadata fields rather than
773  /// the `attributes` map.
774  pub(crate) fn attribute(&self, name: &str) -> Option<&str> {
775    if name.eq_ignore_ascii_case("id") {
776      return self.metadata.id.as_deref();
777    }
778    if name.eq_ignore_ascii_case("class") {
779      return self.metadata.class_name.as_deref();
780    }
781    if name.eq_ignore_ascii_case("lang") {
782      return self.metadata.lang.as_ref().map(Lang::as_str);
783    }
784    self
785      .metadata
786      .attributes
787      .as_ref()?
788      .iter()
789      .find(|(attr_name, _)| attr_name.eq_ignore_ascii_case(name))
790      .map(|(_, value)| value.as_ref())
791  }
792}
793
794/// Style layers contributed by a node before cascade/inheritance assembly.
795#[derive(Debug, Default, Clone)]
796pub(crate) struct NodeStyleLayers {
797  /// UA/default style preset for the element.
798  pub(crate) preset: Option<Arc<Style>>,
799  /// Presentation attributes, which author rules outrank.
800  pub(crate) presentation: Option<Box<Style>>,
801  /// Inline style attached directly to the element.
802  pub(crate) inline: Option<Box<Style>>,
803  pub(crate) dir: Option<Direction>,
804  pub(crate) lang: Option<Lang>,
805}
806
807impl NodeStyleLayers {
808  /// Whether nothing but the preset styles the element beyond its matched rules.
809  pub(crate) fn is_preset_only(&self) -> bool {
810    self.presentation.is_none()
811      && self.inline.is_none()
812      && self.dir.is_none()
813      && self.lang.is_none()
814  }
815}
816
817/// Selector-matching queries read by [`crate::matching`].
818impl Node {
819  /// The element's tag name.
820  pub fn tag_name(&self) -> Option<&str> {
821    self.metadata.tag_name.as_deref()
822  }
823
824  /// The element's `id` attribute, when present.
825  pub fn id(&self) -> Option<&str> {
826    self.metadata.id.as_deref()
827  }
828
829  /// The element's `class` attribute, space-separated.
830  pub fn class_name(&self) -> Option<&str> {
831    self.metadata.class_name.as_deref()
832  }
833
834  /// The element's classes, split on ASCII whitespace as the HTML `class` attribute is.
835  pub fn classes(&self) -> impl Iterator<Item = &str> {
836    self
837      .class_name()
838      .into_iter()
839      .flat_map(str::split_ascii_whitespace)
840  }
841
842  /// The names in the element's attribute map.
843  pub(crate) fn attribute_names(&self) -> impl Iterator<Item = &str> {
844    self
845      .metadata
846      .attributes
847      .iter()
848      .flat_map(|attributes| attributes.iter().map(|(name, _)| name.as_ref()))
849  }
850
851  /// The rules the element's `tw` utilities compile to through `cache`, in the order they were
852  /// written.
853  pub(crate) fn tw_rules<'n>(
854    &'n self,
855    cache: &TailwindCache,
856  ) -> impl Iterator<Item = &'n Arc<TwRule>> {
857    self
858      .metadata
859      .tw
860      .iter()
861      .flat_map(move |tw| tw.rules(Some(cache)).iter())
862  }
863}
864
865#[cfg(test)]
866mod tests {
867  use std::str::FromStr;
868
869  use super::*;
870  use crate::style::{BackgroundImage, Style, StyleDeclaration, TailwindValues};
871
872  #[test]
873  fn an_image_writes_its_own_size_once_and_zero_without_a_sign() {
874    let node = Node::image(("a.png", Some(-0.0), Some(20.0)))
875      .with_attributes(BTreeMap::from([("height".into(), "5".into())]));
876    let html = node.to_html();
877
878    assert!(html.contains(r#"width="0""#), "{html}");
879    assert_eq!(html.matches("height=").count(), 1, "{html}");
880    assert!(html.contains(r#"height="20""#), "{html}");
881  }
882
883  #[test]
884  fn alt_distinguishes_missing_from_empty() {
885    let node = Node::container(Vec::new());
886
887    assert_eq!(node.alt(), None);
888
889    let node = node.with_attributes(BTreeMap::from([("alt".into(), "".into())]));
890
891    assert_eq!(node.alt(), Some(""));
892  }
893
894  #[test]
895  fn image_source_input_deserializes_raw_rgba() {
896    let input: ImageSourceInput = serde_json::from_value(serde_json::json!({
897      "width": 2,
898      "height": 1,
899      "data": [255, 0, 0, 128, 0, 255, 0, 255],
900    }))
901    .unwrap();
902
903    let ImageSourceInput::Rgba(raw) = input else {
904      panic!("expected Rgba, got {input:?}");
905    };
906    let ImageSource::Bitmap(buffer) = &raw.source else {
907      panic!("expected bitmap source");
908    };
909
910    assert_eq!((buffer.width(), buffer.height()), (2, 1));
911    assert_eq!(buffer.data(), [128, 0, 0, 128, 0, 255, 0, 255]);
912  }
913
914  #[test]
915  fn image_source_input_raw_rgba_premultiplied_skips_premultiply() {
916    let input: ImageSourceInput = serde_json::from_value(serde_json::json!({
917      "width": 1,
918      "height": 1,
919      "data": [100, 50, 0, 128],
920      "premultiplied": true,
921    }))
922    .unwrap();
923
924    let ImageSourceInput::Rgba(raw) = input else {
925      panic!("expected Rgba, got {input:?}");
926    };
927    let ImageSource::Bitmap(buffer) = &raw.source else {
928      panic!("expected bitmap source");
929    };
930
931    assert_eq!(buffer.data(), [100, 50, 0, 128]);
932  }
933
934  #[test]
935  fn image_source_input_rejects_mismatched_raw_rgba() {
936    let result: Result<ImageSourceInput, _> = serde_json::from_value(serde_json::json!({
937      "width": 4,
938      "height": 4,
939      "data": [0, 0, 0, 0],
940    }));
941
942    assert!(result.is_err());
943  }
944
945  #[test]
946  fn collect_style_fetch_tasks_collects_nested_background_image_urls() {
947    let background_url = "https://placehold.co/80x80/22c55e/white";
948    let node = Node::container([Node::container([]).with_style(Style::default().with(
949      StyleDeclaration::background_image(Some(
950        [BackgroundImage::Url(background_url.into())].into(),
951      )),
952    ))]);
953
954    let mut urls = Xxh3HashSet::default();
955    node.style_image_urls(&mut urls);
956
957    assert_eq!(urls.into_iter().collect::<Vec<_>>(), vec![background_url]);
958  }
959
960  #[test]
961  fn collect_style_fetch_tasks_collects_preset_and_tailwind_image_urls() {
962    let preset_url = "https://placehold.co/64x64/f97316/white";
963    let tailwind_url = "/bg.png";
964    let Ok(tw) = TailwindValues::from_str("bg-[url(/bg.png)]") else {
965      return;
966    };
967    let node = Node::container([])
968      .with_preset(
969        Style::default().with(StyleDeclaration::background_image(Some(
970          [BackgroundImage::Url(preset_url.into())].into(),
971        ))),
972      )
973      .with_tw(tw);
974
975    let mut urls = Xxh3HashSet::default();
976    node.style_image_urls(&mut urls);
977
978    let tasks = urls.into_iter().collect::<Vec<_>>();
979
980    assert_eq!(tasks, vec![tailwind_url, preset_url]);
981  }
982
983  #[test]
984  fn collect_style_fetch_tasks_collects_tailwind_mask_image_url() {
985    let mask_url = "/logo.svg";
986    let Ok(tw) = TailwindValues::from_str("mask-[url(/logo.svg)]") else {
987      return;
988    };
989    let node = Node::container([]).with_tw(tw);
990
991    let mut urls = Xxh3HashSet::default();
992    node.style_image_urls(&mut urls);
993
994    assert_eq!(urls.into_iter().collect::<Vec<_>>(), vec![mask_url]);
995  }
996
997  #[test]
998  fn collect_style_fetch_tasks_collects_tailwind_list_and_content_image_urls() {
999    let Ok(tw) =
1000      TailwindValues::from_str("list-image-[url(/marker.svg)] before:content-[url(/icon.png)]")
1001    else {
1002      return;
1003    };
1004    let node = Node::container([]).with_tw(tw);
1005
1006    let mut urls = Xxh3HashSet::default();
1007    node.style_image_urls(&mut urls);
1008
1009    let mut urls = urls.into_iter().collect::<Vec<_>>();
1010
1011    urls.sort_unstable();
1012    assert_eq!(urls, vec!["/icon.png", "/marker.svg"]);
1013  }
1014}
1015
1016#[cfg(test)]
1017mod matching_tests {
1018  use std::collections::BTreeMap;
1019
1020  use crate::{
1021    Cache,
1022    layout::node::Node,
1023    matching::{MatchedDeclarationsView, match_stylesheets_view},
1024    style::{ComputedStyle, Length, Style, StyleSheet},
1025    viewport::Viewport,
1026  };
1027
1028  fn container_with_class(class_name: &str) -> Node {
1029    Node::container([]).with_class_name(class_name)
1030  }
1031
1032  fn computed_style_from_matches(matches: &MatchedDeclarationsView<'_>) -> ComputedStyle {
1033    let mut style = Style::default();
1034    for declarations in matches
1035      .layered_normal()
1036      .iter()
1037      .chain(matches.unlayered_normal())
1038    {
1039      for declaration in declarations.iter() {
1040        style.push(declaration.clone(), false);
1041      }
1042    }
1043    for declarations in matches.important() {
1044      for declaration in declarations.iter() {
1045        style.push(declaration.clone(), false);
1046      }
1047    }
1048    style.inherit(&ComputedStyle::default())
1049  }
1050
1051  fn parse_stylesheet(css: &str) -> StyleSheet {
1052    let result = StyleSheet::parse(css);
1053    assert!(result.is_ok(), "expected stylesheet to parse: {result:?}");
1054    result.unwrap_or_default()
1055  }
1056
1057  fn parse_stylesheet_list<I, S>(stylesheets: I) -> StyleSheet
1058  where
1059    I: IntoIterator<Item = S>,
1060    S: AsRef<str>,
1061  {
1062    let result = StyleSheet::parse_list(stylesheets);
1063    assert!(
1064      result.is_ok(),
1065      "expected stylesheet list to parse: {result:?}"
1066    );
1067    result.unwrap_or_default()
1068  }
1069
1070  #[test]
1071  fn layered_rules_outrank_source_order() {
1072    let root = container_with_class("card");
1073    let stylesheet = parse_stylesheet(
1074      r#"
1075        @layer theme, base;
1076        @layer base {
1077          .card { width: 10px; }
1078        }
1079        @layer theme {
1080          .card { width: 20px; }
1081        }
1082      "#,
1083    );
1084
1085    let matched = match_stylesheets_view(
1086      &root,
1087      &[&stylesheet],
1088      Viewport::default(),
1089      Cache::default().tailwind(),
1090    );
1091    assert_eq!(matched.len(), 1);
1092    assert_eq!(
1093      computed_style_from_matches(matched[0].element())
1094        .box_data
1095        .width,
1096      Length::Px(10.0).into()
1097    );
1098  }
1099
1100  #[test]
1101  fn one_stylesheet_matches_media_queries_per_viewport() {
1102    let root = container_with_class("card");
1103    let stylesheet = parse_stylesheet(
1104      r#"
1105        .card { width: 10px; }
1106        @media (min-width: 600px) {
1107          .card { width: 20px; }
1108        }
1109      "#,
1110    );
1111
1112    for (viewport, width) in [((400, 300), 10.0), ((800, 600), 20.0), ((400, 300), 10.0)] {
1113      let matched = match_stylesheets_view(
1114        &root,
1115        &[&stylesheet],
1116        Viewport::new(viewport),
1117        Cache::default().tailwind(),
1118      );
1119      assert_eq!(
1120        computed_style_from_matches(matched[0].element())
1121          .box_data
1122          .width,
1123        Length::Px(width).into()
1124      );
1125    }
1126  }
1127
1128  #[test]
1129  fn nested_selector_uses_parent_list_specificity() {
1130    let root = Node::container([container_with_class("title")]).with_class_name("card notice");
1131
1132    let stylesheet = parse_stylesheet(
1133      r#"
1134        .card, #panel {
1135          .title { width: 10px; }
1136        }
1137
1138        .notice .title { width: 20px; }
1139      "#,
1140    );
1141
1142    let matched = match_stylesheets_view(
1143      &root,
1144      &[&stylesheet],
1145      Viewport::default(),
1146      Cache::default().tailwind(),
1147    );
1148    assert_eq!(matched.len(), 2);
1149    assert_eq!(
1150      computed_style_from_matches(matched[1].element())
1151        .box_data
1152        .width,
1153      Length::Px(10.0).into()
1154    );
1155  }
1156
1157  #[test]
1158  fn important_layered_rules_outrank_unlayered_important() {
1159    let root = container_with_class("card");
1160    let stylesheet = parse_stylesheet(
1161      r#"
1162        @layer theme, base;
1163        .card { width: 5px !important; }
1164        @layer base {
1165          .card { width: 10px !important; }
1166        }
1167        @layer theme {
1168          .card { width: 20px !important; }
1169        }
1170      "#,
1171    );
1172
1173    let matched = match_stylesheets_view(
1174      &root,
1175      &[&stylesheet],
1176      Viewport::default(),
1177      Cache::default().tailwind(),
1178    );
1179    assert_eq!(matched.len(), 1);
1180    assert_eq!(
1181      computed_style_from_matches(matched[0].element())
1182        .box_data
1183        .width,
1184      Length::Px(20.0).into()
1185    );
1186  }
1187
1188  #[test]
1189  fn later_stylesheet_rules_outrank_earlier_stylesheets_on_ties() {
1190    let root = container_with_class("card");
1191    let stylesheet = parse_stylesheet(".card { width: 10px; } .card { width: 20px; }");
1192
1193    let matched = match_stylesheets_view(
1194      &root,
1195      &[&stylesheet],
1196      Viewport::default(),
1197      Cache::default().tailwind(),
1198    );
1199    assert_eq!(matched.len(), 1);
1200    assert_eq!(
1201      computed_style_from_matches(matched[0].element())
1202        .box_data
1203        .width,
1204      Length::Px(20.0).into()
1205    );
1206  }
1207
1208  #[test]
1209  fn parse_list_preserves_cross_stylesheet_layer_order() {
1210    let root = container_with_class("card");
1211    let stylesheet = parse_stylesheet_list([
1212      r#"
1213        @layer theme, base;
1214        @layer base {
1215          .card { width: 10px; }
1216        }
1217      "#,
1218      r#"
1219        @layer theme {
1220          .card { width: 20px; }
1221        }
1222      "#,
1223    ]);
1224
1225    let matched = match_stylesheets_view(
1226      &root,
1227      &[&stylesheet],
1228      Viewport::default(),
1229      Cache::default().tailwind(),
1230    );
1231    assert_eq!(matched.len(), 1);
1232    assert_eq!(
1233      computed_style_from_matches(matched[0].element())
1234        .box_data
1235        .width,
1236      Length::Px(10.0).into()
1237    );
1238  }
1239
1240  #[test]
1241  fn root_selector_list_with_host_keeps_matching_root() {
1242    let root = Node::default();
1243    let stylesheet = parse_stylesheet(
1244      r#"
1245        :root, :host {
1246          width: 10px;
1247        }
1248      "#,
1249    );
1250
1251    let matched = match_stylesheets_view(
1252      &root,
1253      &[&stylesheet],
1254      Viewport::default(),
1255      Cache::default().tailwind(),
1256    );
1257    assert_eq!(matched.len(), 1);
1258    assert_eq!(
1259      computed_style_from_matches(matched[0].element())
1260        .box_data
1261        .width,
1262      Length::Px(10.0).into()
1263    );
1264  }
1265
1266  #[test]
1267  fn sibling_combinators_only_match_the_correct_siblings() {
1268    let root = Node::container([
1269      container_with_class("lead"),
1270      container_with_class("title"),
1271      container_with_class("spacer"),
1272      container_with_class("title"),
1273    ])
1274    .with_class_name("container");
1275    let stylesheet = parse_stylesheet(
1276      r#"
1277        .container .title { width: 20px; }
1278        .lead + .title { width: 10px; }
1279        .lead ~ .title { height: 30px; }
1280      "#,
1281    );
1282
1283    let matched = match_stylesheets_view(
1284      &root,
1285      &[&stylesheet],
1286      Viewport::default(),
1287      Cache::default().tailwind(),
1288    );
1289    assert_eq!(matched.len(), 5);
1290    assert_eq!(
1291      computed_style_from_matches(matched[2].element())
1292        .box_data
1293        .width,
1294      Length::Px(10.0).into()
1295    );
1296    assert_eq!(
1297      computed_style_from_matches(matched[2].element())
1298        .box_data
1299        .height,
1300      Length::Px(30.0).into()
1301    );
1302    assert_eq!(
1303      computed_style_from_matches(matched[4].element())
1304        .box_data
1305        .width,
1306      Length::Px(20.0).into()
1307    );
1308    assert_eq!(
1309      computed_style_from_matches(matched[4].element())
1310        .box_data
1311        .height,
1312      Length::Px(30.0).into()
1313    );
1314  }
1315
1316  #[test]
1317  fn attribute_selectors_match_node_metadata_and_attributes() {
1318    let root = Node::container([Node::container([])
1319      .with_id("hero")
1320      .with_class_name("card featured")
1321      .with_attributes(BTreeMap::from([
1322        (Box::<str>::from("data-kind"), Box::<str>::from("promo")),
1323        (
1324          Box::<str>::from("data-state"),
1325          Box::<str>::from("ready now"),
1326        ),
1327      ]))]);
1328    let stylesheet = parse_stylesheet(
1329      r#"
1330        [id="hero"] { width: 10px; }
1331        [class~="featured"] { height: 20px; }
1332        [data-kind="promo"] { width: 30px; }
1333        [data-state~="ready"] { height: 40px; }
1334      "#,
1335    );
1336
1337    let matched = match_stylesheets_view(
1338      &root,
1339      &[&stylesheet],
1340      Viewport::default(),
1341      Cache::default().tailwind(),
1342    );
1343    assert_eq!(matched.len(), 2);
1344    assert_eq!(
1345      computed_style_from_matches(matched[1].element())
1346        .box_data
1347        .width,
1348      Length::Px(30.0).into()
1349    );
1350    assert_eq!(
1351      computed_style_from_matches(matched[1].element())
1352        .box_data
1353        .height,
1354      Length::Px(40.0).into()
1355    );
1356  }
1357
1358  #[test]
1359  fn test_repro_mixed_importance_bug() {
1360    let stylesheet = parse_stylesheet(".test { width: 10px; height: 20px !important; }");
1361    let root = Node::container([]).with_class_name("test");
1362    let matched = match_stylesheets_view(
1363      &root,
1364      &[&stylesheet],
1365      Viewport::default(),
1366      Cache::default().tailwind(),
1367    );
1368
1369    assert_eq!(matched[0].element().unlayered_normal()[0].len(), 1);
1370    assert!(
1371      matched[0].element().unlayered_normal()[0]
1372        .importance
1373        .is_empty()
1374    );
1375
1376    assert_eq!(matched[0].element().important()[0].len(), 1);
1377    assert!(!matched[0].element().important()[0].importance.is_empty());
1378  }
1379
1380  #[test]
1381  fn empty_ignores_text_without_characters() {
1382    let stylesheet = parse_stylesheet(".box:empty { width: 10px; }");
1383    let root = Node::container([
1384      Node::container([Node::text("")]).with_class_name("box"),
1385      Node::container([Node::text("x")]).with_class_name("box"),
1386      Node::container([Node::container([])]).with_class_name("box"),
1387    ]);
1388    let matched = match_stylesheets_view(
1389      &root,
1390      &[&stylesheet],
1391      Viewport::default(),
1392      Cache::default().tailwind(),
1393    );
1394    let matches_empty = |index: usize| !matched[index].element().unlayered_normal().is_empty();
1395
1396    assert!(matches_empty(1));
1397    assert!(!matches_empty(3));
1398    assert!(!matches_empty(5));
1399  }
1400
1401  #[test]
1402  fn pseudo_element_rules_land_in_before_after_buckets() {
1403    let root = Node::container([]).with_class_name("card");
1404    let stylesheet = parse_stylesheet(
1405      r#"
1406        .card::before { content: "x"; }
1407        .card::after  { content: "y"; }
1408        .card         { width: 10px; }
1409      "#,
1410    );
1411
1412    let matched = match_stylesheets_view(
1413      &root,
1414      &[&stylesheet],
1415      Viewport::default(),
1416      Cache::default().tailwind(),
1417    );
1418    assert_eq!(matched.len(), 1);
1419
1420    assert!(!matched[0].element().unlayered_normal().is_empty());
1421    assert!(matched[0].before().is_some());
1422    assert!(matched[0].after().is_some());
1423  }
1424
1425  #[test]
1426  fn pseudo_element_rules_are_skipped_on_replaced_elements() {
1427    let root = Node::image("data:image/png;base64,iVBOR").with_class_name("logo");
1428    let stylesheet = parse_stylesheet(r#".logo::before { content: "x"; }"#);
1429
1430    let matched = match_stylesheets_view(
1431      &root,
1432      &[&stylesheet],
1433      Viewport::default(),
1434      Cache::default().tailwind(),
1435    );
1436    assert_eq!(matched.len(), 1);
1437    assert!(matched[0].before().is_none());
1438    assert!(matched[0].after().is_none());
1439  }
1440
1441  #[test]
1442  fn unsupported_pseudo_element_does_not_create_bucket() {
1443    let root = Node::container([]).with_class_name("card");
1444    let stylesheet = parse_stylesheet(r#".card::placeholder { color: red; }"#);
1445
1446    let matched = match_stylesheets_view(
1447      &root,
1448      &[&stylesheet],
1449      Viewport::default(),
1450      Cache::default().tailwind(),
1451    );
1452    assert_eq!(matched.len(), 1);
1453    assert!(matched[0].before().is_none());
1454    assert!(matched[0].after().is_none());
1455  }
1456}