The headless browser for AI agents and web scraping
Cascade shadow host rules in scope
SGavrlf8bcf3202bdf
diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rsindex ed37f6c9..ef9ab6e0 100644--- a/crates/obscura-dom/src/selector.rs+++ b/crates/obscura-dom/src/selector.rs@@ -206,6 +206,13 @@ impl<'i> parser::Parser<'i> for ObscuraSelectorParser {true}+ // `:host` is parsed by the selectors crate itself. Ordinary document+ // matching still cannot match it because those contexts deliberately have+ // no `current_host`.+ fn parse_host(&self) -> bool {+ true+ }+fn parse_non_ts_pseudo_class(&self,_location: cssparser::SourceLocation,@@ -909,6 +916,38 @@ impl Matcher {)}+ /// Match a selector from `host`'s shadow-tree scope against the host.+ /// Supplying the scope explicitly prevents `:host` from leaking into+ /// document stylesheets or a different shadow root.+ pub fn matches_shadow_host(+ &mut self,+ tree: &DomTree,+ nid: NodeId,+ compiled: &CompiledSelector,+ host: NodeId,+ ) -> bool {+ if nid != host || !tree.with_node(nid, |n| n.is_element()).unwrap_or(false) {+ return false;+ }+ let mut context = MatchingContext::new(+ MatchingMode::Normal,+ Some(self.ancestors.filter()),+ &mut self.caches,+ QuirksMode::NoQuirks,+ NeedsSelectorFlags::No,+ MatchingForInvalidation::No,+ );+ let element = DomElement::new(tree, nid);+ context.current_host = Some(element.opaque());+ selectors::matching::matches_selector(+ &compiled.sel,+ 0,+ Some(&compiled.hashes),+ &element,+ &mut context,+ )+ }+/// Push `nid`'s hashes onto the ancestor filter before descending into its/// children. Must be paired with a matching [`Matcher::pop_ancestor`].pub fn push_ancestor(&mut self, tree: &DomTree, nid: NodeId) {@@ -1012,6 +1051,15 @@ pub struct CompiledSelector {}impl CompiledSelector {+ /// Whether this selector is eligible to match a featureless shadow host.+ /// Shadow-tree stylesheets use this to retain only `:host` selectors when+ /// matching against the host in their own tree scope.+ pub fn matches_featureless_host(&self) -> bool {+ self.sel+ .matches_featureless_host_selector_or_pseudo_element()+ .contains(parser::FeaturelessHostMatches::FOR_HOST)+ }+/// The one bucket usable by legacy selector indexes. Selectors whose/// subject has multiple disjoint alternatives deliberately report/// `Universal`; use [`Self::candidate_keys`] to opt into multi-bucket@@ -1670,4 +1718,30 @@ mod tests {Some(host));}++ #[test]+ fn host_selectors_require_and_respect_explicit_shadow_scope() {+ let tree = parse_html(+ r#"<!doctype html><x-card id="host" class="active"></x-card><x-card id="other"></x-card>"#,+ );+ let host = tree.get_element_by_id("host").unwrap();+ let other = tree.get_element_by_id("other").unwrap();+ tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();++ let plain = tree.compile_rule_selector(":host").unwrap();+ let qualified = tree.compile_rule_selector(":host(.active)").unwrap();+ let rejected = tree.compile_rule_selector(":host([hidden])").unwrap();+ assert!(plain.matches_featureless_host());+ assert!(qualified.matches_featureless_host());++ let mut matcher = tree.matcher();+ assert!(matcher.matches_shadow_host(&tree, host, &plain, host));+ assert!(matcher.matches_shadow_host(&tree, host, &qualified, host));+ assert!(!matcher.matches_shadow_host(&tree, host, &rejected, host));+ assert!(!matcher.matches_shadow_host(&tree, other, &plain, host));++ // Parsing support must not make `:host` observable in document scope.+ assert!(!tree.matches_selector(host, ":host").unwrap());+ assert!(tree.query_selector_all(":host").unwrap().is_empty());+ }}diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rsindex f1c4569d..06d7493d 100644--- a/crates/obscura-render/src/css.rs+++ b/crates/obscura-render/src/css.rs@@ -1568,6 +1568,22 @@ struct Rule {layer: Option<LayerOrder>,}+#[derive(Default)]+struct ShadowHostDeclarations {+ normal: String,+ important: String,+}++fn append_declaration_stream(target: &mut String, declarations: &str) {+ if declarations.trim().is_empty() {+ return;+ }+ if !target.is_empty() && !target.ends_with(';') {+ target.push(';');+ }+ target.push_str(declarations);+}+const NO_CANDIDATE_SLOT: u32 = u32::MAX;fn is_root_element(tree: &DomTree, nid: NodeId) -> bool {@@ -2302,6 +2318,11 @@ fn evaluate_container_query_expr(/// An indexed set of author rules ready for fast per-element matching.pub struct Stylesheet {rules: Vec<Rule>,+ /// Rules whose subject can match this stylesheet's featureless shadow+ /// host. Kept separate because a host is outside the shadow tree's normal+ /// selector index and must only be matched with that tree's explicit host+ /// scope.+ host_rules: Vec<usize>,invalidation_map: InvalidationMap,registered_custom_properties: HashMap<String, RegisteredCustomProperty>,/// Index zero is the unconditional sentinel.@@ -2627,6 +2648,7 @@ impl Stylesheet {) -> Self {let mut sheet = Stylesheet {rules: Vec::new(),+ host_rules: Vec::new(),invalidation_map: InvalidationMap::default(),registered_custom_properties: HashMap::new(),container_conditions: vec![ContainerConditionNode {@@ -2850,6 +2872,9 @@ impl Stylesheet {let normal_flags = declaration_stream_flags(&normal_decls);let important_flags = declaration_stream_flags(&important_decls);let idx = sheet.rules.len();+ if sel.matches_featureless_host() {+ sheet.host_rules.push(idx);+ }let candidate_slot = if sel.candidate_keys().len() > 1 {let slot = u32::try_from(sheet.candidate_slot_count).expect("selector candidate slot count exceeds u32");@@ -3169,6 +3194,70 @@ impl Stylesheet {)}+ fn shadow_host_declarations(+ &self,+ tree: &DomTree,+ matcher: &mut Matcher,+ host: NodeId,+ mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,+ ) -> ShadowHostDeclarations {+ let mut normal = Vec::new();+ let mut important = Vec::new();+ for &index in &self.host_rules {+ let rule = &self.rules[index];+ if matcher.matches_shadow_host(tree, host, &rule.sel, host)+ && self.container_condition_is_active(+ rule.container_condition_id,+ host,+ ContainerQuerySubjectKind::Element,+ &mut evaluator,+ )+ {+ let matched = (rule.specificity, rule.order, index);+ if !rule.normal_decls.is_empty() {+ normal.push(matched);+ }+ if !rule.important_decls.is_empty() {+ important.push(matched);+ }+ }+ }+ normal.sort_unstable_by(|a, b| {+ compare_rule_cascade(+ self.rules[a.2].layer.as_ref(),+ a.0,+ a.1,+ self.rules[b.2].layer.as_ref(),+ b.0,+ b.1,+ false,+ )+ });+ important.sort_unstable_by(|a, b| {+ compare_rule_cascade(+ self.rules[a.2].layer.as_ref(),+ a.0,+ a.1,+ self.rules[b.2].layer.as_ref(),+ b.0,+ b.1,+ true,+ )+ });++ let mut declarations = ShadowHostDeclarations::default();+ for &(_, _, index) in &normal {+ append_declaration_stream(&mut declarations.normal, &self.rules[index].normal_decls);+ }+ for &(_, _, index) in &important {+ append_declaration_stream(+ &mut declarations.important,+ &self.rules[index].important_decls,+ );+ }+ declarations+ }+/// Apply every author rule that matches `nid` to `style`, in cascade order/// (ascending specificity, then source order, so the winner is applied last)./// `id`, `classes`, and `local` are the element's precomputed keys.@@ -3232,6 +3321,7 @@ impl Stylesheet {parent_props,inline_css,None,+ None,animation_sample,animation_timeline,)@@ -3296,12 +3386,51 @@ impl Stylesheet {style,parent_props,inline_css,+ None,Some(evaluator),animation_sample,animation_timeline,)}+ /// Apply document author rules together with the `:host` rules from the+ /// host's own shadow tree. Encapsulation context precedes specificity and+ /// layer order: shadow normal declarations are weaker than document/inline+ /// normal declarations, while shadow `!important` is stronger than every+ /// document/inline author-important declaration.+ pub(crate) fn apply_with_shadow_host_at_animation_time(+ &self,+ shadow_host_sheet: &Stylesheet,+ tree: &DomTree,+ matcher: &mut Matcher,+ nid: NodeId,+ id: Option<&str>,+ classes: &[String],+ local: &str,+ style: &mut LayoutStyle,+ parent_props: &HashMap<String, String>,+ inline_css: Option<&str>,+ evaluator: Option<&mut ContainerQueryEvaluator<'_>>,+ animation_sample: crate::AnimationSample,+ animation_timeline: &mut crate::AnimationTimelineState,+ ) -> Option<HashMap<String, String>> {+ self.apply_internal(+ tree,+ matcher,+ nid,+ id,+ classes,+ local,+ style,+ parent_props,+ inline_css,+ Some(shadow_host_sheet),+ evaluator,+ animation_sample,+ animation_timeline,+ )+ }+fn apply_internal(&self,tree: &DomTree,@@ -3313,10 +3442,16 @@ impl Stylesheet {style: &mut LayoutStyle,parent_props: &HashMap<String, String>,inline_css: Option<&str>,+ shadow_host_sheet: Option<&Stylesheet>,mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,animation_sample: crate::AnimationSample,animation_timeline: &mut crate::AnimationTimelineState,) -> Option<HashMap<String, String>> {+ let shadow_host_declarations = shadow_host_sheet+ .map(|sheet| {+ sheet.shadow_host_declarations(tree, matcher, nid, evaluator.as_deref_mut())+ })+ .unwrap_or_default();// Keep the two cascade priorities separate from the outset. A typical// stylesheet has very few important declarations, so cloning and// sorting every matching normal-only rule into an empty important pass@@ -3447,7 +3582,11 @@ impl Stylesheet {// properties cascade fully before any `var()` is substituted.let inline_normal_flags = declaration_stream_flags(&inline_normal);let inline_important_flags = declaration_stream_flags(&inline_important);- let has_own_custom_properties = inline_normal_flags.has_custom_properties+ let shadow_normal_flags = declaration_stream_flags(&shadow_host_declarations.normal);+ let shadow_important_flags = declaration_stream_flags(&shadow_host_declarations.important);+ let has_own_custom_properties = shadow_normal_flags.has_custom_properties+ || shadow_important_flags.has_custom_properties+ || inline_normal_flags.has_custom_properties|| inline_important_flags.has_custom_properties|| normal_matched.iter()@@ -3488,6 +3627,9 @@ impl Stylesheet {}}};+ if shadow_normal_flags.has_custom_properties {+ collect_custom(&shadow_host_declarations.normal);+ }for &(_, _, i) in &normal_matched {let rule = &self.rules[i];if rule.normal_flags.has_custom_properties {@@ -3506,6 +3648,9 @@ impl Stylesheet {if inline_important_flags.has_custom_properties {collect_custom(&inline_important);}+ if shadow_important_flags.has_custom_properties {+ collect_custom(&shadow_host_declarations.important);+ }let mut resolved_props = parent_props.clone();for (name, registration) in &self.registered_custom_properties {@@ -3602,6 +3747,18 @@ impl Stylesheet {// scheme, not the declaration order. Determine the scheme winner// across the complete author cascade before applying any color-valued// property. The style starts with its inherited scheme.+ if shadow_normal_flags.has_color_scheme {+ let expanded = substitute_declarations(+ &shadow_host_declarations.normal,+ props,+ shadow_normal_flags.has_var,+ );+ crate::style::apply_color_scheme_declarations_from(+ style,+ &expanded,+ inherited_color_scheme_dark,+ );+ }for &(_, _, i) in &normal_matched {let rule = &self.rules[i];if !rule.normal_flags.has_color_scheme {@@ -3646,9 +3803,27 @@ impl Stylesheet {inherited_color_scheme_dark,);}+ if shadow_important_flags.has_color_scheme {+ let expanded = substitute_declarations(+ &shadow_host_declarations.important,+ props,+ shadow_important_flags.has_var,+ );+ crate::style::apply_color_scheme_declarations_from(+ style,+ &expanded,+ inherited_color_scheme_dark,+ );+ }// Pass 2: apply normal declarations with `var()` substituted against// the resolved custom-property map.+ let expanded = substitute_declarations(+ &shadow_host_declarations.normal,+ props,+ shadow_normal_flags.has_var,+ );+ crate::style::apply_declarations_with_locked_color_scheme(style, &expanded);for &(_, _, i) in &normal_matched {let rule = &self.rules[i];let expanded =@@ -3663,7 +3838,8 @@ impl Stylesheet {// important author origin. Resolve those controls on a temporary style// before sampling, then let the ordinary important pass override the// sampled values where appropriate.- let important_has_animation = inline_important_flags.has_animation+ let important_has_animation = shadow_important_flags.has_animation+ || inline_important_flags.has_animation|| important_matched.iter().any(|&(_, _, i)| self.rules[i].important_flags.has_animation);@@ -3691,6 +3867,14 @@ impl Stylesheet {);crate::style::apply_animation_declarations(&mut animation_style, &expanded);}+ if shadow_important_flags.has_animation {+ let expanded = substitute_declarations(+ &shadow_host_declarations.important,+ props,+ shadow_important_flags.has_var,+ );+ crate::style::apply_animation_declarations(&mut animation_style, &expanded);+ }if let Some(name) = animation_style.animation_name.as_deref() {if let Some(keyframes) = self.keyframes.get(name) {style.animation_has_render_effect = !keyframes.tracks.is_empty();@@ -3736,6 +3920,12 @@ impl Stylesheet {let expanded =substitute_declarations(&inline_important, props, inline_important_flags.has_var);crate::style::apply_declarations_with_locked_color_scheme(style, &expanded);+ let expanded = substitute_declarations(+ &shadow_host_declarations.important,+ props,+ shadow_important_flags.has_var,+ );+ crate::style::apply_declarations_with_locked_color_scheme(style, &expanded);effective}}diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rsindex 4d39b308..b4c4357b 100644--- a/crates/obscura-render/src/dom.rs+++ b/crates/obscura-render/src/dom.rs@@ -2255,7 +2255,26 @@ fn cascade_walk(.get_attribute("class").map(|c| c.split_whitespace().map(|s| s.to_string()).collect()).unwrap_or_default();- let effective_props = if let Some(evaluator) = container_evaluator.as_deref_mut() {+ let shadow_host_sheet = tree+ .shadow_root(id)+ .and_then(|root| shadow_sheets.get(&root));+ let effective_props = if let Some(shadow_host_sheet) = shadow_host_sheet {+ sheet.apply_with_shadow_host_at_animation_time(+ shadow_host_sheet,+ tree,+ matcher,+ id,+ node_id,+ &classes,+ elem.local.as_ref(),+ &mut style,+ parent_props,+ node.get_attribute("style"),+ container_evaluator.as_deref_mut(),+ animation_sample,+ animation_timeline,+ )+ } else if let Some(evaluator) = container_evaluator.as_deref_mut() {sheet.apply_with_container_queries_at_animation_time(tree,matcher,@@ -13950,7 +13969,7 @@ mod tests {assert_eq!(light_style.width, crate::Dimension::Px(123.0));assert_eq!(light_style.height, crate::Dimension::Px(9.0));assert_eq!(light_style.padding.left, 13.0);- assert_eq!(light_style.margin.left, 0.0);+ assert_eq!(light_style.margin.left, 99.0);assert_eq!(first_style.width, crate::Dimension::Px(41.0));assert_eq!(first_style.height, crate::Dimension::Px(23.0));assert_eq!(first_style.padding.left, 0.0);@@ -13961,6 +13980,81 @@ mod tests {assert_eq!(second_style.margin.left, 0.0);}+ #[test]+ fn shadow_host_rules_match_in_scope_and_follow_encapsulation_cascade_order() {+ let tree = parse_html(+ r#"<style>+ x-one { width:110px; --normal-size:66px; height:var(--normal-size) }+ x-one { margin-left:8px !important; padding-left:9px !important; --critical:7px !important }+ </style>+ <x-one id="host-one" class="active" style="margin-left:11px !important"></x-one>+ <x-two id="host-two"></x-two>+ <div id="source-one">+ <style>+ :host { display:block; width:40px; --normal-size:22px }+ :host(.active) { margin-left:31px !important; padding-left:var(--critical) !important; --critical:17px !important }+ :host([hidden]) { border-left-width:19px }+ .active { border-right-width:23px }+ </style>+ <div style="height:5px"></div>+ </div>+ <div id="source-two">+ <style>:host { display:block; width:55px }</style>+ <div style="height:7px"></div>+ </div>"#,+ );+ let host_one = tree.get_element_by_id("host-one").unwrap();+ let host_two = tree.get_element_by_id("host-two").unwrap();+ let source_one = tree.get_element_by_id("source-one").unwrap();+ let source_two = tree.get_element_by_id("source-two").unwrap();+ attach_programmatic_shadow(&tree, host_one, source_one);+ attach_programmatic_shadow(&tree, host_two, source_two);++ let laid = layout_dom(&tree, (400.0, 300.0));+ let first = &laid.styles[&host_one];+ let second = &laid.styles[&host_two];++ assert_eq!(+ first.display,+ crate::Display::Block,+ ":host supplies geometry"+ );+ assert_eq!(+ first.width,+ crate::Dimension::Px(110.0),+ "outer normal wins"+ );+ assert_eq!(+ first.height,+ crate::Dimension::Px(66.0),+ "outer custom property wins"+ );+ assert_eq!(+ first.margin.left, 31.0,+ "inner important beats inline important"+ );+ assert_eq!(+ first.padding.left, 17.0,+ "inner important custom property wins"+ );+ assert_eq!(+ first.border.left, 0.0,+ "non-matching :host argument is isolated"+ );+ assert_eq!(+ first.border.right, 0.0,+ "ordinary shadow selector cannot style host"+ );+ assert_eq!(+ laid.rects[&host_one].width, 127.0,+ "content width plus host padding"+ );++ assert_eq!(second.width, crate::Dimension::Px(55.0));+ assert_eq!(second.height, crate::Dimension::Auto);+ assert_eq!(second.margin.left, 0.0, "first shadow root cannot leak");+ }+#[test]fn direct_shadow_inline_block_is_blockified_as_a_flex_item() {let tree = parse_html(