Skip to content

The headless browser for AI agents and web scraping

Cascade slotted rules through native assignment

SGavrl87445df83220
diff --git a/crates/obscura-dom/src/selector.rs b/crates/obscura-dom/src/selector.rs
index ef9ab6e0..d1a6c134 100644
--- a/crates/obscura-dom/src/selector.rs
+++ b/crates/obscura-dom/src/selector.rs
@@ -213,6 +213,13 @@ impl<'i> parser::Parser<'i> for ObscuraSelectorParser {
true
}
+ // The selectors crate implements the `::slotted()` grammar and matching
+ // combinator. DomElement's slot hooks below provide the tree-specific
+ // assignment boundary.
+ fn parse_slotted(&self) -> bool {
+ true
+ }
+
fn parse_non_ts_pseudo_class(
&self,
_location: cssparser::SourceLocation,
@@ -529,11 +536,13 @@ impl<'a> Element for DomElement<'a> {
}
fn is_html_slot_element(&self) -> bool {
- false
+ self.tree.is_html_slot_element(self.node_id)
}
fn assigned_slot(&self) -> Option<Self> {
- None
+ self.tree
+ .assigned_slot(self.node_id)
+ .map(|node_id| DomElement::new(self.tree, node_id))
}
fn has_id(&self, id: &CssString, case_sensitivity: CaseSensitivity) -> bool {
@@ -926,19 +935,41 @@ impl Matcher {
compiled: &CompiledSelector,
host: NodeId,
) -> bool {
- if nid != host || !tree.with_node(nid, |n| n.is_element()).unwrap_or(false) {
+ if nid != host {
+ return false;
+ }
+ self.matches_in_shadow_scope(tree, nid, compiled, host)
+ }
+
+ /// Match `compiled` in the shadow tree hosted by `host`. This supplies the
+ /// scope used by `::slotted()`'s slot-assignment combinator without making
+ /// shadow-only selectors observable to document matching.
+ pub fn matches_in_shadow_scope(
+ &mut self,
+ tree: &DomTree,
+ nid: NodeId,
+ compiled: &CompiledSelector,
+ host: NodeId,
+ ) -> bool {
+ if !tree.with_node(nid, |n| n.is_element()).unwrap_or(false) {
return false;
}
let mut context = MatchingContext::new(
MatchingMode::Normal,
- Some(self.ancestors.filter()),
+ // The caller's reusable bloom tracks the subject's DOM ancestors.
+ // A slotted selector crosses to the assigned slot and then walks
+ // that slot's shadow-tree ancestors, so the DOM bloom would cause
+ // false negatives for `.wrapper slot::slotted(...)`. Scoped rules
+ // are already narrowed to a small per-shadow index; match them
+ // without an incompatible ancestor filter.
+ None,
&mut self.caches,
QuirksMode::NoQuirks,
NeedsSelectorFlags::No,
MatchingForInvalidation::No,
);
let element = DomElement::new(tree, nid);
- context.current_host = Some(element.opaque());
+ context.current_host = Some(DomElement::new(tree, host).opaque());
selectors::matching::matches_selector(
&compiled.sel,
0,
@@ -1060,6 +1091,12 @@ impl CompiledSelector {
.contains(parser::FeaturelessHostMatches::FOR_HOST)
}
+ /// Whether this selector contains the `::slotted()` pseudo-element and
+ /// must be collected at a slot-assignment boundary.
+ pub fn is_slotted(&self) -> bool {
+ self.sel.is_slotted()
+ }
+
/// 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
@@ -1744,4 +1781,44 @@ mod tests {
assert!(!tree.matches_selector(host, ":host").unwrap());
assert!(tree.query_selector_all(":host").unwrap().is_empty());
}
+
+ #[test]
+ fn slotted_selectors_match_only_assigned_elements_in_their_shadow_scope() {
+ let tree = parse_html(
+ r#"<!doctype html><x-card id="host"><span id="item" class="item" slot="title"></span><span id="unslotted" class="item" slot="missing"></span></x-card>"#,
+ );
+ let host = tree.get_element_by_id("host").unwrap();
+ let item = tree.get_element_by_id("item").unwrap();
+ let unslotted = tree.get_element_by_id("unslotted").unwrap();
+ let root = tree.attach_shadow_root(host, ShadowRootMode::Open).unwrap();
+ let slot = shadow_element(
+ &tree,
+ "slot",
+ &[("name", "title"), ("class", "outlet")],
+ );
+ let wrapper = shadow_element(&tree, "div", &[("class", "wrapper")]);
+ tree.append_child(root, wrapper);
+ tree.append_child(wrapper, slot);
+
+ let plain = tree.compile_rule_selector("::slotted(.item)").unwrap();
+ let qualified = tree
+ .compile_rule_selector("slot.outlet::slotted(.item)")
+ .unwrap();
+ let descendant = tree
+ .compile_rule_selector(".wrapper slot.outlet::slotted(.item)")
+ .unwrap();
+ let rejected = tree.compile_rule_selector("::slotted(.other)").unwrap();
+ assert!(plain.is_slotted());
+
+ let mut matcher = tree.matcher();
+ assert!(matcher.matches_in_shadow_scope(&tree, item, &plain, host));
+ assert!(matcher.matches_in_shadow_scope(&tree, item, &qualified, host));
+ assert!(matcher.matches_in_shadow_scope(&tree, item, &descendant, host));
+ assert!(!matcher.matches_in_shadow_scope(&tree, item, &rejected, host));
+ assert!(!matcher.matches_in_shadow_scope(&tree, unslotted, &plain, host));
+ assert!(!matcher.matches_in_shadow_scope(&tree, item, &plain, item));
+
+ // Document matching parses the selector but has no shadow scope.
+ assert!(!tree.matches_selector(item, "::slotted(.item)").unwrap());
+ }
}
diff --git a/crates/obscura-dom/src/tree.rs b/crates/obscura-dom/src/tree.rs
index f6d7e1a3..cd21e355 100644
--- a/crates/obscura-dom/src/tree.rs
+++ b/crates/obscura-dom/src/tree.rs
@@ -927,6 +927,99 @@ impl DomTree {
Some(self.descendants(root))
}
+ /// Whether `node` is an HTML `<slot>` element. Slot assignment is defined
+ /// only for HTML slots; same-local-name elements in other namespaces do
+ /// not participate in the flattened tree.
+ pub fn is_html_slot_element(&self, node: NodeId) -> bool {
+ self.get_node(node).is_some_and(|node| {
+ node.as_element().is_some_and(|name| {
+ name.ns.as_ref() == "http://www.w3.org/1999/xhtml"
+ && name.local.as_ref() == "slot"
+ })
+ })
+ }
+
+ /// Return the first slot to which `node` is assigned.
+ ///
+ /// The node must be a direct light child of a shadow host. Element slot
+ /// names and slot `name` values compare as exact strings; text nodes use
+ /// the empty/default name. The first same-name slot in shadow-tree order
+ /// wins, matching the HTML slot assignment algorithm.
+ pub fn assigned_slot(&self, node: NodeId) -> Option<NodeId> {
+ let node_ref = self.get_node(node)?;
+ let parent = node_ref.parent?;
+ let name = if node_ref.is_element() {
+ node_ref.get_attribute("slot").unwrap_or("").to_owned()
+ } else if node_ref.text_content_of_text_node().is_some() {
+ String::new()
+ } else {
+ return None;
+ };
+ drop(node_ref);
+
+ let root = self.shadow_root(parent)?;
+ self.descendants(root).into_iter().find(|candidate| {
+ self.is_html_slot_element(*candidate)
+ && self
+ .get_node(*candidate)
+ .and_then(|slot| slot.get_attribute("name").map(str::to_owned))
+ .unwrap_or_default()
+ == name
+ })
+ }
+
+ /// Flattened children for an HTML slot. Assigned nodes replace fallback
+ /// children; an unassigned slot exposes its ordinary child list.
+ pub fn slot_rendered_children(&self, slot: NodeId) -> Option<Vec<NodeId>> {
+ if !self.is_html_slot_element(slot) {
+ return None;
+ }
+ let root = self.containing_shadow_root(slot)?;
+ let host = self.shadow_root_info(root)?.host;
+ let name = self
+ .get_node(slot)
+ .and_then(|slot| slot.get_attribute("name").map(str::to_owned))
+ .unwrap_or_default();
+ let is_same_name_slot = |candidate: NodeId| {
+ self.is_html_slot_element(candidate)
+ && self
+ .get_node(candidate)
+ .and_then(|slot| slot.get_attribute("name").map(str::to_owned))
+ .unwrap_or_default()
+ == name
+ };
+ if self
+ .descendants(root)
+ .into_iter()
+ .take_while(|candidate| *candidate != slot)
+ .any(is_same_name_slot)
+ {
+ return Some(self.children(slot));
+ }
+ let assigned = self
+ .children(host)
+ .into_iter()
+ .filter(|candidate| {
+ let Some(node) = self.get_node(*candidate) else {
+ return false;
+ };
+ let candidate_name = if node.is_element() {
+ node.get_attribute("slot").unwrap_or("")
+ } else if node.text_content_of_text_node().is_some() {
+ ""
+ } else {
+ return false;
+ };
+ candidate_name == name
+ })
+ .collect::<Vec<_>>();
+ Some(if assigned.is_empty() {
+ self.children(slot)
+ } else {
+ assigned
+ })
+ }
+
/// Returns the node after `current` in document order, without leaving the
/// subtree rooted at `root`.
///
@@ -1480,6 +1573,46 @@ mod tests {
);
}
+ #[test]
+ fn slot_assignment_uses_exact_names_first_slot_and_fallback_children() {
+ let tree = DomTree::new();
+ let host = element(&tree, "x-card");
+ tree.append_child(tree.document(), host);
+ let named = element(&tree, "span");
+ tree.with_node_mut(named, |node| node.set_attribute("slot", "title".into()));
+ let default_text = tree.new_node(NodeData::Text {
+ contents: "default".into(),
+ });
+ tree.append_child(host, named);
+ tree.append_child(host, default_text);
+
+ let root = tree
+ .attach_shadow_root(host, ShadowRootMode::Open)
+ .unwrap();
+ let first_named = element(&tree, "slot");
+ tree.with_node_mut(first_named, |node| node.set_attribute("name", "title".into()));
+ let duplicate_named = element(&tree, "slot");
+ tree.with_node_mut(duplicate_named, |node| node.set_attribute("name", "title".into()));
+ let fallback = element(&tree, "b");
+ tree.append_child(duplicate_named, fallback);
+ let default_slot = element(&tree, "slot");
+ tree.append_child(root, first_named);
+ tree.append_child(root, duplicate_named);
+ tree.append_child(root, default_slot);
+
+ assert_eq!(tree.assigned_slot(named), Some(first_named));
+ assert_eq!(tree.assigned_slot(default_text), Some(default_slot));
+ assert_eq!(tree.slot_rendered_children(first_named), Some(vec![named]));
+ assert_eq!(
+ tree.slot_rendered_children(duplicate_named),
+ Some(vec![fallback])
+ );
+ assert_eq!(
+ tree.slot_rendered_children(default_slot),
+ Some(vec![default_text])
+ );
+ }
+
#[test]
fn document_id_lookup_never_exposes_a_shadow_descendant() {
let tree = DomTree::new();
diff --git a/crates/obscura-render/src/css.rs b/crates/obscura-render/src/css.rs
index 06d7493d..68e9cfc8 100644
--- a/crates/obscura-render/src/css.rs
+++ b/crates/obscura-render/src/css.rs
@@ -1569,11 +1569,16 @@ struct Rule {
}
#[derive(Default)]
-struct ShadowHostDeclarations {
+struct ShadowScopeDeclarations {
normal: String,
important: String,
}
+pub(crate) struct ShadowSlottedScope<'a> {
+ pub sheet: &'a Stylesheet,
+ pub host: NodeId,
+}
+
fn append_declaration_stream(target: &mut String, declarations: &str) {
if declarations.trim().is_empty() {
return;
@@ -2323,6 +2328,9 @@ pub struct Stylesheet {
/// selector index and must only be matched with that tree's explicit host
/// scope.
host_rules: Vec<usize>,
+ /// `::slotted()` rules are matched against assigned light children with
+ /// this stylesheet's host supplied as the selector tree scope.
+ slotted_rules: Vec<usize>,
invalidation_map: InvalidationMap,
registered_custom_properties: HashMap<String, RegisteredCustomProperty>,
/// Index zero is the unconditional sentinel.
@@ -2649,6 +2657,7 @@ impl Stylesheet {
let mut sheet = Stylesheet {
rules: Vec::new(),
host_rules: Vec::new(),
+ slotted_rules: Vec::new(),
invalidation_map: InvalidationMap::default(),
registered_custom_properties: HashMap::new(),
container_conditions: vec![ContainerConditionNode {
@@ -2875,6 +2884,9 @@ impl Stylesheet {
if sel.matches_featureless_host() {
sheet.host_rules.push(idx);
}
+ if sel.is_slotted() {
+ sheet.slotted_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");
@@ -3200,7 +3212,7 @@ impl Stylesheet {
matcher: &mut Matcher,
host: NodeId,
mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,
- ) -> ShadowHostDeclarations {
+ ) -> ShadowScopeDeclarations {
let mut normal = Vec::new();
let mut important = Vec::new();
for &index in &self.host_rules {
@@ -3245,7 +3257,72 @@ impl Stylesheet {
)
});
- let mut declarations = ShadowHostDeclarations::default();
+ let mut declarations = ShadowScopeDeclarations::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
+ }
+
+ fn shadow_slotted_declarations(
+ &self,
+ tree: &DomTree,
+ matcher: &mut Matcher,
+ subject: NodeId,
+ host: NodeId,
+ mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,
+ ) -> ShadowScopeDeclarations {
+ let mut normal = Vec::new();
+ let mut important = Vec::new();
+ for &index in &self.slotted_rules {
+ let rule = &self.rules[index];
+ if matcher.matches_in_shadow_scope(tree, subject, &rule.sel, host)
+ && self.container_condition_is_active(
+ rule.container_condition_id,
+ subject,
+ 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 = ShadowScopeDeclarations::default();
for &(_, _, index) in &normal {
append_declaration_stream(&mut declarations.normal, &self.rules[index].normal_decls);
}
@@ -3321,6 +3398,7 @@ impl Stylesheet {
parent_props,
inline_css,
None,
+ &[],
None,
animation_sample,
animation_timeline,
@@ -3387,20 +3465,22 @@ impl Stylesheet {
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(
+ /// Apply document author rules together with `:host` and `::slotted()`
+ /// rules from the element's applicable shadow scopes. Encapsulation
+ /// context precedes specificity and layer order: shadow normal declarations
+ /// are weaker than document/inline normal declarations, while shadow
+ /// `!important` is stronger than document/inline author-important.
+ pub(crate) fn apply_with_shadow_scopes_at_animation_time(
&self,
- shadow_host_sheet: &Stylesheet,
+ shadow_host_sheet: Option<&Stylesheet>,
+ slotted_scopes: &[ShadowSlottedScope<'_>],
tree: &DomTree,
matcher: &mut Matcher,
nid: NodeId,
@@ -3424,7 +3504,8 @@ impl Stylesheet {
style,
parent_props,
inline_css,
- Some(shadow_host_sheet),
+ shadow_host_sheet,
+ slotted_scopes,
evaluator,
animation_sample,
animation_timeline,
@@ -3443,6 +3524,7 @@ impl Stylesheet {
parent_props: &HashMap<String, String>,
inline_css: Option<&str>,
shadow_host_sheet: Option<&Stylesheet>,
+ slotted_scopes: &[ShadowSlottedScope<'_>],
mut evaluator: Option<&mut ContainerQueryEvaluator<'_>>,
animation_sample: crate::AnimationSample,
animation_timeline: &mut crate::AnimationTimelineState,
@@ -3452,6 +3534,40 @@ impl Stylesheet {
sheet.shadow_host_declarations(tree, matcher, nid, evaluator.as_deref_mut())
})
.unwrap_or_default();
+ let mut shadow_scope_declarations = ShadowScopeDeclarations::default();
+ append_declaration_stream(
+ &mut shadow_scope_declarations.normal,
+ &shadow_host_declarations.normal,
+ );
+ let mut slotted_declarations = Vec::with_capacity(slotted_scopes.len());
+ for scope in slotted_scopes {
+ slotted_declarations.push(scope.sheet.shadow_slotted_declarations(
+ tree,
+ matcher,
+ nid,
+ scope.host,
+ evaluator.as_deref_mut(),
+ ));
+ }
+ // Match Gecko's ShadowCascadeOrder: normal declarations progress from
+ // the host's own (innermost) tree through outer slot scopes toward the
+ // document. Important declarations reverse that order.
+ for declarations in slotted_declarations.iter().rev() {
+ append_declaration_stream(
+ &mut shadow_scope_declarations.normal,
+ &declarations.normal,
+ );
+ }
+ for declarations in &slotted_declarations {
+ append_declaration_stream(
+ &mut shadow_scope_declarations.important,
+ &declarations.important,
+ );
+ }
+ append_declaration_stream(
+ &mut shadow_scope_declarations.important,
+ &shadow_host_declarations.important,
+ );
// 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
@@ -3582,8 +3698,8 @@ 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 shadow_normal_flags = declaration_stream_flags(&shadow_host_declarations.normal);
- let shadow_important_flags = declaration_stream_flags(&shadow_host_declarations.important);
+ let shadow_normal_flags = declaration_stream_flags(&shadow_scope_declarations.normal);
+ let shadow_important_flags = declaration_stream_flags(&shadow_scope_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
@@ -3628,7 +3744,7 @@ impl Stylesheet {
}
};
if shadow_normal_flags.has_custom_properties {
- collect_custom(&shadow_host_declarations.normal);
+ collect_custom(&shadow_scope_declarations.normal);
}
for &(_, _, i) in &normal_matched {
let rule = &self.rules[i];
@@ -3649,7 +3765,7 @@ impl Stylesheet {
collect_custom(&inline_important);
}
if shadow_important_flags.has_custom_properties {
- collect_custom(&shadow_host_declarations.important);
+ collect_custom(&shadow_scope_declarations.important);
}
let mut resolved_props = parent_props.clone();
@@ -3749,7 +3865,7 @@ impl Stylesheet {
// property. The style starts with its inherited scheme.
if shadow_normal_flags.has_color_scheme {
let expanded = substitute_declarations(
- &shadow_host_declarations.normal,
+ &shadow_scope_declarations.normal,
props,
shadow_normal_flags.has_var,
);
@@ -3805,7 +3921,7 @@ impl Stylesheet {
}
if shadow_important_flags.has_color_scheme {
let expanded = substitute_declarations(
- &shadow_host_declarations.important,
+ &shadow_scope_declarations.important,
props,
shadow_important_flags.has_var,
);
@@ -3819,7 +3935,7 @@ impl Stylesheet {
// Pass 2: apply normal declarations with `var()` substituted against
// the resolved custom-property map.
let expanded = substitute_declarations(
- &shadow_host_declarations.normal,
+ &shadow_scope_declarations.normal,
props,
shadow_normal_flags.has_var,
);
@@ -3869,7 +3985,7 @@ impl Stylesheet {
}
if shadow_important_flags.has_animation {
let expanded = substitute_declarations(
- &shadow_host_declarations.important,
+ &shadow_scope_declarations.important,
props,
shadow_important_flags.has_var,
);
@@ -3921,7 +4037,7 @@ impl Stylesheet {
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,
+ &shadow_scope_declarations.important,
props,
shadow_important_flags.has_var,
);
diff --git a/crates/obscura-render/src/dom.rs b/crates/obscura-render/src/dom.rs
index b4c4357b..01f82a35 100644
--- a/crates/obscura-render/src/dom.rs
+++ b/crates/obscura-render/src/dom.rs
@@ -2258,9 +2258,28 @@ fn cascade_walk(
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,
+ let mut slotted_scopes = Vec::new();
+ let mut assigned_slot = tree.assigned_slot(id);
+ for _ in 0..tree.len() {
+ let Some(slot) = assigned_slot else { break };
+ let Some(root) = tree.containing_shadow_root(slot) else {
+ break;
+ };
+ let Some(host) = tree.shadow_root_info(root).map(|root| root.host) else {
+ break;
+ };
+ if let Some(shadow_sheet) = shadow_sheets.get(&root) {
+ slotted_scopes.push(crate::css::ShadowSlottedScope {
+ sheet: shadow_sheet,
+ host,
+ });
+ }
+ assigned_slot = tree.assigned_slot(slot);
+ }
+ let effective_props = if shadow_host_sheet.is_some() || !slotted_scopes.is_empty() {
+ sheet.apply_with_shadow_scopes_at_animation_time(
+ shadow_host_sheet.map(|sheet| &**sheet),
+ &slotted_scopes,
tree,
matcher,
id,
@@ -8430,14 +8449,6 @@ fn resolve_static_positions_and_reparent(
}
}
-fn is_html_slot(tree: &DomTree, id: NodeId) -> bool {
- tree.get_node(id).is_some_and(|node| {
- node.as_element().is_some_and(|name| {
- name.ns.as_ref() == "http://www.w3.org/1999/xhtml" && name.local.as_ref() == "slot"
- })
- })
-}
-
/// Children which need computed-value resolution below `id`.
///
/// CSSOM still exposes and styles unslotted light DOM, so this differs from
@@ -8458,58 +8469,6 @@ fn style_children(tree: &DomTree, id: NodeId) -> Vec<NodeId> {
/// host's matching slottables. Text and element light children are slottable;
/// comments and other node kinds are not. When no node is assigned, the slot's
/// ordinary children remain its fallback content.
-fn assigned_nodes_for_slot(tree: &DomTree, slot: NodeId) -> Option<Vec<NodeId>> {
- if !is_html_slot(tree, slot) {
- return None;
- }
- let root = tree.containing_shadow_root(slot)?;
- let host = tree.shadow_root_info(root)?.host;
- let name = tree
- .get_node(slot)
- .and_then(|node| node.get_attribute("name").map(str::to_owned))
- .unwrap_or_default();
-
- let is_same_name_slot = |candidate: NodeId| {
- is_html_slot(tree, candidate)
- && tree
- .get_node(candidate)
- .and_then(|node| node.get_attribute("name").map(str::to_owned))
- .unwrap_or_default()
- == name
- };
- if tree
- .descendants(root)
- .into_iter()
- .take_while(|candidate| *candidate != slot)
- .any(is_same_name_slot)
- {
- return Some(tree.children(slot));
- }
-
- let assigned = tree
- .children(host)
- .into_iter()
- .filter(|candidate| {
- let Some(node) = tree.get_node(*candidate) else {
- return false;
- };
- let candidate_name = if node.is_element() {
- node.get_attribute("slot").unwrap_or("")
- } else if node.text_content_of_text_node().is_some() {
- ""
- } else {
- return false;
- };
- candidate_name == name
- })
- .collect::<Vec<_>>();
- Some(if assigned.is_empty() {
- tree.children(slot)
- } else {
- assigned
- })
-}
-
/// Return the flattened-tree children that generate boxes for `id`.
pub(crate) fn rendered_children(tree: &DomTree, id: NodeId) -> Vec<NodeId> {
if let Some(shadow_children) = tree.shadow_children(id) {
@@ -8518,7 +8477,7 @@ pub(crate) fn rendered_children(tree: &DomTree, id: NodeId) -> Vec<NodeId> {
// slot insertion points below; unslotted children generate no boxes.
return shadow_children;
}
- if let Some(assigned_or_fallback) = assigned_nodes_for_slot(tree, id) {
+ if let Some(assigned_or_fallback) = tree.slot_rendered_children(id) {
return assigned_or_fallback;
}
@@ -8565,25 +8524,10 @@ pub(crate) fn rendered_parent(tree: &DomTree, id: NodeId) -> Option<NodeId> {
if let Some(root) = tree.shadow_root_info(parent) {
return Some(root.host);
}
- let Some(shadow_root) = tree.shadow_root(parent) else {
+ if tree.shadow_root(parent).is_none() {
return Some(parent);
- };
- let node = tree.get_node(id)?;
- let name = if node.is_element() {
- node.get_attribute("slot").unwrap_or("")
- } else if node.text_content_of_text_node().is_some() {
- ""
- } else {
- return None;
- };
- tree.descendants(shadow_root).into_iter().find(|candidate| {
- is_html_slot(tree, *candidate)
- && tree
- .get_node(*candidate)
- .and_then(|slot| slot.get_attribute("name").map(str::to_owned))
- .unwrap_or_default()
- == name
- })
+ }
+ tree.assigned_slot(id)
}
/// Flattened-tree descendants in preorder, excluding `root`.
@@ -14055,6 +13999,63 @@ mod tests {
assert_eq!(second.margin.left, 0.0, "first shadow root cannot leak");
}
+ #[test]
+ fn slotted_rules_style_only_assigned_light_children_with_shadow_cascade_order() {
+ let tree = parse_html(
+ r#"<style>
+ .item { width:120px; height:var(--normal-size); --normal-size:33px }
+ .item { margin-left:5px !important; padding-left:var(--critical) !important; --critical:7px !important }
+ </style>
+ <x-one id="host-one">
+ <span id="assigned-one" class="item" slot="title" style="margin-left:9px !important"></span>
+ <span id="unslotted" class="item" slot="missing"></span>
+ </x-one>
+ <x-two id="host-two"><span id="assigned-two" class="item"></span></x-two>
+ <div id="source-one">
+ <style>
+ ::slotted(.item) { display:block; width:40px; --normal-size:11px; border-left:3px solid }
+ .wrapper slot.named::slotted(.item) { margin-left:21px !important; padding-left:var(--critical) !important; --critical:17px !important }
+ ::slotted([hidden]) { border-top:19px solid }
+ .item { border-right:23px solid }
+ </style>
+ <div class="wrapper"><slot class="named" name="title"></slot></div>
+ </div>
+ <div id="source-two">
+ <style>::slotted(.item) { display:block; border-bottom:4px solid }</style>
+ <slot></slot>
+ </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();
+ let assigned_one = tree.get_element_by_id("assigned-one").unwrap();
+ let assigned_two = tree.get_element_by_id("assigned-two").unwrap();
+ let unslotted = tree.get_element_by_id("unslotted").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[&assigned_one];
+ let second = &laid.styles[&assigned_two];
+ let hidden = &laid.styles[&unslotted];
+
+ assert_eq!(first.display, crate::Display::Block);
+ assert_eq!(first.width, crate::Dimension::Px(120.0), "document normal wins");
+ assert_eq!(first.height, crate::Dimension::Px(33.0), "document custom property wins");
+ assert_eq!(first.margin.left, 21.0, "shadow important beats inline important");
+ assert_eq!(first.padding.left, 17.0, "shadow important custom property wins");
+ assert_eq!(first.border.left, 3.0, "slot-qualified selector matches");
+ assert_eq!(first.border.right, 0.0, "ordinary shadow selector stays isolated");
+ assert_eq!(first.border.top, 0.0, "slotted argument must match");
+ assert_eq!(laid.rects[&assigned_one].width, 140.0);
+
+ assert_eq!(second.border.bottom, 4.0);
+ assert_eq!(second.border.left, 0.0, "first shadow root cannot leak");
+ assert_eq!(hidden.border.left, 0.0, "unassigned light child is not slotted");
+ assert!(!laid.rects.contains_key(&unslotted));
+ }
+
#[test]
fn direct_shadow_inline_block_is_blockified_as_a_flex_item() {
let tree = parse_html(