1use super::*;
4
5impl AppRuntime {
6 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 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 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 let max_build_depth = if cfg!(debug_assertions) { 128 } else { 256 };
505 if current_path.len() >= max_build_depth {
506 let style = match parent_style {
507 Some(p) => ComputedStyle::inherit_from(p),
508 None => ComputedStyle::default(),
509 };
510 return LayoutNode::new(style);
511 }
512 match blueprint {
513 NodeBlueprint::Element {
514 tag,
515 classes,
516 attributes,
517 children,
518 ..
519 } => {
520 let entity_id = blueprint
521 .entity_id()
522 .unwrap_or(strata_primitives::EntityId::NONE);
523
524 if Self::is_style_tag(tag) {
527 let mut style = ComputedStyle::default();
528 style.display = Display::None;
529 return LayoutNode::new(style).with_entity_id(entity_id);
530 }
531
532 let (mut style, current_meta_opt) = Self::resolve_element_cascade_style(
533 tag,
534 classes,
535 attributes,
536 parent_style,
537 current_path,
538 ctx,
539 stylesheets,
540 ancestors,
541 preceding_siblings,
542 is_last_element_child,
543 group_state,
544 );
545
546 Self::apply_top_layer_position_override(tag, attributes, &mut style);
547
548 if matches!(tag, Tag::Svg | Tag::Path) {
551 if let Some(mut svg_node) =
552 Self::try_build_svg_leaf_node(blueprint, attributes, &mut style, entity_id)
553 {
554 Self::apply_portal_and_anchor_metadata(&mut svg_node, tag, attributes);
555 return svg_node;
556 }
557 }
558
559 if matches!(tag, Tag::Input | Tag::Textarea) {
561 let mut input_node = Self::build_input_leaf_node(
562 blueprint,
563 matches!(tag, Tag::Textarea),
564 attributes,
565 *style,
566 entity_id,
567 );
568 Self::apply_portal_and_anchor_metadata(&mut input_node, tag, attributes);
569 return input_node;
570 }
571
572 if matches!(tag, Tag::Img) {
575 if let Some(mut img_node) =
576 Self::try_build_img_leaf_node(attributes, &mut style, entity_id)
577 {
578 Self::apply_portal_and_anchor_metadata(&mut img_node, tag, attributes);
579 return img_node;
580 }
581 }
582
583 let canvas2d_payload = attributes.iter().find_map(|attr| {
585 if let strata_dom::Attribute::ScenePayload(payload) = attr {
586 if payload
587 .downcast_ref::<Vec<strata_render::canvas2d::CanvasCommand>>()
588 .is_some()
589 || payload
590 .downcast_ref::<std::sync::Arc<
591 Vec<strata_render::canvas2d::CanvasCommand>,
592 >>()
593 .is_some()
594 || payload
595 .downcast_ref::<strata_render::canvas2d::Canvas2DPaintCallback>()
596 .is_some()
597 {
598 return Some(std::sync::Arc::clone(payload));
599 }
600 }
601 None
602 });
603 if (canvas2d_payload.is_some()
604 || matches!(tag, Tag::Canvas)
605 || matches!(tag, Tag::Custom("Canvas3D" | "Canvas2D")))
606 && Self::apply_canvas3d_sizing_and_check_leaf(attributes, children, &mut style)
607 {
608 let mut canvas_node = LayoutNode::new(*style).with_entity_id(entity_id);
609 if let Some(payload) = canvas2d_payload {
610 canvas_node.scene_3d = Some(strata_layout::ViewportSceneHandle(payload));
611 } else if let Some(scene_arc) =
612 strata_render::scene3d::extract_scene3d_arc_from_blueprint(blueprint)
613 {
614 canvas_node.scene_3d =
615 Some(strata_layout::ViewportSceneHandle(scene_arc));
616 }
617 Self::apply_portal_and_anchor_metadata(&mut canvas_node, tag, attributes);
618 return canvas_node;
619 }
620
621 Self::apply_single_text_inline_intrinsic_sizing(&mut style, children);
622
623 let child_group_state = if Self::classes_have_group_marker(classes) {
624 let self_hovered = ctx
625 .hovered_path
626 .is_some_and(|h| h.starts_with(current_path));
627 let self_focused = ctx
628 .focused_path
629 .is_some_and(|f| f.starts_with(current_path));
630 let self_active = self_hovered && ctx.is_mouse_down;
631 (
632 group_state.0 || self_hovered,
633 group_state.1 || self_focused,
634 group_state.2 || self_active,
635 )
636 } else {
637 group_state
638 };
639
640 let pushed_ancestor = if let Some(meta) = current_meta_opt {
641 ancestors.push(meta);
642 true
643 } else {
644 false
645 };
646
647 let child_nodes = Self::build_flattened_children_full(
648 children,
649 Some(&style),
650 current_path,
651 ctx,
652 stylesheets,
653 ancestors,
654 child_group_state,
655 );
656
657 if pushed_ancestor {
658 ancestors.pop();
659 }
660
661 let mut node =
662 LayoutNode::with_children(*style, child_nodes).with_entity_id(entity_id);
663 if let Some(payload) = canvas2d_payload {
664 node.scene_3d = Some(strata_layout::ViewportSceneHandle(payload));
665 } else if matches!(tag, Tag::Canvas | Tag::Custom("Canvas3D")) {
666 if let Some(scene_arc) =
667 strata_render::scene3d::extract_scene3d_arc_from_blueprint(blueprint)
668 {
669 node.scene_3d = Some(strata_layout::ViewportSceneHandle(scene_arc));
670 }
671 } else {
672 for attr in attributes {
673 if let strata_dom::Attribute::ScenePayload(payload) = attr {
674 node.scene_3d = Some(strata_layout::ViewportSceneHandle(
675 std::sync::Arc::clone(payload),
676 ));
677 break;
678 }
679 }
680 }
681 Self::apply_portal_and_anchor_metadata(&mut node, tag, attributes);
682 node
683 }
684 NodeBlueprint::Text(text) => {
685 Self::build_text_leaf_layout_node(text.clone(), parent_style)
686 }
687 NodeBlueprint::DynamicText(dyn_fn) => {
688 Self::build_text_leaf_layout_node(dyn_fn(), parent_style)
689 }
690 NodeBlueprint::Fragment(children) => {
691 let mut style = Box::new(match parent_style {
692 Some(p) => ComputedStyle::inherit_from(p),
693 None => ComputedStyle::default(),
694 });
695 style.display = Display::Flex;
696 style.flex_direction = FlexDirection::Column;
697
698 let child_nodes = Self::build_flattened_children_full(
699 children,
700 Some(&style),
701 current_path,
702 ctx,
703 stylesheets,
704 ancestors,
705 group_state,
706 );
707
708 LayoutNode::with_children(*style, child_nodes)
709 }
710 NodeBlueprint::Empty => Self::build_empty_leaf_layout_node(),
711 }
712 }
713
714 #[inline(never)]
715 pub(crate) fn build_text_leaf_layout_node(
716 text: String,
717 parent_style: Option<&ComputedStyle>,
718 ) -> LayoutNode {
719 let mut style = match parent_style {
720 Some(p) => ComputedStyle::inherit_from(p),
721 None => ComputedStyle::default(),
722 };
723 style.display = Display::Inline;
724 let is_mono = strata_layout::is_monospace_family(style.font_family);
725 let (w, h) = strata_layout::measure_text_bounds_styled_with_family(
726 &text,
727 style.font_size,
728 style.line_height,
729 None,
730 is_mono,
731 style.font_family,
732 style.font_weight,
733 style.font_style,
734 );
735 style.width = Dimension::Px(w.ceil());
736 style.height = Dimension::Px(h);
737 LayoutNode::with_text(style, text)
738 }
739
740 #[inline(never)]
741 fn build_empty_leaf_layout_node() -> LayoutNode {
742 let mut style = ComputedStyle::default();
743 style.display = Display::None;
744 LayoutNode::new(style)
745 }
746
747 #[allow(clippy::too_many_arguments)]
748 fn build_flattened_children_full(
749 children: &[NodeBlueprint],
750 parent_style: Option<&ComputedStyle>,
751 parent_path: &mut Vec<usize>,
752 ctx: &InteractionContext,
753 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
754 ancestors: &mut Vec<CascadeElementMeta>,
755 group_state: (bool, bool, bool),
756 ) -> Vec<LayoutNode> {
757 if parent_path.len() >= 256 {
758 return Vec::new();
759 }
760 let mut flat = Vec::with_capacity(children.len());
761 for child in children {
762 Self::flatten_blueprints(child, &mut flat);
763 }
764
765 let last_elem_flat_idx = if !stylesheets.is_empty() {
766 flat.iter().rposition(
767 |bp| matches!(bp, NodeBlueprint::Element { tag, .. } if !Self::is_style_tag(tag)),
768 )
769 } else {
770 None
771 };
772
773 let mut out = Vec::with_capacity(flat.len());
774 let mut preceding_siblings: Vec<CascadeElementMeta> = Vec::new();
775
776 for (idx, child_bp) in flat.into_iter().enumerate() {
777 parent_path.push(idx);
778 let is_last_elem = last_elem_flat_idx == Some(idx);
779 let node = Self::build_layout_tree_full(
780 child_bp,
781 parent_style,
782 parent_path,
783 ctx,
784 stylesheets,
785 ancestors,
786 &preceding_siblings,
787 is_last_elem,
788 group_state,
789 );
790 if !stylesheets.is_empty() {
791 if let NodeBlueprint::Element {
792 tag,
793 classes,
794 attributes,
795 ..
796 } = child_bp
797 {
798 if !Self::is_style_tag(tag) {
799 let is_hovered =
800 ctx.hovered_path.is_some_and(|h| h.starts_with(parent_path));
801 let is_focused =
802 ctx.focused_path.is_some_and(|f| f.starts_with(parent_path));
803 let is_active = is_hovered && ctx.is_mouse_down;
804 let is_disabled = attributes.iter().any(|attr| match attr {
805 strata_dom::Attribute::Property { key, value } => {
806 key.eq_ignore_ascii_case("disabled")
807 && !value.eq_ignore_ascii_case("false")
808 }
809 _ => false,
810 });
811 let (class_vec, id_val, attr_vec) =
812 Self::extract_element_selector_meta(classes, attributes);
813 preceding_siblings.push(CascadeElementMeta {
814 tag: Self::tag_as_str(tag),
815 classes: class_vec,
816 id: id_val,
817 attributes: attr_vec,
818 pseudo_state: strata_style::selector::PseudoState {
819 is_hovered,
820 is_focused,
821 is_active,
822 is_disabled,
823 is_dark: ctx.is_dark_mode,
824 is_group_hovered: group_state.0,
825 is_group_focused: group_state.1,
826 is_group_active: group_state.2,
827 },
828 });
829 }
830 }
831 }
832 parent_path.pop();
833 out.push(node);
834 }
835 out
836 }
837
838 pub(crate) fn append_child_layout_nodes_with_interaction_context(
840 blueprint: &NodeBlueprint,
841 parent_style: Option<&ComputedStyle>,
842 parent_path: &mut Vec<usize>,
843 child_counter: &mut usize,
844 ctx: &InteractionContext,
845 out: &mut Vec<LayoutNode>,
846 ) {
847 if parent_path.len() >= 256 {
848 return;
849 }
850 if let NodeBlueprint::Fragment(children) = blueprint {
851 for child in children {
852 Self::append_child_layout_nodes_with_interaction_context(
853 child,
854 parent_style,
855 parent_path,
856 child_counter,
857 ctx,
858 out,
859 );
860 }
861 } else {
862 let this_idx = *child_counter;
863 *child_counter += 1;
864 parent_path.push(this_idx);
865 let node = Self::build_layout_tree_with_interaction_context(
866 blueprint,
867 parent_style,
868 parent_path,
869 ctx,
870 );
871 parent_path.pop();
872 out.push(node);
873 }
874 }
875
876 pub(crate) fn append_child_layout_nodes_with_context(
878 blueprint: &NodeBlueprint,
879 parent_style: Option<&ComputedStyle>,
880 parent_path: &mut Vec<usize>,
881 child_counter: &mut usize,
882 hovered_path: Option<&[usize]>,
883 out: &mut Vec<LayoutNode>,
884 ) {
885 let ctx = InteractionContext {
886 hovered_path,
887 ..Default::default()
888 };
889 Self::append_child_layout_nodes_with_interaction_context(
890 blueprint,
891 parent_style,
892 parent_path,
893 child_counter,
894 &ctx,
895 out,
896 );
897 }
898
899 pub fn append_child_layout_nodes(
901 blueprint: &NodeBlueprint,
902 parent_style: Option<&ComputedStyle>,
903 out: &mut Vec<LayoutNode>,
904 ) {
905 let mut path_buf = Vec::new();
906 let mut child_counter = out.len();
907 Self::append_child_layout_nodes_with_context(
908 blueprint,
909 parent_style,
910 &mut path_buf,
911 &mut child_counter,
912 None,
913 out,
914 );
915 }
916
917 pub(crate) fn flatten_blueprints<'a>(bp: &'a NodeBlueprint, out: &mut Vec<&'a NodeBlueprint>) {
919 let mut stack = vec![bp];
920 while let Some(current) = stack.pop() {
921 if let NodeBlueprint::Fragment(children) = current {
922 for c in children.iter().rev() {
923 stack.push(c);
924 }
925 } else {
926 out.push(current);
927 }
928 }
929 }
930
931 fn extract_inline_style_decl(style_raw: &str, target_prop: &str) -> Option<String> {
932 for decl in style_raw.split(';') {
933 if let Some((k, v)) = decl.split_once(':') {
934 if k.trim().eq_ignore_ascii_case(target_prop) {
935 let val = v.trim().trim_end_matches("!important").trim();
936 if !val.is_empty() && !val.eq_ignore_ascii_case("none") {
937 return Some(val.trim_matches('"').trim_matches('\'').to_string());
938 }
939 }
940 }
941 }
942 None
943 }
944
945 #[inline(never)]
946 fn apply_top_layer_position_override(
947 tag: &Tag,
948 attributes: &[strata_dom::Attribute],
949 style: &mut ComputedStyle,
950 ) {
951 if matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal")) {
952 style.position = strata_style::types::Position::Fixed;
953 return;
954 }
955 for attr in attributes {
956 if let strata_dom::Attribute::Property { key, value } = attr {
957 let k = key.trim();
958 let v = value.trim();
959 match k {
960 "data-portal" => {
961 if !matches!(
962 v.to_ascii_lowercase().as_str(),
963 "false" | "0" | "no" | "off"
964 ) {
965 style.position = strata_style::types::Position::Fixed;
966 return;
967 }
968 }
969 "popover" => {
970 style.position = strata_style::types::Position::Fixed;
971 return;
972 }
973 "data-portal-anchor" | "anchor" | "position-anchor" if !v.is_empty() => {
974 style.position = strata_style::types::Position::Fixed;
975 return;
976 }
977 "style" => {
978 if Self::extract_inline_style_decl(v, "position-anchor").is_some() {
979 style.position = strata_style::types::Position::Fixed;
980 return;
981 }
982 }
983 _ => {}
984 }
985 }
986 }
987 }
988
989 #[inline(never)]
990 pub(crate) fn apply_portal_and_anchor_metadata(
991 node: &mut LayoutNode,
992 tag: &Tag,
993 attributes: &[strata_dom::Attribute],
994 ) {
995 let is_portal_tag = matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal"));
996 if !is_portal_tag && attributes.is_empty() {
997 return;
998 }
999
1000 let mut element_id: Option<String> = None;
1001 let mut anchor_name: Option<String> = None;
1002 let mut is_portal_attr = false;
1003 let mut anchor_target: Option<String> = None;
1004 let mut placement_raw: Option<String> = None;
1005 let mut offset_opt: Option<f32> = None;
1006 let mut flip_opt: Option<bool> = None;
1007 let mut shift_opt: Option<bool> = None;
1008 let mut padding_opt: Option<f32> = None;
1009 let mut match_width_opt: Option<bool> = None;
1010 let mut min_width_from_anchor_opt: Option<bool> = None;
1011 let mut inline_style_raw: Option<&str> = None;
1012
1013 for attr in attributes {
1014 if let strata_dom::Attribute::Property { key, value } = attr {
1015 let k = key.trim();
1016 let v = value.trim();
1017 match k {
1018 "id" | "data-anchor-id" => {
1019 if !v.is_empty() {
1020 element_id = Some(v.to_string());
1021 }
1022 }
1023 "data-anchor-name" | "anchor-name" => {
1024 if !v.is_empty() {
1025 anchor_name = Some(v.to_string());
1026 }
1027 }
1028 "data-portal" => {
1029 is_portal_attr = !matches!(
1030 v.to_ascii_lowercase().as_str(),
1031 "false" | "0" | "no" | "off"
1032 );
1033 }
1034 "popover" => {
1035 is_portal_attr = true;
1036 }
1037 "data-portal-anchor" | "anchor" | "position-anchor" => {
1038 if !v.is_empty() {
1039 anchor_target = Some(v.to_string());
1040 }
1041 }
1042 "data-portal-placement" | "placement" | "position-area" | "inset-area" => {
1043 if !v.is_empty() {
1044 placement_raw = Some(v.to_string());
1045 }
1046 }
1047 "data-portal-offset" => {
1048 if let Ok(parsed) = v.trim_end_matches("px").trim().parse::<f32>() {
1049 offset_opt = Some(parsed);
1050 }
1051 }
1052 "data-portal-flip" => {
1053 flip_opt = Some(!matches!(
1054 v.to_ascii_lowercase().as_str(),
1055 "false" | "0" | "no" | "off"
1056 ));
1057 }
1058 "data-portal-shift" => {
1059 shift_opt = Some(!matches!(
1060 v.to_ascii_lowercase().as_str(),
1061 "false" | "0" | "no" | "off"
1062 ));
1063 }
1064 "data-portal-padding" => {
1065 if let Ok(parsed) = v.trim_end_matches("px").trim().parse::<f32>() {
1066 padding_opt = Some(parsed);
1067 }
1068 }
1069 "data-portal-match-width" => {
1070 match_width_opt = Some(matches!(
1071 v.to_ascii_lowercase().as_str(),
1072 "true" | "1" | "yes" | "on"
1073 ));
1074 }
1075 "data-portal-min-width" => {
1076 min_width_from_anchor_opt = Some(matches!(
1077 v.to_ascii_lowercase().as_str(),
1078 "true" | "1" | "yes" | "on"
1079 ));
1080 }
1081 "style" => {
1082 inline_style_raw = Some(v);
1083 }
1084 _ => {}
1085 }
1086 }
1087 }
1088
1089 if let Some(style_str) = inline_style_raw {
1090 if anchor_name.is_none() {
1091 anchor_name = Self::extract_inline_style_decl(style_str, "anchor-name");
1092 }
1093 if anchor_target.is_none() {
1094 anchor_target = Self::extract_inline_style_decl(style_str, "position-anchor");
1095 }
1096 if placement_raw.is_none() {
1097 placement_raw = Self::extract_inline_style_decl(style_str, "position-area")
1098 .or_else(|| Self::extract_inline_style_decl(style_str, "inset-area"));
1099 }
1100 }
1101
1102 let portal_anchor = anchor_target.map(|anchor_id| {
1103 let placement = placement_raw
1104 .as_deref()
1105 .and_then(strata_layout::AnchorPlacement::parse)
1106 .unwrap_or(strata_layout::AnchorPlacement::BottomEnd);
1107 Box::new(strata_layout::PortalAnchorSpec {
1108 anchor_id,
1109 placement,
1110 offset: offset_opt.unwrap_or(4.0),
1111 flip: flip_opt.unwrap_or(true),
1112 shift: shift_opt.unwrap_or(true),
1113 viewport_padding: padding_opt.unwrap_or(8.0),
1114 match_width: match_width_opt.unwrap_or(false),
1115 min_width_from_anchor: min_width_from_anchor_opt.unwrap_or(false),
1116 })
1117 });
1118
1119 node.element_id = element_id;
1120 node.anchor_name = anchor_name;
1121 node.is_top_layer = is_portal_tag || is_portal_attr || portal_anchor.is_some();
1122 node.portal_anchor = portal_anchor;
1123 }
1124
1125 pub fn rebuild_layout_tree(&mut self) {
1127 self.applied_scroll_offsets.clear();
1128 self.applied_portal_offsets.clear();
1129 let stylesheets = Self::collect_stylesheets_from_blueprint(&self.root_blueprint);
1130 for sheet in &stylesheets {
1131 self.register_keyframes_stylesheet(sheet);
1132 }
1133 let rebuild_start = std::time::Instant::now();
1134 let ctx = self.interaction_context();
1135 self.layout_root = Self::build_layout_tree_with_interaction(&self.root_blueprint, &ctx);
1136 self.sync_active_input_layout();
1137 let now_ms = self.runtime_start_epoch.elapsed().as_secs_f64() * 1000.0;
1138 self.sync_tree_animations(now_ms);
1139 let compute_start = std::time::Instant::now();
1140 self.frame_profile.rebuild += compute_start.duration_since(rebuild_start);
1141 self.layout_root
1142 .compute_layout(self.viewport_width, self.viewport_height);
1143 Self::sync_layout_to_ir(&self.layout_root, &mut self.ir_graph);
1144 self.layout_computations += 1;
1145 self.frame_profile.layout += compute_start.elapsed();
1146 if perf_logging_enabled() {
1147 perf_log_ms(
1148 "compute_layout_rebuild",
1149 compute_start,
1150 format!(
1151 "{} layout nodes",
1152 perf_count_layout_nodes(&self.layout_root)
1153 ),
1154 );
1155 }
1156 self.apply_viewport_clamps();
1157 self.apply_scroll_offsets();
1158 self.dispatch_resize_observers();
1159 self.spatial_index
1160 .rebuild(&self.root_blueprint, &self.layout_root);
1161 self.compile_display_list();
1162 }
1163
1164 pub fn layout_compute_count(&self) -> u64 {
1166 self.layout_computations
1167 }
1168
1169 pub fn find_layout_node_mut<'a>(
1171 root: &'a mut LayoutNode,
1172 path: &[usize],
1173 ) -> Option<&'a mut LayoutNode> {
1174 let mut cur = root;
1175 for &idx in path {
1176 if idx >= cur.children.len() {
1177 return None;
1178 }
1179 cur = &mut cur.children[idx];
1180 }
1181 Some(cur)
1182 }
1183
1184 pub fn collect_dynamic_text_bindings(
1186 blueprint: &NodeBlueprint,
1187 parent_path: &mut Vec<usize>,
1188 bindings: &mut Vec<DynamicTextBinding>,
1189 ) {
1190 if parent_path.len() >= 256 {
1191 return;
1192 }
1193 match blueprint {
1194 NodeBlueprint::Element { children, .. } => {
1195 let mut child_counter = 0;
1196 for child in children {
1197 Self::collect_child_dynamic_text_bindings(
1198 child,
1199 parent_path,
1200 &mut child_counter,
1201 bindings,
1202 );
1203 }
1204 }
1205 NodeBlueprint::Fragment(children) => {
1206 let mut child_counter = 0;
1207 for child in children {
1208 Self::collect_child_dynamic_text_bindings(
1209 child,
1210 parent_path,
1211 &mut child_counter,
1212 bindings,
1213 );
1214 }
1215 }
1216 NodeBlueprint::DynamicText(f) => {
1217 let val = f();
1218 bindings.push(DynamicTextBinding {
1219 path: parent_path.clone(),
1220 closure: f.clone(),
1221 last_value: val,
1222 });
1223 }
1224 _ => {}
1225 }
1226 }
1227
1228 fn collect_child_dynamic_text_bindings(
1229 blueprint: &NodeBlueprint,
1230 parent_path: &mut Vec<usize>,
1231 child_counter: &mut usize,
1232 bindings: &mut Vec<DynamicTextBinding>,
1233 ) {
1234 if let NodeBlueprint::Fragment(children) = blueprint {
1235 for child in children {
1236 Self::collect_child_dynamic_text_bindings(
1237 child,
1238 parent_path,
1239 child_counter,
1240 bindings,
1241 );
1242 }
1243 } else {
1244 let this_idx = *child_counter;
1245 *child_counter += 1;
1246 parent_path.push(this_idx);
1247 Self::collect_dynamic_text_bindings(blueprint, parent_path, bindings);
1248 parent_path.pop();
1249 }
1250 }
1251
1252 #[inline(never)]
1253 #[allow(clippy::too_many_arguments)]
1254 fn resolve_element_cascade_style(
1255 tag: &Tag,
1256 classes: &strata_dom::ClassList,
1257 attributes: &[strata_dom::Attribute],
1258 parent_style: Option<&ComputedStyle>,
1259 current_path: &[usize],
1260 ctx: &InteractionContext,
1261 stylesheets: &[std::sync::Arc<strata_style::StyleSheet>],
1262 ancestors: &[CascadeElementMeta],
1263 preceding_siblings: &[CascadeElementMeta],
1264 is_last_element_child: bool,
1265 group_state: (bool, bool, bool),
1266 ) -> (Box<ComputedStyle>, Option<CascadeElementMeta>) {
1267 let is_hovered = ctx
1268 .hovered_path
1269 .is_some_and(|h| h.starts_with(current_path));
1270 let is_focused = ctx
1271 .focused_path
1272 .is_some_and(|f| f.starts_with(current_path));
1273 let is_active = is_hovered && ctx.is_mouse_down;
1274 let is_disabled = attributes.iter().any(|attr| match attr {
1275 strata_dom::Attribute::Property { key, value } => {
1276 key.eq_ignore_ascii_case("disabled") && !value.eq_ignore_ascii_case("false")
1277 }
1278 _ => false,
1279 });
1280 let is_dark = ctx.is_dark_mode;
1281 let pseudo_state = strata_style::selector::PseudoState {
1282 is_hovered,
1283 is_focused,
1284 is_active,
1285 is_disabled,
1286 is_dark,
1287 is_group_hovered: group_state.0,
1288 is_group_focused: group_state.1,
1289 is_group_active: group_state.2,
1290 };
1291 let mut style = Box::new(match parent_style {
1292 Some(p) => ComputedStyle::inherit_from(p),
1293 None => ComputedStyle::default(),
1294 });
1295
1296 let mut has_direct_style = false;
1297 let mut direct_computed_override: Option<&strata_style::types::ComputedStyle> = None;
1298 let mut inline_decls: Vec<strata_style::Declaration> = Vec::new();
1299 for attr in attributes {
1300 if let strata_dom::Attribute::DirectStyle(any) = attr {
1301 if let Some(decls) = any.downcast_ref::<Vec<strata_style::Declaration>>() {
1302 inline_decls.extend(decls.iter().cloned());
1303 has_direct_style = true;
1304 } else if let Some(cs) = any.downcast_ref::<strata_style::types::ComputedStyle>() {
1305 direct_computed_override = Some(cs);
1306 has_direct_style = true;
1307 }
1308 }
1309 }
1310 if !has_direct_style {
1311 for attr in attributes {
1312 if let strata_dom::Attribute::Property { key, value } = attr {
1313 if key.eq_ignore_ascii_case("style") && !value.is_empty() {
1314 inline_decls.extend(strata_style::parse_declarations(value));
1315 }
1316 }
1317 }
1318 }
1319
1320 let tag_name = Self::tag_as_str(tag);
1321 let mut matched_base_rules: Vec<(
1322 u32,
1323 strata_style::Specificity,
1324 usize,
1325 &[strata_style::Declaration],
1326 )> = Vec::new();
1327 let mut matched_interactive_rules: Vec<(
1328 u32,
1329 strata_style::Specificity,
1330 usize,
1331 &[strata_style::Declaration],
1332 )> = Vec::new();
1333 let mut current_meta_opt: Option<CascadeElementMeta> = None;
1334
1335 if !stylesheets.is_empty() {
1336 let (class_vec, id_val, attr_vec) =
1337 Self::extract_element_selector_meta(classes, attributes);
1338 let elem_ref = strata_style::selector::ElementRef::new(
1339 tag_name,
1340 &class_vec,
1341 id_val.as_deref(),
1342 &attr_vec,
1343 );
1344 let ancestor_refs: Vec<strata_style::selector::ElementRef<'_>> = ancestors
1345 .iter()
1346 .map(|a| {
1347 strata_style::selector::ElementRef::new(
1348 a.tag,
1349 &a.classes,
1350 a.id.as_deref(),
1351 &a.attributes,
1352 )
1353 })
1354 .collect();
1355 let ancestor_states: Vec<strata_style::selector::PseudoState> =
1356 ancestors.iter().map(|a| a.pseudo_state).collect();
1357 let sib_refs: Vec<strata_style::selector::ElementRef<'_>> = preceding_siblings
1358 .iter()
1359 .map(|s| {
1360 strata_style::selector::ElementRef::new(
1361 s.tag,
1362 &s.classes,
1363 s.id.as_deref(),
1364 &s.attributes,
1365 )
1366 })
1367 .collect();
1368 let sib_states: Vec<strata_style::selector::PseudoState> =
1369 preceding_siblings.iter().map(|s| s.pseudo_state).collect();
1370
1371 let mut order_counter = 0usize;
1372 for sheet in stylesheets {
1373 for rule in &sheet.rules {
1374 let layer = rule.layer_order.unwrap_or(u32::MAX);
1375 for sel in &rule.selectors {
1376 order_counter += 1;
1377 if sel.matches_hierarchy_with_ancestor_states(
1378 &elem_ref,
1379 &ancestor_refs,
1380 Some(&ancestor_states),
1381 &sib_refs,
1382 Some(&sib_states),
1383 Some(is_last_element_child),
1384 None,
1385 &pseudo_state,
1386 ) {
1387 if sel.has_any_interactive_pseudo() {
1388 matched_interactive_rules.push((
1389 layer,
1390 sel.specificity,
1391 order_counter,
1392 &rule.declarations,
1393 ));
1394 } else {
1395 matched_base_rules.push((
1396 layer,
1397 sel.specificity,
1398 order_counter,
1399 &rule.declarations,
1400 ));
1401 }
1402 }
1403 }
1404 }
1405 }
1406 matched_base_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1407 matched_interactive_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1408
1409 for sheet in stylesheets {
1410 for srule in &sheet.starting_styles {
1411 if srule.selectors.iter().any(|sel| {
1412 sel.matches_hierarchy_with_ancestor_states(
1413 &elem_ref,
1414 &ancestor_refs,
1415 Some(&ancestor_states),
1416 &sib_refs,
1417 Some(&sib_states),
1418 Some(is_last_element_child),
1419 None,
1420 &pseudo_state,
1421 )
1422 }) {
1423 if style.starting_style.is_none() {
1424 style.starting_style = Some(Box::new((*style).clone()));
1425 }
1426 if let Some(start_box) = style.starting_style.as_mut() {
1427 for decl in &srule.declarations {
1428 strata_style::CascadeSolver::apply_declaration(start_box, decl);
1429 }
1430 }
1431 }
1432 }
1433 }
1434
1435 current_meta_opt = Some(CascadeElementMeta {
1436 tag: tag_name,
1437 classes: class_vec,
1438 id: id_val,
1439 attributes: attr_vec,
1440 pseudo_state,
1441 });
1442 }
1443
1444 let has_display_class = classes.iter().any(|c| {
1445 strata_style::tailwind::tokenize_classes(c)
1446 .into_iter()
1447 .any(|tok| {
1448 let mut base = tok;
1449 while let (Some(_), rest) = strata_style::tailwind::split_modifier(base) {
1450 base = rest;
1451 }
1452 matches!(
1453 base,
1454 "flex"
1455 | "grid"
1456 | "block"
1457 | "inline-flex"
1458 | "inline-block"
1459 | "inline"
1460 | "hidden"
1461 | "table"
1462 | "inline-table"
1463 | "table-row-group"
1464 | "table-header-group"
1465 | "table-footer-group"
1466 | "table-row"
1467 | "table-cell"
1468 | "table-column-group"
1469 | "table-column"
1470 | "table-caption"
1471 )
1472 })
1473 });
1474 let has_explicit_display_decl = inline_decls
1475 .iter()
1476 .any(|d| d.property.eq_ignore_ascii_case("display"))
1477 || matched_base_rules.iter().any(|(_, _, _, decls)| {
1478 decls
1479 .iter()
1480 .any(|d| d.property.eq_ignore_ascii_case("display"))
1481 })
1482 || matched_interactive_rules.iter().any(|(_, _, _, decls)| {
1483 decls
1484 .iter()
1485 .any(|d| d.property.eq_ignore_ascii_case("display"))
1486 });
1487
1488 if !has_display_class && !has_explicit_display_decl {
1489 match tag {
1490 Tag::Svg | Tag::Path | Tag::Input | Tag::Textarea => {}
1491 Tag::Table => {
1492 style.display = Display::Table;
1493 }
1494 Tag::Thead => {
1495 style.display = Display::TableHeaderGroup;
1496 }
1497 Tag::Tbody => {
1498 style.display = Display::TableRowGroup;
1499 }
1500 Tag::Tr => {
1501 style.display = Display::TableRow;
1502 }
1503 Tag::Th | Tag::Td => {
1504 style.display = Display::TableCell;
1505 }
1506 Tag::Div
1507 | Tag::Main
1508 | Tag::Section
1509 | Tag::Header
1510 | Tag::Footer
1511 | Tag::Nav
1512 | Tag::Aside
1513 | Tag::Ul
1514 | Tag::Ol
1515 | Tag::Form => {
1516 style.display = Display::Flex;
1517 style.flex_direction = FlexDirection::Column;
1518 }
1519 Tag::P => {
1520 style.display = Display::Block;
1521 }
1522 Tag::H1 | Tag::H2 | Tag::H3 | Tag::H4 | Tag::H5 | Tag::H6 => {
1523 style.display = Display::Flex;
1524 style.flex_direction = FlexDirection::Column;
1525 }
1526 Tag::Button => {
1527 style.display = Display::InlineFlex;
1528 style.align_items = strata_style::types::AlignItems::Center;
1529 style.justify_content = strata_style::types::JustifyContent::Center;
1530 }
1531 Tag::Span => {
1532 style.display = Display::Inline;
1533 }
1534 Tag::Img => {
1535 style.display = Display::InlineBlock;
1536 }
1537 Tag::A => {
1538 style.display = Display::Inline;
1539 if style.text_decoration == strata_style::types::TextDecoration::None {
1540 style.text_decoration = strata_style::types::TextDecoration::Underline;
1541 }
1542 }
1543 _ => {
1544 if let Tag::Custom(name) = tag {
1545 if matches!(
1546 name.to_ascii_lowercase().as_str(),
1547 "code"
1548 | "strong"
1549 | "em"
1550 | "b"
1551 | "i"
1552 | "u"
1553 | "s"
1554 | "small"
1555 | "mark"
1556 | "kbd"
1557 | "samp"
1558 | "var"
1559 | "abbr"
1560 | "cite"
1561 | "q"
1562 | "sub"
1563 | "sup"
1564 | "del"
1565 | "ins"
1566 | "time"
1567 ) {
1568 style.display = Display::Inline;
1569 } else {
1570 style.display = Display::Flex;
1571 if name.eq_ignore_ascii_case("portal") {
1572 style.flex_direction = FlexDirection::Column;
1573 }
1574 }
1575 } else {
1576 style.display = Display::Flex;
1577 }
1578 }
1579 }
1580 } else if matches!(tag, Tag::Custom(name) if name.eq_ignore_ascii_case("portal"))
1581 && matches!(style.display, Display::Flex | Display::InlineFlex)
1582 {
1583 let has_explicit_flex_dir = classes.iter().any(|c| {
1584 c.split_whitespace().any(|tok| {
1585 matches!(
1586 tok,
1587 "flex-row" | "flex-row-reverse" | "flex-col" | "flex-col-reverse"
1588 )
1589 })
1590 }) || inline_decls
1591 .iter()
1592 .any(|d| d.property.eq_ignore_ascii_case("flex-direction"));
1593 if !has_explicit_flex_dir {
1594 style.flex_direction = FlexDirection::Column;
1595 }
1596 }
1597
1598 for &(_, _, _, decls) in &matched_base_rules {
1599 for decl in decls {
1600 if decl.property.starts_with("--") && !decl.important {
1601 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1602 }
1603 }
1604 }
1605 for decl in &inline_decls {
1606 if decl.property.starts_with("--") && !decl.important {
1607 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1608 }
1609 }
1610
1611 for &(_, _, _, decls) in &matched_base_rules {
1612 for decl in decls {
1613 if !decl.property.starts_with("--") && !decl.important {
1614 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1615 }
1616 }
1617 }
1618
1619 Self::apply_base_tailwind_classes(&mut style, classes, &pseudo_state);
1620
1621 if let Some(cs) = direct_computed_override {
1622 *style = cs.clone();
1623 }
1624 for attr in attributes {
1625 if let strata_dom::Attribute::Property { key, value } = attr {
1626 if key.eq_ignore_ascii_case("href") && !value.is_empty() {
1627 let val_atom = strata_primitives::atom::intern(value);
1628 style.set_custom_property(strata_primitives::AtomId::HREF, val_atom);
1629 if matches!(tag, Tag::A)
1630 && style.color == strata_style::types::Color::new(0, 0, 0, 255)
1631 {
1632 style.color = strata_style::types::Color::new(37, 99, 235, 255);
1633 }
1634 } else if key.eq_ignore_ascii_case("colspan") {
1635 if let Ok(cs) = value.parse::<u32>() {
1636 style.colspan = cs.max(1);
1637 }
1638 } else if key.eq_ignore_ascii_case("rowspan") {
1639 if let Ok(rs) = value.parse::<u32>() {
1640 style.rowspan = rs.max(1);
1641 }
1642 }
1643 }
1644 }
1645 for decl in &inline_decls {
1646 if !decl.property.starts_with("--") && !decl.important {
1647 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1648 }
1649 }
1650
1651 for &(_, _, _, decls) in &matched_interactive_rules {
1652 for decl in decls {
1653 if decl.property.starts_with("--") && !decl.important {
1654 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1655 }
1656 }
1657 }
1658 for &(_, _, _, decls) in &matched_interactive_rules {
1659 for decl in decls {
1660 if !decl.property.starts_with("--") && !decl.important {
1661 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1662 }
1663 }
1664 }
1665
1666 Self::apply_interactive_tailwind_classes(&mut style, classes, &pseudo_state);
1667
1668 if !matched_base_rules.is_empty() || !matched_interactive_rules.is_empty() {
1669 let mut important_rules: Vec<(
1670 u32,
1671 strata_style::Specificity,
1672 usize,
1673 &[strata_style::Declaration],
1674 )> = Vec::new();
1675 for &entry in matched_base_rules
1676 .iter()
1677 .chain(matched_interactive_rules.iter())
1678 {
1679 if entry.3.iter().any(|d| d.important) {
1680 important_rules.push(entry);
1681 }
1682 }
1683 important_rules.sort_by_key(|&(l, s, o, _)| (l, s, o));
1684 for &(_, _, _, decls) in &important_rules {
1685 for decl in decls {
1686 if decl.important && decl.property.starts_with("--") {
1687 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1688 }
1689 }
1690 }
1691 for &(_, _, _, decls) in &important_rules {
1692 for decl in decls {
1693 if decl.important && !decl.property.starts_with("--") {
1694 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1695 }
1696 }
1697 }
1698 }
1699 for decl in &inline_decls {
1700 if decl.important && decl.property.starts_with("--") {
1701 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1702 }
1703 }
1704 for decl in &inline_decls {
1705 if decl.important && !decl.property.starts_with("--") {
1706 strata_style::CascadeSolver::apply_declaration(&mut style, decl);
1707 }
1708 }
1709
1710 if matches!(tag, Tag::Button)
1711 && style.display == Display::Flex
1712 && style.width == Dimension::Auto
1713 && style.flex_grow == 0.0
1714 {
1715 style.display = Display::InlineFlex;
1716 }
1717
1718 (style, current_meta_opt)
1719 }
1720
1721 #[inline(never)]
1722 fn try_build_svg_leaf_node(
1723 blueprint: &NodeBlueprint,
1724 attributes: &[strata_dom::Attribute],
1725 style: &mut ComputedStyle,
1726 entity_id: strata_primitives::EntityId,
1727 ) -> Option<LayoutNode> {
1728 let mut view_box = (24.0f32, 24.0f32);
1729 let mut explicit_svg_w = None;
1730 let mut explicit_svg_h = None;
1731 for attr in attributes {
1732 if let strata_dom::Attribute::Property { key, value } = attr {
1733 if key == "viewBox" {
1734 let parts: Vec<f32> = value
1735 .split(|c: char| c.is_whitespace() || c == ',')
1736 .filter(|s| !s.is_empty())
1737 .filter_map(|s| s.parse::<f32>().ok())
1738 .collect();
1739 if parts.len() >= 4 {
1740 view_box = (parts[2], parts[3]);
1741 }
1742 } else if key == "width" {
1743 if let Ok(w) = value.trim_end_matches("px").parse::<f32>() {
1744 explicit_svg_w = Some(w);
1745 }
1746 } else if key == "height" {
1747 if let Ok(h) = value.trim_end_matches("px").parse::<f32>() {
1748 explicit_svg_h = Some(h);
1749 }
1750 }
1751 }
1752 }
1753
1754 let svg_items = Self::collect_svg_items_from_blueprint(
1755 blueprint,
1756 view_box,
1757 None,
1758 None,
1759 2.0,
1760 strata_layout::StrokeLineCap::Round,
1761 strata_layout::StrokeLineJoin::Round,
1762 Vec::new(),
1763 strata_layout::FillRule::NonZero,
1764 style.color,
1765 );
1766
1767 if svg_items.is_empty() {
1768 return None;
1769 }
1770
1771 if style.width == Dimension::Auto {
1772 style.width = Dimension::Px(explicit_svg_w.unwrap_or(if view_box.0 > 24.0 {
1773 view_box.0.min(80.0)
1774 } else {
1775 16.0
1776 }));
1777 }
1778 if style.height == Dimension::Auto {
1779 style.height = Dimension::Px(explicit_svg_h.unwrap_or(if view_box.1 > 24.0 {
1780 view_box.1.min(80.0)
1781 } else {
1782 16.0
1783 }));
1784 }
1785 Some(LayoutNode::with_svg_items(style.clone(), svg_items).with_entity_id(entity_id))
1786 }
1787
1788 pub(crate) const PASSWORD_MASK_CHAR: char = '\u{2022}';
1790
1791 pub(crate) fn is_password_input_attrs(attributes: &[strata_dom::Attribute]) -> bool {
1793 attributes.iter().any(|attr| {
1794 matches!(
1795 attr,
1796 strata_dom::Attribute::Property { key, value }
1797 if key.eq_ignore_ascii_case("type")
1798 && value.trim().eq_ignore_ascii_case("password")
1799 )
1800 })
1801 }
1802
1803 pub(crate) fn mask_password_text(text: &str) -> String {
1806 let count = text.chars().count();
1807 let mut masked = String::with_capacity(count * Self::PASSWORD_MASK_CHAR.len_utf8());
1808 for _ in 0..count {
1809 masked.push(Self::PASSWORD_MASK_CHAR);
1810 }
1811 masked
1812 }
1813
1814 #[inline(never)]
1815 fn build_input_leaf_node(
1816 blueprint: &NodeBlueprint,
1817 is_textarea: bool,
1818 attributes: &[strata_dom::Attribute],
1819 mut style: ComputedStyle,
1820 entity_id: strata_primitives::EntityId,
1821 ) -> LayoutNode {
1822 if style.cursor == strata_style::types::Cursor::Default {
1823 style.cursor = strata_style::types::Cursor::Text;
1824 }
1825 style.white_space = if is_textarea {
1826 strata_style::types::WhiteSpace::PreWrap
1827 } else {
1828 strata_style::types::WhiteSpace::NoWrap
1829 };
1830 style.overflow_x = strata_style::types::Overflow::Hidden;
1831 if is_textarea {
1832 if style.overflow_y == strata_style::types::Overflow::Visible {
1833 style.overflow_y = strata_style::types::Overflow::Auto;
1834 }
1835 } else {
1836 style.overflow_y = strata_style::types::Overflow::Hidden;
1837 }
1838 let is_password = !is_textarea && Self::is_password_input_attrs(attributes);
1839 let mut value_text = None;
1840 let mut placeholder_text = None;
1841 let mut rows_attr: Option<usize> = None;
1842 let mut cols_attr: Option<usize> = None;
1843 for attr in attributes {
1844 if let strata_dom::Attribute::Property { key, value } = attr {
1845 if key == "value" && !value.is_empty() {
1846 value_text = Some(value.clone());
1847 } else if key == "placeholder" && !value.is_empty() {
1848 placeholder_text = Some(value.clone());
1849 } else if key == "rows" {
1850 rows_attr = value.trim().parse::<usize>().ok().filter(|&r| r > 0);
1851 } else if key == "cols" {
1852 cols_attr = value.trim().parse::<usize>().ok().filter(|&c| c > 0);
1853 }
1854 }
1855 }
1856 if is_textarea && value_text.is_none() {
1857 let child_text = Self::extract_text_content(blueprint);
1858 if !child_text.is_empty() {
1859 value_text = Some(child_text);
1860 }
1861 }
1862 let is_mono = strata_layout::is_monospace_family(style.font_family);
1863 let char_w = if is_mono {
1864 style.font_size * 0.60
1865 } else {
1866 style.font_size * 0.55
1867 };
1868 if style.height == Dimension::Auto {
1869 let line_count = if is_textarea {
1870 rows_attr.unwrap_or(3) as f32
1871 } else {
1872 1.0
1873 };
1874 let text_h = style.font_size * style.line_height * line_count;
1875 style.height = Dimension::Px(
1876 text_h
1877 + style.padding.top
1878 + style.padding.bottom
1879 + style.border_width.top
1880 + style.border_width.bottom,
1881 );
1882 }
1883 let border_h = style.border_width.left + style.border_width.right;
1884 if let Some(val) = value_text {
1885 let display_val = if is_password {
1886 Self::mask_password_text(&val)
1887 } else {
1888 val
1889 };
1890 let max_chars = if is_textarea {
1891 display_val
1892 .lines()
1893 .map(|l| l.chars().count())
1894 .max()
1895 .unwrap_or(0)
1896 } else {
1897 display_val.chars().count()
1898 };
1899 let approx_width = if is_textarea {
1900 cols_attr
1901 .map(|c| c as f32 * char_w)
1902 .unwrap_or_else(|| (max_chars as f32 * char_w).max(200.0))
1903 } else {
1904 (max_chars as f32 * char_w).max(40.0)
1905 };
1906 if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1907 style.width = Dimension::Px(
1908 approx_width + style.padding.left + style.padding.right + border_h,
1909 );
1910 }
1911 LayoutNode::with_text(style, display_val).with_entity_id(entity_id)
1912 } else if let Some(ph) = placeholder_text {
1913 let approx_width = if is_textarea {
1914 cols_attr
1915 .map(|c| c as f32 * char_w)
1916 .unwrap_or_else(|| (ph.chars().count() as f32 * char_w).max(200.0))
1917 } else {
1918 (ph.chars().count() as f32 * char_w).max(40.0)
1919 };
1920 if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1921 style.width = Dimension::Px(
1922 approx_width + style.padding.left + style.padding.right + border_h,
1923 );
1924 }
1925 style.color = strata_style::types::Color::new(140, 145, 155, 255);
1926 LayoutNode::with_text(style, ph).with_entity_id(entity_id)
1927 } else {
1928 let default_w = if is_textarea {
1929 cols_attr.map(|c| c as f32 * char_w).unwrap_or(200.0)
1930 } else {
1931 60.0
1932 };
1933 if style.width == Dimension::Auto && style.flex_grow <= 0.0 {
1934 style.width =
1935 Dimension::Px(default_w + style.padding.left + style.padding.right + border_h);
1936 }
1937 LayoutNode::with_text(style, String::new()).with_entity_id(entity_id)
1938 }
1939 }
1940
1941 #[inline(never)]
1942 fn try_build_img_leaf_node(
1943 attributes: &[strata_dom::Attribute],
1944 style: &mut ComputedStyle,
1945 entity_id: strata_primitives::EntityId,
1946 ) -> Option<LayoutNode> {
1947 let mut src_value = None;
1948 for attr in attributes {
1949 if let strata_dom::Attribute::Property { key, value } = attr {
1950 if key.eq_ignore_ascii_case("src") && !value.is_empty() {
1951 src_value = Some(value.as_str());
1952 }
1953 }
1954 }
1955 let src = src_value?;
1956 let payload = data_uri_base64_payload(src)?;
1957 let decoded = decode_base64(payload)?;
1958 let (width, height) = png_dimensions(&decoded)?;
1959 if style.width == Dimension::Auto {
1960 style.width = Dimension::Px(width as f32);
1961 }
1962 if style.height == Dimension::Auto {
1963 style.height = Dimension::Px(height as f32);
1964 }
1965 if style.display == Display::Inline {
1966 style.display = Display::InlineBlock;
1967 }
1968 let image = strata_layout::ImageResource {
1969 data: std::sync::Arc::new(decoded),
1970 width,
1971 height,
1972 };
1973 Some(LayoutNode::with_image(style.clone(), image).with_entity_id(entity_id))
1974 }
1975
1976 #[inline(never)]
1977 fn apply_canvas3d_sizing_and_check_leaf(
1978 attributes: &[strata_dom::Attribute],
1979 children: &[NodeBlueprint],
1980 style: &mut ComputedStyle,
1981 ) -> bool {
1982 for attr in attributes {
1983 if let strata_dom::Attribute::Property { key, value } = attr {
1984 if key == "width" && style.width == Dimension::Auto {
1985 if let Ok(w) = value.trim_end_matches("px").parse::<f32>() {
1986 style.width = Dimension::Px(w);
1987 }
1988 } else if key == "height" && style.height == Dimension::Auto {
1989 if let Ok(h) = value.trim_end_matches("px").parse::<f32>() {
1990 style.height = Dimension::Px(h);
1991 }
1992 }
1993 }
1994 }
1995 let is_declarative_3d_child = |c: &NodeBlueprint| match c {
1996 NodeBlueprint::Element {
1997 tag: Tag::Custom(name),
1998 ..
1999 } => matches!(
2000 *name,
2001 "PerspectiveCamera"
2002 | "OrthographicCamera"
2003 | "AmbientLight"
2004 | "DirectionalLight"
2005 | "PointLight"
2006 | "Mesh"
2007 | "BoxGeometry"
2008 | "SphereGeometry"
2009 | "PlaneGeometry"
2010 | "CylinderGeometry"
2011 | "StandardMaterial"
2012 | "ShaderMaterial"
2013 ),
2014 NodeBlueprint::Empty => true,
2015 _ => false,
2016 };
2017 let has_dom_overlay_children = children.iter().any(|c| !is_declarative_3d_child(c));
2018 if has_dom_overlay_children {
2019 return false;
2020 }
2021 attributes.iter().any(|a| {
2022 matches!(a, strata_dom::Attribute::ScenePayload(_))
2023 || matches!(a, strata_dom::Attribute::Property { key, value } if key == "data-strata-canvas3d" && value == "true")
2024 }) || children.iter().any(|c| match c {
2025 NodeBlueprint::Element { .. } => is_declarative_3d_child(c),
2026 _ => false,
2027 })
2028 }
2029
2030 #[inline(never)]
2031 pub(crate) fn apply_single_text_inline_intrinsic_sizing(
2032 style: &mut ComputedStyle,
2033 children: &[NodeBlueprint],
2034 ) {
2035 let is_atomic_inline = matches!(
2042 style.display,
2043 Display::InlineFlex | Display::InlineBlock
2044 );
2045 let is_flexible_or_min_zero =
2046 style.flex_grow > 0.0 || matches!(style.min_width, Dimension::Px(px) if px == 0.0);
2047 if is_atomic_inline
2048 && !is_flexible_or_min_zero
2049 && style.width == Dimension::Auto
2050 && children.len() == 1
2051 {
2052 let single_text: Option<std::borrow::Cow<'_, str>> = match &children[0] {
2053 NodeBlueprint::Text(t) => Some(std::borrow::Cow::Borrowed(t.as_str())),
2054 NodeBlueprint::DynamicText(dyn_fn) => Some(std::borrow::Cow::Owned(dyn_fn())),
2055 _ => None,
2056 };
2057 if let Some(t) = single_text {
2058 let is_mono = strata_layout::is_monospace_family(style.font_family);
2059 let (text_w, raw_h) = strata_layout::measure_text_bounds_styled_with_family(
2060 &t,
2061 style.font_size,
2062 style.line_height,
2063 None,
2064 is_mono,
2065 style.font_family,
2066 style.font_weight,
2067 style.font_style,
2068 );
2069 let total_w = (text_w
2070 + style.padding.left
2071 + style.padding.right
2072 + style.border_width.left
2073 + style.border_width.right)
2074 .ceil();
2075 style.width = Dimension::Px(total_w);
2076 if style.height == Dimension::Auto {
2077 let total_h = raw_h
2078 + style.padding.top
2079 + style.padding.bottom
2080 + style.border_width.top
2081 + style.border_width.bottom;
2082 style.height = Dimension::Px(total_h);
2083 }
2084 }
2085 }
2086 }
2087}