Skip to main content

strata/runtime/
layout_tree.rs

1//! Layout tree construction, blueprint flattening, and UI IR graph synchronization.
2
3use super::*;
4
5impl AppRuntime {
6    /// Locates a blueprint node given its hierarchical index path.
7    pub fn find_blueprint_at_path<'a>(
8        blueprint: &'a NodeBlueprint,
9        path: &[usize],
10    ) -> Option<&'a NodeBlueprint> {
11        let mut cur = blueprint;
12        for &idx in path {
13            match cur {
14                NodeBlueprint::Element { children, .. } => {
15                    let mut flat = Vec::new();
16                    for c in children {
17                        Self::flatten_blueprints(c, &mut flat);
18                    }
19                    if idx >= flat.len() {
20                        return None;
21                    }
22                    cur = flat[idx];
23                }
24                NodeBlueprint::Fragment(children) => {
25                    let mut flat = Vec::new();
26                    for c in children {
27                        Self::flatten_blueprints(c, &mut flat);
28                    }
29                    if idx >= flat.len() {
30                        return None;
31                    }
32                    cur = flat[idx];
33                }
34                _ => return None,
35            }
36        }
37        Some(cur)
38    }
39
40    /// Compiles a reactive blueprint tree into a 64-byte cache-aligned UiIrGraph.
41    pub fn build_ir_graph(blueprint: &NodeBlueprint) -> strata_dom::UiIrGraph {
42        let mut graph = strata_dom::UiIrGraph::new();
43        let root_id = blueprint.compile_to_ir(&mut graph);
44        graph.root_id = if root_id.is_null() {
45            None
46        } else {
47            Some(root_id)
48        };
49        graph.recompute_subtree_spans();
50        graph
51    }
52
53    /// Synchronizes computed 2D geometry from LayoutNode hierarchy to UiIrGraph FixedRect coordinates.
54    pub fn sync_layout_to_ir(layout_root: &LayoutNode, ir_graph: &mut strata_dom::UiIrGraph) {
55        if let Some(root_id) = ir_graph.root_id {
56            Self::sync_layout_to_ir_recursive(layout_root, ir_graph, root_id);
57        }
58    }
59
60    pub(crate) fn sync_layout_to_ir_recursive(
61        layout_node: &LayoutNode,
62        ir_graph: &mut strata_dom::UiIrGraph,
63        ir_id: strata_dom::NodeId,
64    ) {
65        if ir_id.is_null() {
66            return;
67        }
68        if let Some(node) = ir_graph.get_mut(ir_id) {
69            node.layout_rect = strata_dom::FixedRect::from_f32(
70                layout_node.geometry.border_box.x,
71                layout_node.geometry.border_box.y,
72                layout_node.geometry.border_box.width,
73                layout_node.geometry.border_box.height,
74            );
75        }
76
77        let first_child = ir_graph
78            .get(ir_id)
79            .map(|n| n.first_child)
80            .unwrap_or(strata_dom::NodeId::NULL);
81        let mut curr_ir_child = first_child;
82        let mut layout_child_idx = 0;
83        while !curr_ir_child.is_null() && layout_child_idx < layout_node.children.len() {
84            let next_ir_child = ir_graph
85                .get(curr_ir_child)
86                .map(|n| n.next_sibling)
87                .unwrap_or(strata_dom::NodeId::NULL);
88            Self::sync_layout_to_ir_recursive(
89                &layout_node.children[layout_child_idx],
90                ir_graph,
91                curr_ir_child,
92            );
93            curr_ir_child = next_ir_child;
94            layout_child_idx += 1;
95        }
96    }
97
98    /// Reconstructs a LayoutNode hierarchy directly from a UiIrGraph.
99    pub fn build_layout_from_ir(
100        graph: &strata_dom::UiIrGraph,
101        node_id: strata_dom::NodeId,
102    ) -> LayoutNode {
103        let ir_node = match graph.get(node_id) {
104            Some(n) => n,
105            None => return LayoutNode::new(ComputedStyle::default()),
106        };
107
108        let mut style = ComputedStyle::default();
109        match ir_node.tag {
110            strata_dom::IrTag::FlexContainer => {
111                style.display = Display::Flex;
112            }
113            strata_dom::IrTag::GridContainer => {
114                style.display = Display::Grid;
115            }
116            strata_dom::IrTag::Span | strata_dom::IrTag::Text => {
117                style.display = Display::Inline;
118            }
119            _ => {
120                style.display = Display::Block;
121            }
122        }
123
124        let mut children = Vec::with_capacity(ir_node.child_count as usize);
125        let mut child_id = ir_node.first_child;
126        while !child_id.is_null() {
127            let next_sibling = graph
128                .get(child_id)
129                .map(|n| n.next_sibling)
130                .unwrap_or(strata_dom::NodeId::NULL);
131            children.push(Self::build_layout_from_ir(graph, child_id));
132            child_id = next_sibling;
133        }
134
135        let mut layout_node = LayoutNode::with_children(style, children);
136        let (x, y, w, h) = ir_node.layout_rect.to_f32();
137        if w > 0.0 || h > 0.0 {
138            let rect = strata_layout::Rect::new(x, y, w, h);
139            layout_node.geometry.border_box = rect;
140            layout_node.geometry.content_box = rect;
141            layout_node.geometry.padding_box = rect;
142            layout_node.geometry.margin_box = rect;
143        }
144        layout_node
145    }
146
147    /// Maps a DOM `Tag` to its canonical lowercase HTML element name for CSS selector matching.
148    pub(crate) fn tag_as_str(tag: &Tag) -> &'static str {
149        match tag {
150            Tag::Div => "div",
151            Tag::Span => "span",
152            Tag::Button => "button",
153            Tag::Input => "input",
154            Tag::Select => "select",
155            Tag::Option => "option",
156            Tag::Textarea => "textarea",
157            Tag::Label => "label",
158            Tag::Form => "form",
159            Tag::Header => "header",
160            Tag::Nav => "nav",
161            Tag::Main => "main",
162            Tag::Section => "section",
163            Tag::Aside => "aside",
164            Tag::Footer => "footer",
165            Tag::H1 => "h1",
166            Tag::H2 => "h2",
167            Tag::H3 => "h3",
168            Tag::H4 => "h4",
169            Tag::H5 => "h5",
170            Tag::H6 => "h6",
171            Tag::P => "p",
172            Tag::Ul => "ul",
173            Tag::Ol => "ol",
174            Tag::Li => "li",
175            Tag::A => "a",
176            Tag::Img => "img",
177            Tag::Audio => "audio",
178            Tag::Video => "video",
179            Tag::Svg => "svg",
180            Tag::Path => "path",
181            Tag::Canvas => "canvas",
182            Tag::Table => "table",
183            Tag::Thead => "thead",
184            Tag::Tbody => "tbody",
185            Tag::Tr => "tr",
186            Tag::Th => "th",
187            Tag::Td => "td",
188            Tag::Hr => "hr",
189            Tag::Br => "br",
190            Tag::Custom(name) => name,
191        }
192    }
193
194    /// Returns true if `tag` represents a `<style>` element.
195    #[inline]
196    pub(crate) fn is_style_tag(tag: &Tag) -> bool {
197        matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("style"))
198    }
199
200    /// Extracts concatenated text content inside a `<style>` element blueprint.
201    pub(crate) fn extract_style_element_text(children: &[NodeBlueprint], out: &mut String) {
202        for child in children {
203            match child {
204                NodeBlueprint::Text(t) => out.push_str(t),
205                NodeBlueprint::DynamicText(f) => out.push_str(&f()),
206                NodeBlueprint::Fragment(inner) => Self::extract_style_element_text(inner, out),
207                _ => {}
208            }
209        }
210    }
211
212    /// Parses and caches a CSS stylesheet string so hover/focus restyles avoid re-parsing unchanged `<style>` blocks.
213    pub(crate) fn parse_cached_stylesheet(
214        css: &str,
215    ) -> Option<std::sync::Arc<strata_style::StyleSheet>> {
216        thread_local! {
217            static STYLE_SHEET_CACHE: std::cell::RefCell<
218                std::collections::HashMap<String, std::sync::Arc<strata_style::StyleSheet>>
219            > = std::cell::RefCell::new(std::collections::HashMap::new());
220        }
221        let trimmed = css.trim();
222        if trimmed.is_empty() {
223            return None;
224        }
225        STYLE_SHEET_CACHE.with(|cache| {
226            if let Some(existing) = cache.borrow().get(trimmed) {
227                return Some(existing.clone());
228            }
229            let parsed = strata_style::StyleSheet::parse(trimmed).ok()?;
230            let arc = std::sync::Arc::new(parsed);
231            let mut map = cache.borrow_mut();
232            if map.len() >= 64 {
233                map.clear();
234            }
235            map.insert(trimmed.to_string(), arc.clone());
236            Some(arc)
237        })
238    }
239
240    /// Collects all `<style>` elements mounted inside `blueprint` in document order.
241    pub(crate) fn collect_stylesheets_from_blueprint(
242        blueprint: &NodeBlueprint,
243    ) -> Vec<std::sync::Arc<strata_style::StyleSheet>> {
244        let mut sheets = Vec::new();
245        Self::collect_stylesheets_rec(blueprint, &mut sheets, 0);
246        sheets
247    }
248
249    fn collect_stylesheets_rec(
250        blueprint: &NodeBlueprint,
251        out: &mut Vec<std::sync::Arc<strata_style::StyleSheet>>,
252        depth: usize,
253    ) {
254        if depth >= 256 {
255            return;
256        }
257        match blueprint {
258            NodeBlueprint::Element { tag, children, .. } => {
259                if Self::is_style_tag(tag) {
260                    let mut css = String::new();
261                    Self::extract_style_element_text(children, &mut css);
262                    if let Some(sheet) = Self::parse_cached_stylesheet(&css) {
263                        out.push(sheet);
264                    }
265                } else {
266                    for child in children {
267                        Self::collect_stylesheets_rec(child, out, depth + 1);
268                    }
269                }
270            }
271            NodeBlueprint::Fragment(children) => {
272                for child in children {
273                    Self::collect_stylesheets_rec(child, out, depth + 1);
274                }
275            }
276            _ => {}
277        }
278    }
279
280    /// Extracts tokenized class names, `id`, and key-value `Property` attributes from a blueprint element.
281    pub(crate) fn extract_element_selector_meta(
282        classes: &strata_dom::ClassList,
283        attributes: &[strata_dom::Attribute],
284    ) -> (Vec<String>, Option<String>, Vec<(String, String)>) {
285        let mut class_vec = Vec::new();
286        for cls in classes.iter() {
287            for tok in strata_style::tailwind::tokenize_classes(cls) {
288                if !tok.is_empty() {
289                    class_vec.push(tok.to_string());
290                }
291            }
292        }
293        let mut id_val = None;
294        let mut attr_vec = Vec::new();
295        for attr in attributes {
296            if let strata_dom::Attribute::Property { key, value } = attr {
297                if key.eq_ignore_ascii_case("id") && !value.is_empty() {
298                    id_val = Some(value.clone());
299                }
300                attr_vec.push((key.clone(), value.clone()));
301            }
302        }
303        (class_vec, id_val, attr_vec)
304    }
305
306    /// Resolves `:root`, `html`, and `body` rules from mounted `<style>` sheets so root custom properties
307    /// (`--*`) and document typography/color defaults cascade to the entire RSX tree.
308    pub(crate) fn resolve_document_root_inherited_style(
309        blueprint: &NodeBlueprint,
310        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
311        ctx: &InteractionContext,
312    ) -> ComputedStyle {
313        let mut doc_style = ComputedStyle::default();
314        let (root_classes, root_id, root_attrs) = match blueprint {
315            NodeBlueprint::Element {
316                classes,
317                attributes,
318                ..
319            } => Self::extract_element_selector_meta(classes, attributes),
320            _ => (Vec::new(), None, Vec::new()),
321        };
322        let pseudo_state = strata_style::selector::PseudoState {
323            is_dark: ctx.is_dark_mode,
324            ..Default::default()
325        };
326
327        for synthetic_tag in [":root", "html", "body"] {
328            let elem_ref = strata_style::selector::ElementRef::new(
329                synthetic_tag,
330                &root_classes,
331                root_id.as_deref(),
332                &root_attrs,
333            );
334            let mut matched = Vec::new();
335            let mut order = 0usize;
336            for sheet in stylesheets {
337                for rule in &sheet.rules {
338                    let layer = rule.layer_order.unwrap_or(u32::MAX);
339                    for sel in &rule.selectors {
340                        order += 1;
341                        if sel.matches_hierarchy_full(
342                            &elem_ref,
343                            &[],
344                            &[],
345                            Some(true),
346                            Some(true),
347                            &pseudo_state,
348                        ) {
349                            matched.push((layer, sel.specificity, order, &rule.declarations));
350                        }
351                    }
352                }
353            }
354            matched.sort_by_key(|&(layer, spec, ord, _)| (layer, spec, ord));
355            for &(_, _, _, decls) in &matched {
356                for decl in decls {
357                    if decl.property.starts_with("--") && !decl.important {
358                        strata_style::CascadeSolver::apply_declaration(&mut doc_style, decl);
359                    }
360                }
361            }
362            for &(_, _, _, decls) in &matched {
363                for decl in decls {
364                    if !decl.property.starts_with("--") && !decl.important {
365                        strata_style::CascadeSolver::apply_declaration(&mut doc_style, decl);
366                    }
367                }
368            }
369            for &(_, _, _, decls) in &matched {
370                for decl in decls {
371                    if decl.important {
372                        strata_style::CascadeSolver::apply_declaration(&mut doc_style, decl);
373                    }
374                }
375            }
376        }
377
378        ComputedStyle::inherit_from(&doc_style)
379    }
380
381    /// Recursively transforms an RSX `NodeBlueprint` into a `LayoutNode` hierarchy with styling and inheritance.
382    pub fn build_layout_tree(blueprint: &NodeBlueprint) -> LayoutNode {
383        let ctx = InteractionContext::default();
384        Self::build_layout_tree_with_interaction(blueprint, &ctx)
385    }
386
387    /// Recursively transforms an RSX `NodeBlueprint` into a `LayoutNode` hierarchy with styling, inheritance, and interaction state.
388    pub fn build_layout_tree_with_interaction(
389        blueprint: &NodeBlueprint,
390        ctx: &InteractionContext,
391    ) -> LayoutNode {
392        let mut path_buf = Vec::new();
393        let stylesheets = Self::collect_stylesheets_from_blueprint(blueprint);
394        let doc_inherited = if !stylesheets.is_empty() {
395            Some(Self::resolve_document_root_inherited_style(
396                blueprint,
397                &stylesheets,
398                ctx,
399            ))
400        } else {
401            None
402        };
403        let mut ancestors = Vec::new();
404        Self::build_layout_tree_full(
405            blueprint,
406            doc_inherited.as_ref(),
407            &mut path_buf,
408            ctx,
409            &stylesheets,
410            &mut ancestors,
411            &[],
412            true,
413            (false, false, false),
414        )
415    }
416
417    /// Recursively transforms an RSX `NodeBlueprint` into a `LayoutNode` hierarchy with styling, inheritance, and hover state.
418    pub fn build_layout_tree_with_hover(
419        blueprint: &NodeBlueprint,
420        hovered_path: Option<&[usize]>,
421    ) -> LayoutNode {
422        let ctx = InteractionContext {
423            hovered_path,
424            ..Default::default()
425        };
426        Self::build_layout_tree_with_interaction(blueprint, &ctx)
427    }
428
429    /// Internal recursive tree builder passing parent ComputedStyle for W3C CSS property inheritance.
430    pub fn build_layout_tree_with_parent(
431        blueprint: &NodeBlueprint,
432        parent_style: Option<&ComputedStyle>,
433    ) -> LayoutNode {
434        let mut path_buf = Vec::new();
435        let ctx = InteractionContext::default();
436        Self::build_layout_tree_with_interaction_context(
437            blueprint,
438            parent_style,
439            &mut path_buf,
440            &ctx,
441        )
442    }
443
444    /// Internal recursive tree builder passing parent style, node path, and active hover state.
445    pub fn build_layout_tree_with_context(
446        blueprint: &NodeBlueprint,
447        parent_style: Option<&ComputedStyle>,
448        current_path: &mut Vec<usize>,
449        hovered_path: Option<&[usize]>,
450    ) -> LayoutNode {
451        let ctx = InteractionContext {
452            hovered_path,
453            ..Default::default()
454        };
455        Self::build_layout_tree_with_interaction_context(
456            blueprint,
457            parent_style,
458            current_path,
459            &ctx,
460        )
461    }
462
463    /// Internal recursive tree builder passing parent style, node path, and full interaction context.
464    pub fn build_layout_tree_with_interaction_context(
465        blueprint: &NodeBlueprint,
466        parent_style: Option<&ComputedStyle>,
467        current_path: &mut Vec<usize>,
468        ctx: &InteractionContext,
469    ) -> LayoutNode {
470        let stylesheets = Self::collect_stylesheets_from_blueprint(blueprint);
471        let doc_inherited = if parent_style.is_none() && !stylesheets.is_empty() {
472            Some(Self::resolve_document_root_inherited_style(
473                blueprint,
474                &stylesheets,
475                ctx,
476            ))
477        } else {
478            None
479        };
480        let mut ancestors = Vec::new();
481        Self::build_layout_tree_full(
482            blueprint,
483            parent_style.or(doc_inherited.as_ref()),
484            current_path,
485            ctx,
486            &stylesheets,
487            &mut ancestors,
488            &[],
489            true,
490            (false, false, false),
491        )
492    }
493
494    #[allow(clippy::too_many_arguments)]
495    pub(crate) fn build_layout_tree_full(
496        blueprint: &NodeBlueprint,
497        parent_style: Option<&ComputedStyle>,
498        current_path: &mut Vec<usize>,
499        ctx: &InteractionContext,
500        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
501        ancestors: &mut Vec<CascadeElementMeta>,
502        preceding_siblings: &[CascadeElementMeta],
503        is_last_element_child: bool,
504        group_state: (bool, bool, bool),
505    ) -> LayoutNode {
506        let max_build_depth = if cfg!(debug_assertions) { 128 } else { 256 };
507        if current_path.len() >= max_build_depth {
508            let style = match parent_style {
509                Some(p) => ComputedStyle::inherit_from(p),
510                None => ComputedStyle::default(),
511            };
512            return LayoutNode::new(style);
513        }
514        match blueprint {
515            NodeBlueprint::Element {
516                tag,
517                classes,
518                attributes,
519                children,
520                ..
521            } => {
522                let entity_id = blueprint
523                    .entity_id()
524                    .unwrap_or(strata_primitives::EntityId::NONE);
525
526                // <style> tags are registered in `stylesheets` and emit a hidden placeholder node
527                // so 1-to-1 blueprint/layout child index correspondence is preserved.
528                if Self::is_style_tag(tag) {
529                    let mut style = ComputedStyle::default();
530                    style.display = Display::None;
531                    return LayoutNode::new(style).with_entity_id(entity_id);
532                }
533
534                let (mut style, current_meta_opt) = Self::resolve_element_cascade_style(
535                    tag,
536                    classes,
537                    attributes,
538                    parent_style,
539                    current_path,
540                    ctx,
541                    stylesheets,
542                    ancestors,
543                    preceding_siblings,
544                    is_last_element_child,
545                    group_state,
546                );
547
548                Self::apply_top_layer_position_override(tag, attributes, &mut style);
549
550                // 1. Vector SVG handling (runs AFTER full cascade so inherited `color`, `w-*`/`h-*`,
551                // custom properties, and `:hover` overrides apply to `<svg stroke="currentColor">`).
552                if matches!(tag, Tag::Svg | Tag::Path) {
553                    if let Some(mut svg_node) =
554                        Self::try_build_svg_leaf_node(blueprint, attributes, &mut style, entity_id)
555                    {
556                        Self::apply_portal_and_anchor_metadata(&mut svg_node, tag, attributes);
557                        return svg_node;
558                    }
559                }
560
561                // 2. Input / Textarea handling: synthesize text from value, children, or placeholder
562                if matches!(tag, Tag::Input | Tag::Textarea) {
563                    let mut input_node = Self::build_input_leaf_node(
564                        blueprint,
565                        matches!(tag, Tag::Textarea),
566                        attributes,
567                        *style,
568                        entity_id,
569                    );
570                    Self::apply_portal_and_anchor_metadata(&mut input_node, tag, attributes);
571                    return input_node;
572                }
573
574                // Replaced raster images: decode a base64 PNG data URI and carry
575                // its intrinsic dimensions on the layout node for painting.
576                if matches!(tag, Tag::Img) {
577                    if let Some(mut img_node) =
578                        Self::try_build_img_leaf_node(attributes, &mut style, entity_id)
579                    {
580                        Self::apply_portal_and_anchor_metadata(&mut img_node, tag, attributes);
581                        return img_node;
582                    }
583                }
584
585                // 2D / 3D Canvas Viewport handling: Canvas / Canvas2D / Canvas3D (or any element carrying a Canvas2D ScenePayload)
586                let canvas2d_payload = attributes.iter().find_map(|attr| {
587                    if let strata_dom::Attribute::ScenePayload(payload) = attr {
588                        if payload
589                            .downcast_ref::<Vec<strata_render::canvas2d::CanvasCommand>>()
590                            .is_some()
591                            || payload
592                                .downcast_ref::<std::sync::Arc<
593                                    Vec<strata_render::canvas2d::CanvasCommand>,
594                                >>()
595                                .is_some()
596                            || payload
597                                .downcast_ref::<strata_render::canvas2d::Canvas2DPaintCallback>()
598                                .is_some()
599                        {
600                            return Some(std::sync::Arc::clone(payload));
601                        }
602                    }
603                    None
604                });
605                if (canvas2d_payload.is_some()
606                    || matches!(tag, Tag::Canvas)
607                    || matches!(tag, Tag::Custom("Canvas3D" | "Canvas2D")))
608                    && Self::apply_canvas3d_sizing_and_check_leaf(attributes, children, &mut style)
609                {
610                    let mut canvas_node = LayoutNode::new(*style).with_entity_id(entity_id);
611                    if let Some(payload) = canvas2d_payload {
612                        canvas_node.scene_3d = Some(strata_layout::ViewportSceneHandle(payload));
613                    } else if let Some(scene_arc) =
614                        strata_render::scene3d::extract_scene3d_arc_from_blueprint(blueprint)
615                    {
616                        canvas_node.scene_3d =
617                            Some(strata_layout::ViewportSceneHandle(scene_arc));
618                    }
619                    Self::apply_portal_and_anchor_metadata(&mut canvas_node, tag, attributes);
620                    return canvas_node;
621                }
622
623                Self::apply_single_text_inline_intrinsic_sizing(&mut style, children);
624
625                let child_group_state = if Self::classes_have_group_marker(classes) {
626                    let self_hovered = ctx
627                        .hovered_path
628                        .is_some_and(|h| h.starts_with(current_path));
629                    let self_focused = ctx
630                        .focused_path
631                        .is_some_and(|f| f.starts_with(current_path));
632                    let self_active = self_hovered && ctx.is_mouse_down;
633                    (
634                        group_state.0 || self_hovered,
635                        group_state.1 || self_focused,
636                        group_state.2 || self_active,
637                    )
638                } else {
639                    group_state
640                };
641
642                let pushed_ancestor = if let Some(meta) = current_meta_opt {
643                    ancestors.push(meta);
644                    true
645                } else {
646                    false
647                };
648
649                let child_nodes = Self::build_flattened_children_full(
650                    children,
651                    Some(&style),
652                    current_path,
653                    ctx,
654                    stylesheets,
655                    ancestors,
656                    child_group_state,
657                );
658
659                if pushed_ancestor {
660                    ancestors.pop();
661                }
662
663                let mut node =
664                    LayoutNode::with_children(*style, child_nodes).with_entity_id(entity_id);
665                if let Some(payload) = canvas2d_payload {
666                    node.scene_3d = Some(strata_layout::ViewportSceneHandle(payload));
667                } else if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
668                    if let Some(scene_arc) =
669                        strata_render::scene3d::extract_scene3d_arc_from_blueprint(blueprint)
670                    {
671                        node.scene_3d = Some(strata_layout::ViewportSceneHandle(scene_arc));
672                    }
673                } else {
674                    for attr in attributes {
675                        if let strata_dom::Attribute::ScenePayload(payload) = attr {
676                            node.scene_3d = Some(strata_layout::ViewportSceneHandle(
677                                std::sync::Arc::clone(payload),
678                            ));
679                            break;
680                        }
681                    }
682                }
683                Self::apply_portal_and_anchor_metadata(&mut node, tag, attributes);
684                node
685            }
686            NodeBlueprint::Text(text) => {
687                Self::build_text_leaf_layout_node(text.clone(), parent_style)
688            }
689            NodeBlueprint::DynamicText(dyn_fn) => {
690                Self::build_text_leaf_layout_node(dyn_fn(), parent_style)
691            }
692            NodeBlueprint::Fragment(children) => {
693                let mut style = Box::new(match parent_style {
694                    Some(p) => ComputedStyle::inherit_from(p),
695                    None => ComputedStyle::default(),
696                });
697                style.display = Display::Flex;
698                style.flex_direction = FlexDirection::Column;
699
700                let child_nodes = Self::build_flattened_children_full(
701                    children,
702                    Some(&style),
703                    current_path,
704                    ctx,
705                    stylesheets,
706                    ancestors,
707                    group_state,
708                );
709
710                LayoutNode::with_children(*style, child_nodes)
711            }
712            NodeBlueprint::Empty => Self::build_empty_leaf_layout_node(),
713        }
714    }
715
716    #[inline(never)]
717    pub(crate) fn build_text_leaf_layout_node(
718        text: String,
719        parent_style: Option<&ComputedStyle>,
720    ) -> LayoutNode {
721        let mut style = match parent_style {
722            Some(p) => ComputedStyle::inherit_from(p),
723            None => ComputedStyle::default(),
724        };
725        style.display = Display::Inline;
726        let is_mono = strata_layout::is_monospace_family(style.font_family);
727        let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
728            &text,
729            style.font_size,
730            style.line_height,
731            None,
732            is_mono,
733            style.font_family,
734            style.font_weight,
735            style.font_style,
736        );
737        style.width = Dimension::Px(w.ceil());
738        style.height = Dimension::Px(h);
739        LayoutNode::with_text(style, text)
740    }
741
742    #[inline(never)]
743    fn build_empty_leaf_layout_node() -> LayoutNode {
744        let mut style = ComputedStyle::default();
745        style.display = Display::None;
746        LayoutNode::new(style)
747    }
748
749    #[allow(clippy::too_many_arguments)]
750    fn build_flattened_children_full(
751        children: &[NodeBlueprint],
752        parent_style: Option<&ComputedStyle>,
753        parent_path: &mut Vec<usize>,
754        ctx: &InteractionContext,
755        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
756        ancestors: &mut Vec<CascadeElementMeta>,
757        group_state: (bool, bool, bool),
758    ) -> Vec<LayoutNode> {
759        if parent_path.len() >= 256 {
760            return Vec::new();
761        }
762        let mut flat = Vec::with_capacity(children.len());
763        for child in children {
764            Self::flatten_blueprints(child, &mut flat);
765        }
766
767        let last_elem_flat_idx = if !stylesheets.is_empty() {
768            flat.iter().rposition(
769                |bp| matches!(bp, NodeBlueprint::Element { tag, .. } if !Self::is_style_tag(tag)),
770            )
771        } else {
772            None
773        };
774
775        let mut out = Vec::with_capacity(flat.len());
776        let mut preceding_siblings: Vec<CascadeElementMeta> = Vec::new();
777
778        for (idx, child_bp) in flat.into_iter().enumerate() {
779            parent_path.push(idx);
780            let is_last_elem = last_elem_flat_idx == Some(idx);
781            let node = Self::build_layout_tree_full(
782                child_bp,
783                parent_style,
784                parent_path,
785                ctx,
786                stylesheets,
787                ancestors,
788                &preceding_siblings,
789                is_last_elem,
790                group_state,
791            );
792            if !stylesheets.is_empty() {
793                if let NodeBlueprint::Element {
794                    tag,
795                    classes,
796                    attributes,
797                    ..
798                } = child_bp
799                {
800                    if !Self::is_style_tag(tag) {
801                        let is_hovered =
802                            ctx.hovered_path.is_some_and(|h| h.starts_with(parent_path));
803                        let is_focused =
804                            ctx.focused_path.is_some_and(|f| f.starts_with(parent_path));
805                        let is_active = is_hovered && ctx.is_mouse_down;
806                        let is_disabled = attributes.iter().any(|attr| match attr {
807                            strata_dom::Attribute::Property { key, value } => {
808                                key.eq_ignore_ascii_case("disabled")
809                                    && !value.eq_ignore_ascii_case("false")
810                            }
811                            _ => false,
812                        });
813                        let (class_vec, id_val, attr_vec) =
814                            Self::extract_element_selector_meta(classes, attributes);
815                        preceding_siblings.push(CascadeElementMeta {
816                            tag: Self::tag_as_str(tag),
817                            classes: class_vec,
818                            id: id_val,
819                            attributes: attr_vec,
820                            pseudo_state: strata_style::selector::PseudoState {
821                                is_hovered,
822                                is_focused,
823                                is_active,
824                                is_disabled,
825                                is_dark: ctx.is_dark_mode,
826                                is_group_hovered: group_state.0,
827                                is_group_focused: group_state.1,
828                                is_group_active: group_state.2,
829                            },
830                        });
831                    }
832                }
833            }
834            parent_path.pop();
835            out.push(node);
836        }
837        out
838    }
839
840    /// Recursively flattens Fragment blueprints so child elements splice directly into parent layout contexts.
841    pub(crate) fn append_child_layout_nodes_with_interaction_context(
842        blueprint: &NodeBlueprint,
843        parent_style: Option<&ComputedStyle>,
844        parent_path: &mut Vec<usize>,
845        child_counter: &mut usize,
846        ctx: &InteractionContext,
847        out: &mut Vec<LayoutNode>,
848    ) {
849        if parent_path.len() >= 256 {
850            return;
851        }
852        if let NodeBlueprint::Fragment(children) = blueprint {
853            for child in children {
854                Self::append_child_layout_nodes_with_interaction_context(
855                    child,
856                    parent_style,
857                    parent_path,
858                    child_counter,
859                    ctx,
860                    out,
861                );
862            }
863        } else {
864            let this_idx = *child_counter;
865            *child_counter += 1;
866            parent_path.push(this_idx);
867            let node = Self::build_layout_tree_with_interaction_context(
868                blueprint,
869                parent_style,
870                parent_path,
871                ctx,
872            );
873            parent_path.pop();
874            out.push(node);
875        }
876    }
877
878    /// Recursively flattens Fragment blueprints so child elements splice directly into parent layout contexts.
879    pub(crate) fn append_child_layout_nodes_with_context(
880        blueprint: &NodeBlueprint,
881        parent_style: Option<&ComputedStyle>,
882        parent_path: &mut Vec<usize>,
883        child_counter: &mut usize,
884        hovered_path: Option<&[usize]>,
885        out: &mut Vec<LayoutNode>,
886    ) {
887        let ctx = InteractionContext {
888            hovered_path,
889            ..Default::default()
890        };
891        Self::append_child_layout_nodes_with_interaction_context(
892            blueprint,
893            parent_style,
894            parent_path,
895            child_counter,
896            &ctx,
897            out,
898        );
899    }
900
901    /// Recursively flattens Fragment blueprints so child elements splice directly into parent layout contexts.
902    pub fn append_child_layout_nodes(
903        blueprint: &NodeBlueprint,
904        parent_style: Option<&ComputedStyle>,
905        out: &mut Vec<LayoutNode>,
906    ) {
907        let mut path_buf = Vec::new();
908        let mut child_counter = out.len();
909        Self::append_child_layout_nodes_with_context(
910            blueprint,
911            parent_style,
912            &mut path_buf,
913            &mut child_counter,
914            None,
915            out,
916        );
917    }
918
919    /// Iteratively flattens Fragment blueprints for linear child index alignment without call-stack recursion.
920    pub(crate) fn flatten_blueprints<'a>(bp: &'a NodeBlueprint, out: &mut Vec<&'a NodeBlueprint>) {
921        let mut stack = vec![bp];
922        while let Some(current) = stack.pop() {
923            if let NodeBlueprint::Fragment(children) = current {
924                for c in children.iter().rev() {
925                    stack.push(c);
926                }
927            } else {
928                out.push(current);
929            }
930        }
931    }
932
933    fn extract_inline_style_decl(style_raw: &str, target_prop: &str) -> Option<String> {
934        for decl in style_raw.split(';') {
935            if let Some((k, v)) = decl.split_once(':') {
936                if k.trim().eq_ignore_ascii_case(target_prop) {
937                    let val = v.trim().trim_end_matches("!important").trim();
938                    if !val.is_empty() && !val.eq_ignore_ascii_case("none") {
939                        return Some(val.trim_matches('"').trim_matches('\'').to_string());
940                    }
941                }
942            }
943        }
944        None
945    }
946
947    #[inline(never)]
948    fn apply_top_layer_position_override(
949        tag: &Tag,
950        attributes: &[strata_dom::Attribute],
951        style: &mut ComputedStyle,
952    ) {
953        if matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal")) {
954            style.position = strata_style::types::Position::Fixed;
955            return;
956        }
957        for attr in attributes {
958            if let strata_dom::Attribute::Property { key, value } = attr {
959                let k = key.trim();
960                let v = value.trim();
961                match k {
962                    "data-portal" => {
963                        if !matches!(
964                            v.to_ascii_lowercase().as_str(),
965                            "false" | "0" | "no" | "off"
966                        ) {
967                            style.position = strata_style::types::Position::Fixed;
968                            return;
969                        }
970                    }
971                    "popover" => {
972                        style.position = strata_style::types::Position::Fixed;
973                        return;
974                    }
975                    "data-portal-anchor" | "anchor" | "position-anchor" if !v.is_empty() => {
976                        style.position = strata_style::types::Position::Fixed;
977                        return;
978                    }
979                    "style" => {
980                        if Self::extract_inline_style_decl(v, "position-anchor").is_some() {
981                            style.position = strata_style::types::Position::Fixed;
982                            return;
983                        }
984                    }
985                    _ => {}
986                }
987            }
988        }
989    }
990
991    #[inline(never)]
992    pub(crate) fn apply_portal_and_anchor_metadata(
993        node: &mut LayoutNode,
994        tag: &Tag,
995        attributes: &[strata_dom::Attribute],
996    ) {
997        let is_portal_tag = matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal"));
998        if !is_portal_tag && attributes.is_empty() {
999            return;
1000        }
1001
1002        let mut element_id: Option<String> = None;
1003        let mut anchor_name: Option<String> = None;
1004        let mut is_portal_attr = false;
1005        let mut anchor_target: Option<String> = None;
1006        let mut placement_raw: Option<String> = None;
1007        let mut offset_opt: Option<f32> = None;
1008        let mut flip_opt: Option<bool> = None;
1009        let mut shift_opt: Option<bool> = None;
1010        let mut padding_opt: Option<f32> = None;
1011        let mut match_width_opt: Option<bool> = None;
1012        let mut min_width_from_anchor_opt: Option<bool> = None;
1013        let mut inline_style_raw: Option<&str> = None;
1014
1015        for attr in attributes {
1016            if let strata_dom::Attribute::Property { key, value } = attr {
1017                let k = key.trim();
1018                let v = value.trim();
1019                match k {
1020                    "id" | "data-anchor-id" => {
1021                        if !v.is_empty() {
1022                            element_id = Some(v.to_string());
1023                        }
1024                    }
1025                    "data-anchor-name" | "anchor-name" => {
1026                        if !v.is_empty() {
1027                            anchor_name = Some(v.to_string());
1028                        }
1029                    }
1030                    "data-portal" => {
1031                        is_portal_attr = !matches!(
1032                            v.to_ascii_lowercase().as_str(),
1033                            "false" | "0" | "no" | "off"
1034                        );
1035                    }
1036                    "popover" => {
1037                        is_portal_attr = true;
1038                    }
1039                    "data-portal-anchor" | "anchor" | "position-anchor" => {
1040                        if !v.is_empty() {
1041                            anchor_target = Some(v.to_string());
1042                        }
1043                    }
1044                    "data-portal-placement" | "placement" | "position-area" | "inset-area" => {
1045                        if !v.is_empty() {
1046                            placement_raw = Some(v.to_string());
1047                        }
1048                    }
1049                    "data-portal-offset" => {
1050                        if let Ok(parsed) = v.trim_end_matches("px").trim().parse::<f32>() {
1051                            offset_opt = Some(parsed);
1052                        }
1053                    }
1054                    "data-portal-flip" => {
1055                        flip_opt = Some(!matches!(
1056                            v.to_ascii_lowercase().as_str(),
1057                            "false" | "0" | "no" | "off"
1058                        ));
1059                    }
1060                    "data-portal-shift" => {
1061                        shift_opt = Some(!matches!(
1062                            v.to_ascii_lowercase().as_str(),
1063                            "false" | "0" | "no" | "off"
1064                        ));
1065                    }
1066                    "data-portal-padding" => {
1067                        if let Ok(parsed) = v.trim_end_matches("px").trim().parse::<f32>() {
1068                            padding_opt = Some(parsed);
1069                        }
1070                    }
1071                    "data-portal-match-width" => {
1072                        match_width_opt = Some(matches!(
1073                            v.to_ascii_lowercase().as_str(),
1074                            "true" | "1" | "yes" | "on"
1075                        ));
1076                    }
1077                    "data-portal-min-width" => {
1078                        min_width_from_anchor_opt = Some(matches!(
1079                            v.to_ascii_lowercase().as_str(),
1080                            "true" | "1" | "yes" | "on"
1081                        ));
1082                    }
1083                    "style" => {
1084                        inline_style_raw = Some(v);
1085                    }
1086                    _ => {}
1087                }
1088            }
1089        }
1090
1091        if let Some(style_str) = inline_style_raw {
1092            if anchor_name.is_none() {
1093                anchor_name = Self::extract_inline_style_decl(style_str, "anchor-name");
1094            }
1095            if anchor_target.is_none() {
1096                anchor_target = Self::extract_inline_style_decl(style_str, "position-anchor");
1097            }
1098            if placement_raw.is_none() {
1099                placement_raw = Self::extract_inline_style_decl(style_str, "position-area")
1100                    .or_else(|| Self::extract_inline_style_decl(style_str, "inset-area"));
1101            }
1102        }
1103
1104        let portal_anchor = anchor_target.map(|anchor_id| {
1105            let placement = placement_raw
1106                .as_deref()
1107                .and_then(strata_layout::AnchorPlacement::parse)
1108                .unwrap_or(strata_layout::AnchorPlacement::BottomEnd);
1109            Box::new(strata_layout::PortalAnchorSpec {
1110                anchor_id,
1111                placement,
1112                offset: offset_opt.unwrap_or(4.0),
1113                flip: flip_opt.unwrap_or(true),
1114                shift: shift_opt.unwrap_or(true),
1115                viewport_padding: padding_opt.unwrap_or(8.0),
1116                match_width: match_width_opt.unwrap_or(false),
1117                min_width_from_anchor: min_width_from_anchor_opt.unwrap_or(false),
1118            })
1119        });
1120
1121        node.element_id = element_id;
1122        node.anchor_name = anchor_name;
1123        node.is_top_layer = is_portal_tag || is_portal_attr || portal_anchor.is_some();
1124        node.portal_anchor = portal_anchor;
1125    }
1126
1127    /// Re-evaluates styling with the current interaction state, recomputes layout, and compiles display list.
1128    pub fn rebuild_layout_tree(&mut self) {
1129        self.applied_scroll_offsets.clear();
1130        self.applied_portal_offsets.clear();
1131        let stylesheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1132        for sheet in &stylesheets {
1133            self.register_keyframes_stylesheet(sheet);
1134        }
1135        let rebuild_start = std::time::Instant::now();
1136        let ctx = self.interaction_context();
1137        self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1138        self.sync_active_input_layout();
1139        let now_ms = self.now_ms();
1140        self.sync_tree_animations(now_ms);
1141        let compute_start = std::time::Instant::now();
1142        self.frame_profile.rebuild += compute_start.duration_since(rebuild_start);
1143        self.layout_root
1144            .compute_layout(self.viewport_width, self.viewport_height);
1145        Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
1146        self.layout_computations += 1;
1147        self.frame_profile.layout += compute_start.elapsed();
1148        if perf_logging_enabled() {
1149            perf_log_ms(
1150                "compute_layout_rebuild",
1151                compute_start,
1152                format!(
1153                    "{} layout nodes",
1154                    perf_count_layout_nodes(&self.layout_root)
1155                ),
1156            );
1157        }
1158        self.apply_viewport_clamps();
1159        self.apply_scroll_offsets();
1160        self.dispatch_resize_observers();
1161        self.spatial_index
1162            .rebuild(&self.root_blueprint, &self.layout_root);
1163        self.compile_display_list();
1164    }
1165
1166    /// Number of full layout computations performed by this runtime.
1167    pub fn layout_compute_count(&self) -> u64 {
1168        self.layout_computations
1169    }
1170
1171    /// Locates a mutable LayoutNode in the layout hierarchy by its hierarchical tree path.
1172    pub fn find_layout_node_mut<'a>(
1173        root: &'a mut LayoutNode,
1174        path: &[usize],
1175    ) -> Option<&'a mut LayoutNode> {
1176        let mut cur = root;
1177        for &idx in path {
1178            if idx >= cur.children.len() {
1179                return None;
1180            }
1181            cur = &mut cur.children[idx];
1182        }
1183        Some(cur)
1184    }
1185
1186    /// Recursively collects dynamic text node bindings with their exact hierarchical paths.
1187    pub fn collect_dynamic_text_bindings(
1188        blueprint: &NodeBlueprint,
1189        parent_path: &mut Vec<usize>,
1190        bindings: &mut Vec<DynamicTextBinding>,
1191    ) {
1192        if parent_path.len() >= 256 {
1193            return;
1194        }
1195        match blueprint {
1196            NodeBlueprint::Element { children, .. } => {
1197                let mut child_counter = 0;
1198                for child in children {
1199                    Self::collect_child_dynamic_text_bindings(
1200                        child,
1201                        parent_path,
1202                        &mut child_counter,
1203                        bindings,
1204                    );
1205                }
1206            }
1207            NodeBlueprint::Fragment(children) => {
1208                let mut child_counter = 0;
1209                for child in children {
1210                    Self::collect_child_dynamic_text_bindings(
1211                        child,
1212                        parent_path,
1213                        &mut child_counter,
1214                        bindings,
1215                    );
1216                }
1217            }
1218            NodeBlueprint::DynamicText(f) => {
1219                let val = f();
1220                bindings.push(DynamicTextBinding {
1221                    path: parent_path.clone(),
1222                    closure: f.clone(),
1223                    last_value: val,
1224                });
1225            }
1226            _ => {}
1227        }
1228    }
1229
1230    fn collect_child_dynamic_text_bindings(
1231        blueprint: &NodeBlueprint,
1232        parent_path: &mut Vec<usize>,
1233        child_counter: &mut usize,
1234        bindings: &mut Vec<DynamicTextBinding>,
1235    ) {
1236        if let NodeBlueprint::Fragment(children) = blueprint {
1237            for child in children {
1238                Self::collect_child_dynamic_text_bindings(
1239                    child,
1240                    parent_path,
1241                    child_counter,
1242                    bindings,
1243                );
1244            }
1245        } else {
1246            let this_idx = *child_counter;
1247            *child_counter += 1;
1248            parent_path.push(this_idx);
1249            Self::collect_dynamic_text_bindings(blueprint, parent_path, bindings);
1250            parent_path.pop();
1251        }
1252    }
1253
1254    #[inline(never)]
1255    #[allow(clippy::too_many_arguments)]
1256    fn resolve_element_cascade_style(
1257        tag: &Tag,
1258        classes: &strata_dom::ClassList,
1259        attributes: &[strata_dom::Attribute],
1260        parent_style: Option<&ComputedStyle>,
1261        current_path: &[usize],
1262        ctx: &InteractionContext,
1263        stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1264        ancestors: &[CascadeElementMeta],
1265        preceding_siblings: &[CascadeElementMeta],
1266        is_last_element_child: bool,
1267        group_state: (bool, bool, bool),
1268    ) -> (Box<ComputedStyle>, Option<CascadeElementMeta>) {
1269        let is_hovered = ctx
1270            .hovered_path
1271            .is_some_and(|h| h.starts_with(current_path));
1272        let is_focused = ctx
1273            .focused_path
1274            .is_some_and(|f| f.starts_with(current_path));
1275        let is_active = is_hovered && ctx.is_mouse_down;
1276        let is_disabled = attributes.iter().any(|attr| match attr {
1277            strata_dom::Attribute::Property { key, value } => {
1278                key.eq_ignore_ascii_case("disabled") && !value.eq_ignore_ascii_case("false")
1279            }
1280            _ => false,
1281        });
1282        let is_dark = ctx.is_dark_mode;
1283        let pseudo_state = strata_style::selector::PseudoState {
1284            is_hovered,
1285            is_focused,
1286            is_active,
1287            is_disabled,
1288            is_dark,
1289            is_group_hovered: group_state.0,
1290            is_group_focused: group_state.1,
1291            is_group_active: group_state.2,
1292        };
1293        let mut style = Box::new(match parent_style {
1294            Some(p) => ComputedStyle::inherit_from(p),
1295            None => ComputedStyle::default(),
1296        });
1297
1298        let mut has_direct_style = false;
1299        let mut direct_computed_override: Option<&strata_style::types::ComputedStyle> = None;
1300        let mut inline_decls: Vec<strata_style::Declaration> = Vec::new();
1301        for attr in attributes {
1302            if let strata_dom::Attribute::DirectStyle(any) = attr {
1303                if let Some(decls) = any.downcast_ref::<Vec<strata_style::Declaration>>() {
1304                    inline_decls.extend(decls.iter().cloned());
1305                    has_direct_style = true;
1306                } else if let Some(cs) = any.downcast_ref::<strata_style::types::ComputedStyle>() {
1307                    direct_computed_override = Some(cs);
1308                    has_direct_style = true;
1309                }
1310            }
1311        }
1312        if !has_direct_style {
1313            for attr in attributes {
1314                if let strata_dom::Attribute::Property { key, value } = attr {
1315                    if key.eq_ignore_ascii_case("style") && !value.is_empty() {
1316                        inline_decls.extend(strata_style::parse_declarations(value));
1317                    }
1318                }
1319            }
1320        }
1321
1322        let tag_name = Self::tag_as_str(tag);
1323        let mut matched_base_rules: Vec<(
1324            u32,
1325            strata_style::Specificity,
1326            usize,
1327            &[strata_style::Declaration],
1328        )> = Vec::new();
1329        let mut matched_interactive_rules: Vec<(
1330            u32,
1331            strata_style::Specificity,
1332            usize,
1333            &[strata_style::Declaration],
1334        )> = Vec::new();
1335        let mut current_meta_opt: Option<CascadeElementMeta> = None;
1336
1337        if !stylesheets.is_empty() {
1338            let (class_vec, id_val, attr_vec) =
1339                Self::extract_element_selector_meta(classes, attributes);
1340            let elem_ref = strata_style::selector::ElementRef::new(
1341                tag_name,
1342                &class_vec,
1343                id_val.as_deref(),
1344                &attr_vec,
1345            );
1346            let ancestor_refs: Vec<strata_style::selector::ElementRef<'_>> = ancestors
1347                .iter()
1348                .map(|a| {
1349                    strata_style::selector::ElementRef::new(
1350                        a.tag,
1351                        &a.classes,
1352                        a.id.as_deref(),
1353                        &a.attributes,
1354                    )
1355                })
1356                .collect();
1357            let ancestor_states: Vec<strata_style::selector::PseudoState> =
1358                ancestors.iter().map(|a| a.pseudo_state).collect();
1359            let sib_refs: Vec<strata_style::selector::ElementRef<'_>> = preceding_siblings
1360                .iter()
1361                .map(|s| {
1362                    strata_style::selector::ElementRef::new(
1363                        s.tag,
1364                        &s.classes,
1365                        s.id.as_deref(),
1366                        &s.attributes,
1367                    )
1368                })
1369                .collect();
1370            let sib_states: Vec<strata_style::selector::PseudoState> =
1371                preceding_siblings.iter().map(|s| s.pseudo_state).collect();
1372
1373            let mut order_counter = 0usize;
1374            for sheet in stylesheets {
1375                for rule in &sheet.rules {
1376                    let layer = rule.layer_order.unwrap_or(u32::MAX);
1377                    for sel in &rule.selectors {
1378                        order_counter += 1;
1379                        if sel.matches_hierarchy_with_ancestor_states(
1380                            &elem_ref,
1381                            &ancestor_refs,
1382                            Some(&ancestor_states),
1383                            &sib_refs,
1384                            Some(&sib_states),
1385                            Some(is_last_element_child),
1386                            None,
1387                            &pseudo_state,
1388                        ) {
1389                            if sel.has_any_interactive_pseudo() {
1390                                matched_interactive_rules.push((
1391                                    layer,
1392                                    sel.specificity,
1393                                    order_counter,
1394                                    &rule.declarations,
1395                                ));
1396                            } else {
1397                                matched_base_rules.push((
1398                                    layer,
1399                                    sel.specificity,
1400                                    order_counter,
1401                                    &rule.declarations,
1402                                ));
1403                            }
1404                        }
1405                    }
1406                }
1407            }
1408            matched_base_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1409            matched_interactive_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1410
1411            for sheet in stylesheets {
1412                for srule in &sheet.starting_styles {
1413                    if srule.selectors.iter().any(|sel| {
1414                        sel.matches_hierarchy_with_ancestor_states(
1415                            &elem_ref,
1416                            &ancestor_refs,
1417                            Some(&ancestor_states),
1418                            &sib_refs,
1419                            Some(&sib_states),
1420                            Some(is_last_element_child),
1421                            None,
1422                            &pseudo_state,
1423                        )
1424                    }) {
1425                        if style.starting_style.is_none() {
1426                            style.starting_style = Some(Box::new((*style).clone()));
1427                        }
1428                        if let Some(start_box) = style.starting_style.as_mut() {
1429                            for decl in &srule.declarations {
1430                                strata_style::CascadeSolver::apply_declaration(start_box, decl);
1431                            }
1432                        }
1433                    }
1434                }
1435            }
1436
1437            current_meta_opt = Some(CascadeElementMeta {
1438                tag: tag_name,
1439                classes: class_vec,
1440                id: id_val,
1441                attributes: attr_vec,
1442                pseudo_state,
1443            });
1444        }
1445
1446        let has_display_class = classes.iter().any(|c| {
1447            strata_style::tailwind::tokenize_classes(c)
1448                .into_iter()
1449                .any(|tok| {
1450                    let mut base = tok;
1451                    while let (Some(_), rest) = strata_style::tailwind::split_modifier(base) {
1452                        base = rest;
1453                    }
1454                    matches!(
1455                        base,
1456                        "flex"
1457                            | "grid"
1458                            | "block"
1459                            | "inline-flex"
1460                            | "inline-block"
1461                            | "inline"
1462                            | "hidden"
1463                            | "table"
1464                            | "inline-table"
1465                            | "table-row-group"
1466                            | "table-header-group"
1467                            | "table-footer-group"
1468                            | "table-row"
1469                            | "table-cell"
1470                            | "table-column-group"
1471                            | "table-column"
1472                            | "table-caption"
1473                    )
1474                })
1475        });
1476        let has_explicit_display_decl = inline_decls
1477            .iter()
1478            .any(|d| d.property.eq_ignore_ascii_case("display"))
1479            || matched_base_rules.iter().any(|(_, _, _, decls)| {
1480                decls
1481                    .iter()
1482                    .any(|d| d.property.eq_ignore_ascii_case("display"))
1483            })
1484            || matched_interactive_rules.iter().any(|(_, _, _, decls)| {
1485                decls
1486                    .iter()
1487                    .any(|d| d.property.eq_ignore_ascii_case("display"))
1488            });
1489
1490        if !has_display_class && !has_explicit_display_decl {
1491            match tag {
1492                Tag::Svg | Tag::Path | Tag::Input | Tag::Textarea => {}
1493                Tag::Table => {
1494                    style.display = Display::Table;
1495                }
1496                Tag::Thead => {
1497                    style.display = Display::TableHeaderGroup;
1498                }
1499                Tag::Tbody => {
1500                    style.display = Display::TableRowGroup;
1501                }
1502                Tag::Tr => {
1503                    style.display = Display::TableRow;
1504                }
1505                Tag::Th | Tag::Td => {
1506                    style.display = Display::TableCell;
1507                }
1508                Tag::Div
1509                | Tag::Main
1510                | Tag::Section
1511                | Tag::Header
1512                | Tag::Footer
1513                | Tag::Nav
1514                | Tag::Aside
1515                | Tag::Ul
1516                | Tag::Ol
1517                | Tag::Form => {
1518                    style.display = Display::Flex;
1519                    style.flex_direction = FlexDirection::Column;
1520                }
1521                Tag::P => {
1522                    style.display = Display::Block;
1523                }
1524                Tag::H1 | Tag::H2 | Tag::H3 | Tag::H4 | Tag::H5 | Tag::H6 => {
1525                    style.display = Display::Flex;
1526                    style.flex_direction = FlexDirection::Column;
1527                }
1528                Tag::Button => {
1529                    style.display = Display::InlineFlex;
1530                    style.align_items = strata_style::types::AlignItems::Center;
1531                    style.justify_content = strata_style::types::JustifyContent::Center;
1532                }
1533                Tag::Span => {
1534                    style.display = Display::Inline;
1535                }
1536                Tag::Img => {
1537                    style.display = Display::InlineBlock;
1538                }
1539                Tag::A => {
1540                    style.display = Display::Inline;
1541                    if style.text_decoration == strata_style::types::TextDecoration::None {
1542                        style.text_decoration = strata_style::types::TextDecoration::Underline;
1543                    }
1544                }
1545                _ => {
1546                    if let Tag::Custom(name) = tag {
1547                        if matches!(
1548                            name.to_ascii_lowercase().as_str(),
1549                            "code"
1550                                | "strong"
1551                                | "em"
1552                                | "b"
1553                                | "i"
1554                                | "u"
1555                                | "s"
1556                                | "small"
1557                                | "mark"
1558                                | "kbd"
1559                                | "samp"
1560                                | "var"
1561                                | "abbr"
1562                                | "cite"
1563                                | "q"
1564                                | "sub"
1565                                | "sup"
1566                                | "del"
1567                                | "ins"
1568                                | "time"
1569                        ) {
1570                            style.display = Display::Inline;
1571                        } else {
1572                            style.display = Display::Flex;
1573                            if name.eq_ignore_ascii_case("portal") {
1574                                style.flex_direction = FlexDirection::Column;
1575                            }
1576                        }
1577                    } else {
1578                        style.display = Display::Flex;
1579                    }
1580                }
1581            }
1582        } else if matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal"))
1583            && matches!(style.display, Display::Flex | Display::InlineFlex)
1584        {
1585            let has_explicit_flex_dir = classes.iter().any(|c| {
1586                c.split_whitespace().any(|tok| {
1587                    matches!(
1588                        tok,
1589                        "flex-row" | "flex-row-reverse" | "flex-col" | "flex-col-reverse"
1590                    )
1591                })
1592            }) || inline_decls
1593                .iter()
1594                .any(|d| d.property.eq_ignore_ascii_case("flex-direction"));
1595            if !has_explicit_flex_dir {
1596                style.flex_direction = FlexDirection::Column;
1597            }
1598        }
1599
1600        for &(_, _, _, decls) in &matched_base_rules {
1601            for decl in decls {
1602                if decl.property.starts_with("--") && !decl.important {
1603                    strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1604                }
1605            }
1606        }
1607        for decl in &inline_decls {
1608            if decl.property.starts_with("--") && !decl.important {
1609                strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1610            }
1611        }
1612
1613        for &(_, _, _, decls) in &matched_base_rules {
1614            for decl in decls {
1615                if !decl.property.starts_with("--") && !decl.important {
1616                    strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1617                }
1618            }
1619        }
1620
1621        Self::apply_base_tailwind_classes(&mut style, classes, &pseudo_state);
1622
1623        if let Some(cs) = direct_computed_override {
1624            *style = cs.clone();
1625        }
1626        for attr in attributes {
1627            if let strata_dom::Attribute::Property { key, value } = attr {
1628                if key.eq_ignore_ascii_case("href") && !value.is_empty() {
1629                    let val_atom = strata_primitives::atom::intern(value);
1630                    style.set_custom_property(strata_primitives::AtomId::HREF, val_atom);
1631                    if matches!(tag, Tag::A)
1632                        && style.color == strata_style::types::Color::new(0, 0, 0, 255)
1633                    {
1634                        style.color = strata_style::types::Color::new(37, 99, 235, 255);
1635                    }
1636                } else if key.eq_ignore_ascii_case("colspan") {
1637                    if let Ok(cs) = value.parse::<u32>() {
1638                        style.colspan = cs.max(1);
1639                    }
1640                } else if key.eq_ignore_ascii_case("rowspan") {
1641                    if let Ok(rs) = value.parse::<u32>() {
1642                        style.rowspan = rs.max(1);
1643                    }
1644                }
1645            }
1646        }
1647        for decl in &inline_decls {
1648            if !decl.property.starts_with("--") && !decl.important {
1649                strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1650            }
1651        }
1652
1653        for &(_, _, _, decls) in &matched_interactive_rules {
1654            for decl in decls {
1655                if decl.property.starts_with("--") && !decl.important {
1656                    strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1657                }
1658            }
1659        }
1660        for &(_, _, _, decls) in &matched_interactive_rules {
1661            for decl in decls {
1662                if !decl.property.starts_with("--") && !decl.important {
1663                    strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1664                }
1665            }
1666        }
1667
1668        Self::apply_interactive_tailwind_classes(&mut style, classes, &pseudo_state);
1669
1670        if !matched_base_rules.is_empty() || !matched_interactive_rules.is_empty() {
1671            let mut important_rules: Vec<(
1672                u32,
1673                strata_style::Specificity,
1674                usize,
1675                &[strata_style::Declaration],
1676            )> = Vec::new();
1677            for &entry in matched_base_rules
1678                .iter()
1679                .chain(matched_interactive_rules.iter())
1680            {
1681                if entry.3.iter().any(|d| d.important) {
1682                    important_rules.push(entry);
1683                }
1684            }
1685            important_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1686            for &(_, _, _, decls) in &important_rules {
1687                for decl in decls {
1688                    if decl.important && decl.property.starts_with("--") {
1689                        strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1690                    }
1691                }
1692            }
1693            for &(_, _, _, decls) in &important_rules {
1694                for decl in decls {
1695                    if decl.important && !decl.property.starts_with("--") {
1696                        strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1697                    }
1698                }
1699            }
1700        }
1701        for decl in &inline_decls {
1702            if decl.important && decl.property.starts_with("--") {
1703                strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1704            }
1705        }
1706        for decl in &inline_decls {
1707            if decl.important && !decl.property.starts_with("--") {
1708                strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1709            }
1710        }
1711
1712        if matches!(tag, Tag::Button)
1713            && style.display == Display::Flex
1714            && style.width == Dimension::Auto
1715            && style.flex_grow == 0.0
1716        {
1717            style.display = Display::InlineFlex;
1718        }
1719
1720        (style, current_meta_opt)
1721    }
1722
1723    #[inline(never)]
1724    fn try_build_svg_leaf_node(
1725        blueprint: &NodeBlueprint,
1726        attributes: &[strata_dom::Attribute],
1727        style: &mut ComputedStyle,
1728        entity_id: strata_primitives::EntityId,
1729    ) -> Option<LayoutNode> {
1730        let mut view_box = (24.0f32, 24.0f32);
1731        let mut explicit_svg_w = None;
1732        let mut explicit_svg_h = None;
1733        for attr in attributes {
1734            if let strata_dom::Attribute::Property { key, value } = attr {
1735                if key == "viewBox" {
1736                    let parts: Vec<f32> = value
1737                        .split(|c: char| c.is_whitespace() || c == ',')
1738                        .filter(|s| !s.is_empty())
1739                        .filter_map(|s| s.parse::<f32>().ok())
1740                        .collect();
1741                    if parts.len() >= 4 {
1742                        view_box = (parts[2], parts[3]);
1743                    }
1744                } else if key == "width" {
1745                    if let Ok(w) = value.trim_end_matches("px").parse::<f32>() {
1746                        explicit_svg_w = Some(w);
1747                    }
1748                } else if key == "height" {
1749                    if let Ok(h) = value.trim_end_matches("px").parse::<f32>() {
1750                        explicit_svg_h = Some(h);
1751                    }
1752                }
1753            }
1754        }
1755
1756        let svg_items = Self::collect_svg_items_from_blueprint(
1757            blueprint,
1758            view_box,
1759            None,
1760            None,
1761            2.0,
1762            strata_layout::StrokeLineCap::Round,
1763            strata_layout::StrokeLineJoin::Round,
1764            Vec::new(),
1765            strata_layout::FillRule::NonZero,
1766            style.color,
1767        );
1768
1769        if svg_items.is_empty() {
1770            return None;
1771        }
1772
1773        if style.width == Dimension::Auto {
1774            style.width = Dimension::Px(explicit_svg_w.unwrap_or(if view_box.0 > 24.0 {
1775                view_box.0.min(80.0)
1776            } else {
1777                16.0
1778            }));
1779        }
1780        if style.height == Dimension::Auto {
1781            style.height = Dimension::Px(explicit_svg_h.unwrap_or(if view_box.1 > 24.0 {
1782                view_box.1.min(80.0)
1783            } else {
1784                16.0
1785            }));
1786        }
1787        Some(LayoutNode::with_svg_items(style.clone(), svg_items).with_entity_id(entity_id))
1788    }
1789
1790    /// Standard bullet glyph (`U+2022`) rendered in place of characters for `<input type="password">`.
1791    pub(crate) const PASSWORD_MASK_CHAR: char = '\u{2022}';
1792
1793    /// Returns `true` when an element's attributes include `type="password"` (case-insensitive).
1794    pub(crate) fn is_password_input_attrs(attributes: &[strata_dom::Attribute]) -> bool {
1795        attributes.iter().any(|attr| {
1796            matches!(
1797                attr,
1798                strata_dom::Attribute::Property { key, value }
1799                    if key.eq_ignore_ascii_case("type")
1800                        && value.trim().eq_ignore_ascii_case("password")
1801            )
1802        })
1803    }
1804
1805    /// Replaces each Unicode scalar value in `text` with [`Self::PASSWORD_MASK_CHAR`] (`•`),
1806    /// preserving exact 1-to-1 character indexing with `TextInputState`.
1807    pub(crate) fn mask_password_text(text: &str) -> String {
1808        let count = text.chars().count();
1809        let mut masked = String::with_capacity(count * Self::PASSWORD_MASK_CHAR.len_utf8());
1810        for _ in 0..count {
1811            masked.push(Self::PASSWORD_MASK_CHAR);
1812        }
1813        masked
1814    }
1815
1816    #[inline(never)]
1817    fn build_input_leaf_node(
1818        blueprint: &NodeBlueprint,
1819        is_textarea: bool,
1820        attributes: &[strata_dom::Attribute],
1821        mut style: ComputedStyle,
1822        entity_id: strata_primitives::EntityId,
1823    ) -> LayoutNode {
1824        if style.cursor == strata_style::types::Cursor::Default {
1825            style.cursor = strata_style::types::Cursor::Text;
1826        }
1827        style.white_space = if is_textarea {
1828            strata_style::types::WhiteSpace::PreWrap
1829        } else {
1830            strata_style::types::WhiteSpace::NoWrap
1831        };
1832        style.overflow_x = strata_style::types::Overflow::Hidden;
1833        if is_textarea {
1834            if style.overflow_y == strata_style::types::Overflow::Visible {
1835                style.overflow_y = strata_style::types::Overflow::Auto;
1836            }
1837        } else {
1838            style.overflow_y = strata_style::types::Overflow::Hidden;
1839        }
1840        let is_password = !is_textarea && Self::is_password_input_attrs(attributes);
1841        let mut value_text = None;
1842        let mut placeholder_text = None;
1843        let mut rows_attr: Option<usize> = None;
1844        let mut cols_attr: Option<usize> = None;
1845        for attr in attributes {
1846            if let strata_dom::Attribute::Property { key, value } = attr {
1847                if key == "value" && !value.is_empty() {
1848                    value_text = Some(value.clone());
1849                } else if key == "placeholder" && !value.is_empty() {
1850                    placeholder_text = Some(value.clone());
1851                } else if key == "rows" {
1852                    rows_attr = value.trim().parse::<usize>().ok().filter(|&r| r > 0);
1853                } else if key == "cols" {
1854                    cols_attr = value.trim().parse::<usize>().ok().filter(|&c| c > 0);
1855                }
1856            }
1857        }
1858        if is_textarea && value_text.is_none() {
1859            let child_text = Self::extract_text_content(blueprint);
1860            if !child_text.is_empty() {
1861                value_text = Some(child_text);
1862            }
1863        }
1864        let is_mono = strata_layout::is_monospace_family(style.font_family);
1865        let char_w = if is_mono {
1866            style.font_size * 0.60
1867        } else {
1868            style.font_size * 0.55
1869        };
1870        if style.height == Dimension::Auto {
1871            let line_count = if is_textarea {
1872                rows_attr.unwrap_or(3) as f32
1873            } else {
1874                1.0
1875            };
1876            let text_h = style.font_size * style.line_height * line_count;
1877            style.height = Dimension::Px(
1878                text_h
1879                    + style.padding.top
1880                    + style.padding.bottom
1881                    + style.border_width.top
1882                    + style.border_width.bottom,
1883            );
1884        }
1885        let border_h = style.border_width.left + style.border_width.right;
1886        if let Some(val) = value_text {
1887            let display_val = if is_password {
1888                Self::mask_password_text(&val)
1889            } else {
1890                val
1891            };
1892            let max_chars = if is_textarea {
1893                display_val
1894                    .lines()
1895                    .map(|l| l.chars().count())
1896                    .max()
1897                    .unwrap_or(0)
1898            } else {
1899                display_val.chars().count()
1900            };
1901            let approx_width = if is_textarea {
1902                cols_attr
1903                    .map(|c| c as f32 * char_w)
1904                    .unwrap_or_else(|| (max_chars as f32 * char_w).max(200.0))
1905            } else {
1906                (max_chars as f32 * char_w).max(40.0)
1907            };
1908            if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1909                style.width = Dimension::Px(
1910                    approx_width + style.padding.left + style.padding.right + border_h,
1911                );
1912            }
1913            LayoutNode::with_text(style, display_val).with_entity_id(entity_id)
1914        } else if let Some(ph) = placeholder_text {
1915            let approx_width = if is_textarea {
1916                cols_attr
1917                    .map(|c| c as f32 * char_w)
1918                    .unwrap_or_else(|| (ph.chars().count() as f32 * char_w).max(200.0))
1919            } else {
1920                (ph.chars().count() as f32 * char_w).max(40.0)
1921            };
1922            if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1923                style.width = Dimension::Px(
1924                    approx_width + style.padding.left + style.padding.right + border_h,
1925                );
1926            }
1927            style.color = strata_style::types::Color::new(140, 145, 155, 255);
1928            LayoutNode::with_text(style, ph).with_entity_id(entity_id)
1929        } else {
1930            let default_w = if is_textarea {
1931                cols_attr.map(|c| c as f32 * char_w).unwrap_or(200.0)
1932            } else {
1933                60.0
1934            };
1935            if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1936                style.width =
1937                    Dimension::Px(default_w + style.padding.left + style.padding.right + border_h);
1938            }
1939            LayoutNode::with_text(style, String::new()).with_entity_id(entity_id)
1940        }
1941    }
1942
1943    #[inline(never)]
1944    fn try_build_img_leaf_node(
1945        attributes: &[strata_dom::Attribute],
1946        style: &mut ComputedStyle,
1947        entity_id: strata_primitives::EntityId,
1948    ) -> Option<LayoutNode> {
1949        let mut src_value = None;
1950        for attr in attributes {
1951            if let strata_dom::Attribute::Property { key, value } = attr {
1952                if key.eq_ignore_ascii_case("src") && !value.is_empty() {
1953                    src_value = Some(value.as_str());
1954                }
1955            }
1956        }
1957        let src = src_value?;
1958        let payload = data_uri_base64_payload(src)?;
1959        let decoded = decode_base64(payload)?;
1960        let (width, height) = png_dimensions(&decoded)?;
1961        if style.width == Dimension::Auto {
1962            style.width = Dimension::Px(width as f32);
1963        }
1964        if style.height == Dimension::Auto {
1965            style.height = Dimension::Px(height as f32);
1966        }
1967        if style.display == Display::Inline {
1968            style.display = Display::InlineBlock;
1969        }
1970        let image = strata_layout::ImageResource {
1971            data: std::sync::Arc::new(decoded),
1972            width,
1973            height,
1974        };
1975        Some(LayoutNode::with_image(style.clone(), image).with_entity_id(entity_id))
1976    }
1977
1978    #[inline(never)]
1979    fn apply_canvas3d_sizing_and_check_leaf(
1980        attributes: &[strata_dom::Attribute],
1981        children: &[NodeBlueprint],
1982        style: &mut ComputedStyle,
1983    ) -> bool {
1984        for attr in attributes {
1985            if let strata_dom::Attribute::Property { key, value } = attr {
1986                if key == "width" && style.width == Dimension::Auto {
1987                    if let Ok(w) = value.trim_end_matches("px").parse::<f32>() {
1988                        style.width = Dimension::Px(w);
1989                    }
1990                } else if key == "height" && style.height == Dimension::Auto {
1991                    if let Ok(h) = value.trim_end_matches("px").parse::<f32>() {
1992                        style.height = Dimension::Px(h);
1993                    }
1994                }
1995            }
1996        }
1997        let is_declarative_3d_child = |c: &NodeBlueprint| match c {
1998            NodeBlueprint::Element {
1999                tag: Tag::Custom(name),
2000                ..
2001            } => matches!(
2002                *name,
2003                "PerspectiveCamera"
2004                    | "OrthographicCamera"
2005                    | "AmbientLight"
2006                    | "DirectionalLight"
2007                    | "PointLight"
2008                    | "Mesh"
2009                    | "BoxGeometry"
2010                    | "SphereGeometry"
2011                    | "PlaneGeometry"
2012                    | "CylinderGeometry"
2013                    | "StandardMaterial"
2014                    | "ShaderMaterial"
2015            ),
2016            NodeBlueprint::Empty => true,
2017            _ => false,
2018        };
2019        let has_dom_overlay_children = children.iter().any(|c| !is_declarative_3d_child(c));
2020        if has_dom_overlay_children {
2021            return false;
2022        }
2023        attributes.iter().any(|a| {
2024            matches!(a, strata_dom::Attribute::ScenePayload(_))
2025                || matches!(a, strata_dom::Attribute::Property { key, value } if key == "data-strata-canvas3d" && value == "true")
2026        }) || children.iter().any(|c| match c {
2027            NodeBlueprint::Element { .. } => is_declarative_3d_child(c),
2028            _ => false,
2029        })
2030    }
2031
2032    #[inline(never)]
2033    pub(crate) fn apply_single_text_inline_intrinsic_sizing(
2034        style: &mut ComputedStyle,
2035        children: &[NodeBlueprint],
2036    ) {
2037        // Non-replaced `display: inline` elements (e.g. `<span>`, `<a>`, `<label>`)
2038        // must remain `width: auto; height: auto` so their inline text wraps to
2039        // whatever width their containing block, flex item (`flex-1 min-w-0`), or
2040        // grid track resolves to. Only atomic inline containers (`inline-flex` /
2041        // `inline-block`) that are not flexible (`flex-grow == 0`) or explicitly
2042        // `min-w-0` should receive eager single-text intrinsic dimensions.
2043        let is_atomic_inline = matches!(
2044            style.display,
2045            Display::InlineFlex | Display::InlineBlock
2046        );
2047        let is_flexible_or_min_zero =
2048            style.flex_grow > 0.0 || matches!(style.min_width, Dimension::Px(px) if px == 0.0);
2049        if is_atomic_inline
2050            && !is_flexible_or_min_zero
2051            && style.width == Dimension::Auto
2052            && children.len() == 1
2053        {
2054            let single_text: Option<std::borrow::Cow<'_, str>> = match &children[0] {
2055                NodeBlueprint::Text(t) => Some(std::borrow::Cow::Borrowed(t.as_str())),
2056                NodeBlueprint::DynamicText(dyn_fn) => Some(std::borrow::Cow::Owned(dyn_fn())),
2057                _ => None,
2058            };
2059            if let Some(t) = single_text {
2060                let is_mono = strata_layout::is_monospace_family(style.font_family);
2061                let (text_w, raw_h) = strata_layout::measure_text_bounds_styled_with_family(
2062                    &t,
2063                    style.font_size,
2064                    style.line_height,
2065                    None,
2066                    is_mono,
2067                    style.font_family,
2068                    style.font_weight,
2069                    style.font_style,
2070                );
2071                let total_w = (text_w
2072                    + style.padding.left
2073                    + style.padding.right
2074                    + style.border_width.left
2075                    + style.border_width.right)
2076                    .ceil();
2077                style.width = Dimension::Px(total_w);
2078                if style.height == Dimension::Auto {
2079                    let total_h = raw_h
2080                        + style.padding.top
2081                        + style.padding.bottom
2082                        + style.border_width.top
2083                        + style.border_width.bottom;
2084                    style.height = Dimension::Px(total_h);
2085                }
2086            }
2087        }
2088    }
2089}