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