dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / css / style_computer_1.lucb
#==============================================================================================
#
# style_computer_1 - CSS::StyleComputer: construction and collecting the matching rules
#
# DESCRIPTION:
# Port of LibWeb/CSS/StyleComputer.h's inline members (CountingBloomFilter, the accessors,
# the computation-context cache helpers and should_reject_with_ancestor_filter) and
# LibWeb/CSS/StyleComputer.cpp (lines 1-438): MatchingRule's helpers, the constructor
# and visit_edges, the user-agent style sheet sources, the rule cache of a cascade origin
# and layer, the invalidation plans and :has() metadata of the scope's rule cache,
# collect_matching_rules and sort_matching_rules.
#
# CountingBloomFilter is a C++ template over its counter type and key bits; StyleComputer
# instantiates it once, as CountingBloomFilter<u8, 14>, so its members are ported for
# that instantiation (the struct stays generic; see types_style_computer). The lambdas
# are private functions with capture structs (DESIGN.md ยง2.7).
#
# Copyright (c) 2018-2025, Andreas Kling <andreas@ladybird.org>
# Copyright (c) 2021, the SerenityOS developers.
# Copyright (c) 2021-2025, Sam Atkins <sam@ladybird.org>
# Copyright (c) 2024, Matthew Olsson <mattco@serenityos.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: CountingBloomFilter (StyleComputer.h) ===================================================
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:33 Web::CSS::CountingBloomFilter::CountingBloomFilter<CounterType, key_bits>.
pub func css_counting_bloom_filter_construct(this: CssCountingBloomFilter[u8]*):
# `CountingBloomFilter() { }` leaves the buckets as they are; StyleComputer clears the filter before use.
return
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:35 Web::CSS::CountingBloomFilter::clear.
pub func css_counting_bloom_filter_clear(this: CssCountingBloomFilter[u8]*):
memory.set(this.m_buckets, 0)
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:37 Web::CSS::CountingBloomFilter::increment.
pub func css_counting_bloom_filter_increment(this: CssCountingBloomFilter[u8]*, key: u32):
let first = css_counting_bloom_filter_bucket1(this, key)
if *first < ak.u8_max:
*first += 1
let second = css_counting_bloom_filter_bucket2(this, key)
if *second < ak.u8_max:
*second += 1
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:47 Web::CSS::CountingBloomFilter::decrement.
pub func css_counting_bloom_filter_decrement(this: CssCountingBloomFilter[u8]*, key: u32):
let first = css_counting_bloom_filter_bucket1(this, key)
if *first < ak.u8_max:
# A counter is never decremented below the number of increments it saw (C++'s `--first` on a u8).
*first -%= 1
let second = css_counting_bloom_filter_bucket2(this, key)
if *second < ak.u8_max:
*second -%= 1
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:57 Web::CSS::CountingBloomFilter::may_contain.
pub func css_counting_bloom_filter_may_contain(this: const CssCountingBloomFilter[u8]*, hash_: u32) -> bool:
return css_counting_bloom_filter_bucket1_const(this, hash_) != 0 and css_counting_bloom_filter_bucket2_const(this, hash_) != 0
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:66 Web::CSS::CountingBloomFilter::hash1.
pub func css_counting_bloom_filter_hash1(this: const CssCountingBloomFilter[u8]*, key: u32) -> u32:
return key & css_counting_bloom_filter_key_mask
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:67 Web::CSS::CountingBloomFilter::hash2.
pub func css_counting_bloom_filter_hash2(this: const CssCountingBloomFilter[u8]*, key: u32) -> u32:
return (key >> 16) & css_counting_bloom_filter_key_mask
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:69 Web::CSS::CountingBloomFilter::bucket1.
pub func css_counting_bloom_filter_bucket1(this: CssCountingBloomFilter[u8]*, key: u32) -> u8*:
return &this.m_buckets[css_counting_bloom_filter_hash1(this, key)]
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:70 Web::CSS::CountingBloomFilter::bucket2.
pub func css_counting_bloom_filter_bucket2(this: CssCountingBloomFilter[u8]*, key: u32) -> u8*:
return &this.m_buckets[css_counting_bloom_filter_hash2(this, key)]
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:71 Web::CSS::CountingBloomFilter::bucket1.
pub func css_counting_bloom_filter_bucket1_const(this: const CssCountingBloomFilter[u8]*, key: u32) -> u8:
return this.m_buckets[css_counting_bloom_filter_hash1(this, key)]
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:72 Web::CSS::CountingBloomFilter::bucket2.
pub func css_counting_bloom_filter_bucket2_const(this: const CssCountingBloomFilter[u8]*, key: u32) -> u8:
return this.m_buckets[css_counting_bloom_filter_hash2(this, key)]
# mark: StyleComputer.h =========================================================================
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:95 Web::CSS::StyleComputer::document.
pub func css_style_computer_document(this: CssStyleComputer*) -> DomDocument*:
return this.m_document
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:96 Web::CSS::StyleComputer::document.
pub func css_style_computer_document_const(this: CssStyleComputer*) -> DomDocument*:
return this.m_document
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:124 Web::CSS::StyleComputer::set_viewport_rect.
pub func css_style_computer_set_viewport_rect(this: CssStyleComputer*, viewport_rect: gfx.CssPixelRect):
this.m_viewport_rect = viewport_rect
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:178 Web::CSS::StyleComputer::viewport_rect.
pub func css_style_computer_viewport_rect(this: CssStyleComputer*) -> gfx.CssPixelRect:
return this.m_viewport_rect
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:211 Web::CSS::StyleComputer::clear_computation_context_caches.
pub func css_style_computer_clear_computation_context_caches(this: CssStyleComputer*):
this.m_cached_font_computation_context = none
this.m_cached_line_height_computation_context = none
this.m_cached_generic_computation_context = none
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:218 Web::CSS::StyleComputer::computation_context_cache_is_empty.
pub func css_style_computer_computation_context_cache_is_empty(this: CssStyleComputer*) -> bool:
return this.m_cached_font_computation_context == none and this.m_cached_line_height_computation_context == none and this.m_cached_generic_computation_context == none
## Ported from Libraries/LibWeb/CSS/StyleComputer.h:229 Web::CSS::StyleComputer::should_reject_with_ancestor_filter.
pub func css_style_computer_should_reject_with_ancestor_filter(this: CssStyleComputer*, selector: const CssSelector*) -> bool:
let ancestor_filter = this.m_ancestor_filter else trap("VERIFY: the style computer has an ancestor filter")
for hash_ in css_selector_ancestor_hashes(selector):
if hash_ == 0:
break
if not css_counting_bloom_filter_may_contain(ancestor_filter, hash_):
return true
return false
# mark: MatchingRule ============================================================================
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:97 Web::CSS::MatchingRule::declaration.
pub func css_matching_rule_declaration(this: const CssMatchingRule*) -> CssStyleProperties*:
let rule = this.rule else trap("VERIFY: the matching rule has a rule")
if css_rule_type(rule) == CssRuleType.style:
return css_style_rule_declaration(as_css_style_rule(rule))
if css_rule_type(rule) == CssRuleType.nested_declarations:
return css_nested_declarations_declaration(as_css_nested_declarations(rule))
trap("VERIFY_NOT_REACHED")
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:106 Web::CSS::MatchingRule::absolutized_selectors.
pub func css_matching_rule_absolutized_selectors(this: const CssMatchingRule*) -> ak.Vector[CssSelector*]:
let rule = this.rule else trap("VERIFY: the matching rule has a rule")
if css_rule_type(rule) == CssRuleType.style:
return css_style_rule_absolutized_selectors(as_css_style_rule(rule))
if css_rule_type(rule) == CssRuleType.nested_declarations:
return css_style_rule_absolutized_selectors(css_nested_declarations_parent_style_rule(as_css_nested_declarations(rule)))
trap("VERIFY_NOT_REACHED")
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:115 Web::CSS::MatchingRule::qualified_layer_name.
pub func css_matching_rule_qualified_layer_name(this: const CssMatchingRule*) -> ak.FlyString:
let rule = this.rule else trap("VERIFY: the matching rule has a rule")
if css_rule_type(rule) == CssRuleType.style:
return css_style_rule_qualified_layer_name(as_css_style_rule(rule))
if css_rule_type(rule) == CssRuleType.nested_declarations:
return css_style_rule_qualified_layer_name(css_nested_declarations_parent_style_rule(as_css_nested_declarations(rule)))
trap("VERIFY_NOT_REACHED")
# mark: Construction ============================================================================
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:124 Web::CSS::StyleComputer::StyleComputer.
pub func css_style_computer_construct(this: CssStyleComputer*, document: DomDocument*):
this.m_document = document
let default_font = platform_font_plugin_default_font(platform_font_plugin_the(), 16.0) else trap("VERIFY: the font plugin has a default font")
this.m_default_font_metrics = css_length_font_metrics_new(gfx.css_pixels_from_int(16), web_fonts.font_pixel_metrics(default_font), css_initial_values_line_height())
this.m_root_element_font_metrics = this.m_default_font_metrics
let ancestor_filter = new CssCountingBloomFilter[u8] else trap("out of memory")
css_counting_bloom_filter_construct(ancestor_filter)
this.m_ancestor_filter = ancestor_filter
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:134 Web::CSS::StyleComputer::visit_edges (override).
pub func css_style_computer_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
let this = (CssStyleComputer*)base
gc.cell_visit_edges_impl(base, visitor)
gc.cell_visitor_visit_t_2(visitor, this.m_document)
# `visitor.visit(*m_has_result_cache)`: Visitor::visit(HashMap) visits the keys and values it has an
# overload for, and HasResultCacheKey and HasMatchResult have none, so nothing is visited.
if let context = this.m_cached_font_computation_context:
var font_computation_context = context
css_computation_context_visit_edges(&font_computation_context, visitor)
if let context = this.m_cached_line_height_computation_context:
var line_height_computation_context = context
css_computation_context_visit_edges(&line_height_computation_context, visitor)
if let context = this.m_cached_generic_computation_context:
var generic_computation_context = context
css_computation_context_visit_edges(&generic_computation_context, visitor)
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:149 Web::CSS::StyleComputer::user_agent_style_sheet_source.
pub func css_style_computer_user_agent_style_sheet_source(name: ak.StringView) -> ak.String?:
if ak.string_view_equals(&name, "CSS/Default.css"):
return ak.string_from_str(css_default_stylesheet_source)
if ak.string_view_equals(&name, "CSS/QuirksMode.css"):
return ak.string_from_str(css_quirks_mode_stylesheet_source)
if ak.string_view_equals(&name, "MathML/Default.css"):
return ak.string_from_str(css_mathml_stylesheet_source)
if ak.string_view_equals(&name, "SVG/Default.css"):
return ak.string_from_str(css_svg_stylesheet_source)
return none
# mark: Rule caches and invalidation plans ======================================================
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:167 Web::CSS::StyleComputer::rule_cache_for_cascade_origin.
pub func css_style_computer_rule_cache_for_cascade_origin(this: CssStyleComputer*, cascade_origin: CssCascadeOrigin, qualified_layer_name: ak.FlyString?, shadow_root: DomShadowRoot*?) -> const CssRuleCache*?:
var style_scope: CssStyleScope* = ---
if let root = shadow_root:
style_scope = dom_shadow_root_style_scope(root)
else:
style_scope = dom_document_style_scope(css_style_computer_document(this))
css_style_scope_build_rule_cache_if_needed(style_scope)
let rule_cache = style_scope.m_rule_cache else trap("VERIFY: the rule cache was built")
var rule_caches_by_layer: const CssRuleCaches* = ---
match cascade_origin:
.author:
rule_caches_by_layer = &rule_cache.author_rule_cache
.user:
rule_caches_by_layer = &rule_cache.user_rule_cache
.user_agent:
rule_caches_by_layer = &rule_cache.user_agent_rule_cache
_:
trap("VERIFY_NOT_REACHED")
let layer_name = qualified_layer_name else return &rule_caches_by_layer.main
let layer_rule_cache = ak.hash_map_get_k_const(&rule_caches_by_layer.by_layer, layer_name) else return none
return *layer_rule_cache
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:191 Web::CSS::filter_namespace_rule.
func css_filter_namespace_rule(element_namespace_uri: ak.FlyString?, rule: const CssMatchingRule*) -> bool:
# FIXME: Filter out non-default namespace using prefixes
if rule.default_namespace != none and not css_optional_fly_strings_equal(element_namespace_uri, rule.default_namespace):
return false
return true
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:199 Web::CSS::StyleComputer::invalidation_plan_for_properties.
pub func css_style_computer_invalidation_plan_for_properties(this: CssStyleComputer*, properties: const ak.Vector[CssInvalidationSetProperty]*, style_scope: const CssStyleScope*) -> CssInvalidationPlan*:
let result = css_invalidation_plan_create()
let rule_cache = style_scope.m_rule_cache else return result
let invalidation_plans = &rule_cache.style_invalidation_data.invalidation_plans
for property in ak.vector_span_const(properties):
if let plan = ak.hash_map_get_k_const(invalidation_plans, property):
css_invalidation_plan_include_all_from(result, **plan)
if result.invalidate_whole_subtree:
break
return result
## has_invalidation_metadata_for_property's `return_bucket_if_present` lambda, for the maps keyed by name.
func css_style_computer_return_bucket_if_present(map: const ak.HashMap[ak.FlyString, ak.Vector[CssHasInvalidationMetadata], ak.FlyStringTraits]*, key: ak.FlyString) -> const ak.Vector[CssHasInvalidationMetadata]*?:
return ak.hash_map_get_k_const(map, key)
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:215 Web::CSS::StyleComputer::has_invalidation_metadata_for_property.
pub func css_style_computer_has_invalidation_metadata_for_property(this: CssStyleComputer*, property: const CssInvalidationSetProperty*, style_scope: const CssStyleScope*) -> const ak.Vector[CssHasInvalidationMetadata]*?:
let rule_cache = style_scope.m_rule_cache else return none
let data = &rule_cache.style_invalidation_data
match property.type_:
.id:
return css_style_computer_return_bucket_if_present(&data.ids_used_in_has_selectors, css_invalidation_set_property_name(property))
.class_:
return css_style_computer_return_bucket_if_present(&data.class_names_used_in_has_selectors, css_invalidation_set_property_name(property))
.attribute:
return css_style_computer_return_bucket_if_present(&data.attribute_names_used_in_has_selectors, css_invalidation_set_property_name(property))
.tag_name:
return css_style_computer_return_bucket_if_present(&data.tag_names_used_in_has_selectors, css_invalidation_set_property_name(property))
.pseudo_class:
match property.value:
.pseudo_class(pseudo_class):
return ak.hash_map_get_k_const(&data.pseudo_classes_used_in_has_selectors, pseudo_class)
_:
trap("VERIFY: Variant::get<PseudoClass>")
_:
return none
# mark: collect_matching_rules ==================================================================
## The state collect_matching_rules' lambdas capture.
struct CssStyleComputerCollectMatchingRules:
var this: CssStyleComputer*
var abstract_element: DomAbstractElement
var shadow_root: DomShadowRoot*?
var element_shadow_root: DomShadowRoot*?
var element_namespace_uri: ak.FlyString?
var rules_to_run: ak.Vector[CssStyleComputerScopedMatchingRule]
# The `rule_root` of the add_rules_from_cache call in progress.
var rule_root: DomShadowRoot*?
## collect_matching_rules' `add_rule_to_run` lambda.
func css_style_computer_add_rule_to_run(captures: CssStyleComputerCollectMatchingRules*, rule_to_run: const CssMatchingRule*, rule_root: DomShadowRoot*?):
# FIXME: This needs to be revised when adding support for the ::shadow selector, as it needs to cross shadow boundaries.
let from_user_agent_or_user_stylesheet = rule_to_run.cascade_origin == CssCascadeOrigin.user_agent or rule_to_run.cascade_origin == CssCascadeOrigin.user
# NOTE: Inside shadow trees, we only match rules that are defined in the shadow tree's style sheets.
# Exceptions are:
# - the shadow tree's *shadow host*, which needs to match :host rules from inside the shadow root.
# - ::slotted() rules, which need to match elements assigned to slots from inside the shadow root.
# - UA or User style sheets don't have a scope, so they are always relevant.
# FIXME: We should reorganize the data so that the document-level StyleComputer doesn't cache *all* rules,
# but instead we'd have some kind of "style scope" at the document level, and also one for each shadow root.
# Then we could only evaluate rules from the current style scope.
var shadow_root_uses_document_style_sheets = false
if let shadow_root = captures.shadow_root:
shadow_root_uses_document_style_sheets = rule_root == none and dom_shadow_root_uses_document_style_sheets(shadow_root)
let rule_is_relevant_for_current_scope = rule_root == captures.shadow_root or (captures.element_shadow_root != none and rule_root == captures.element_shadow_root) or from_user_agent_or_user_stylesheet or rule_to_run.slotted or rule_to_run.contains_part_pseudo_element or shadow_root_uses_document_style_sheets
if not rule_is_relevant_for_current_scope:
return
let selector = rule_to_run.selector
if css_selector_can_use_ancestor_filter(selector) and css_style_computer_should_reject_with_ancestor_filter(captures.this, selector):
return
ak.vector_unchecked_append_u(&captures.rules_to_run, CssStyleComputerScopedMatchingRule(rule = rule_to_run, shadow_root = rule_root))
## collect_matching_rules' `add_rules_to_run` lambda.
func css_style_computer_add_rules_to_run(captures: CssStyleComputerCollectMatchingRules*, rules: const ak.Vector[CssMatchingRule]*, rule_root: DomShadowRoot*?):
ak.vector_grow_capacity(&captures.rules_to_run, ak.vector_size(&captures.rules_to_run) + ak.vector_size(rules))
let rule_span = ak.vector_span_const(rules)
if dom_abstract_element_pseudo_element(&captures.abstract_element) != none:
for rule in &rule_span:
if rule.contains_pseudo_element and css_filter_namespace_rule(captures.element_namespace_uri, rule):
css_style_computer_add_rule_to_run(captures, rule, rule_root)
else:
for rule in &rule_span:
if (rule.slotted or rule.contains_part_pseudo_element or not rule.contains_pseudo_element) and css_filter_namespace_rule(captures.element_namespace_uri, rule):
css_style_computer_add_rule_to_run(captures, rule, rule_root)
## add_rules_from_cache's for_each_matching_rules callback.
func css_style_computer_add_rules_from_cache_callback(context: void*?, matching_rules: const ak.Vector[CssMatchingRule]*) -> ak.IterationDecision:
let captures = (CssStyleComputerCollectMatchingRules*)(context else trap("no captures"))
css_style_computer_add_rules_to_run(captures, matching_rules, captures.rule_root)
return ak.IterationDecision.continue_
## collect_matching_rules' `add_rules_from_cache` lambda.
func css_style_computer_add_rules_from_cache(captures: CssStyleComputerCollectMatchingRules*, rule_cache: const CssRuleCache*, rule_root: DomShadowRoot*?):
captures.rule_root = rule_root
css_rule_cache_for_each_matching_rules(rule_cache, captures.abstract_element, ak.Function1[const ak.Vector[CssMatchingRule]*, ak.IterationDecision](call = css_style_computer_add_rules_from_cache_callback, context = captures))
## The slot an element (or slot) is assigned to (SlottableMixin::assigned_slot_internal).
func css_style_computer_assigned_slot(element: DomElement*) -> HtmlSlotElement*?:
return dom_slottable_mixin_assigned_slot_internal(&element.slottable_mixin)
## `node.first_flat_tree_ancestor_of_type<DOM::ShadowRoot>()`.
func css_style_computer_first_flat_tree_shadow_root_ancestor(node: DomNode*) -> DomShadowRoot*?:
let ancestor = dom_node_first_flat_tree_ancestor_of_type(node, &dom_shadow_root_class) else return none
return as_dom_shadow_root(ancestor)
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:244 Web::CSS::StyleComputer::collect_matching_rules.
pub func css_style_computer_collect_matching_rules(this: CssStyleComputer*, abstract_element: DomAbstractElement, cascade_origin: CssCascadeOrigin, attempted_pseudo_class_matches: CssPseudoClassBitmap*, qualified_layer_name: ak.FlyString? = none) -> ak.Vector[CssStyleComputerScopedMatchingRule]:
var subject = abstract_element
let element = dom_abstract_element_element(&subject)
let root_node = tree_node_root(element.dom_node())
let shadow_root = as_if_dom_shadow_root(root_node)
let element_shadow_root = dom_element_shadow_root(element)
let element_namespace_uri = dom_element_namespace_uri(element)
var shadow_host: DomElement*? = none
if element_shadow_root != none:
shadow_host = element
elif let root = shadow_root:
shadow_host = dom_document_fragment_host(root.dom_document_fragment())
var captures = CssStyleComputerCollectMatchingRules(
this = this,
abstract_element = abstract_element,
shadow_root = shadow_root,
element_shadow_root = element_shadow_root,
element_namespace_uri = element_namespace_uri,
rule_root = none,
)
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, none):
css_style_computer_add_rules_from_cache(&captures, rule_cache, none)
if let root = shadow_root:
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, root):
css_style_computer_add_rules_from_cache(&captures, rule_cache, root)
if let element_root = element_shadow_root:
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, element_root):
css_style_computer_add_rules_from_cache(&captures, rule_cache, element_root)
# Per "find flattened slotables" (https://dom.spec.whatwg.org/#find-flattened-slotables),
# a <slot> element whose root is a shadow root recurses into its own slottables instead of
# being appended itself, so ::slotted() must never match such an intermediate re-slotted slot.
var subject_is_reslotted_slot = false
if let subject_as_slot = as_if_html_slot_element(element):
subject_is_reslotted_slot = dom_node_is_shadow_root(tree_node_root(subject_as_slot.dom_node()))
# Walk up the slot chain for nested slots. An element can be assigned to a slot
# which is itself assigned to another slot in a parent shadow root. The ::slotted()
# pseudo-element matches elements assigned "after flattening", so we must collect
# slotted rules from every shadow root in the chain.
if not subject_is_reslotted_slot:
var slot = css_style_computer_assigned_slot(element)
while let current_slot = slot:
if let slot_shadow_root = as_if_dom_shadow_root(tree_node_root(current_slot.dom_node())):
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, slot_shadow_root):
css_style_computer_add_rules_to_run(&captures, &rule_cache.slotted_rules, slot_shadow_root)
slot = css_style_computer_assigned_slot(current_slot.dom_element())
# ::part() can apply to anything in a shadow tree, that is either an element with a `part` attribute or a pseudo-element.
# Rules from any ancestor style scope can apply, including from the element's own shadow root
# (for :host::part() within the shadow DOM's own stylesheet).
if let root = shadow_root:
if dom_abstract_element_pseudo_element(&subject) != none or dom_element_part_names(element).length != 0:
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, root):
css_style_computer_add_rules_to_run(&captures, &rule_cache.part_rules, root)
var part_shadow_root = css_style_computer_first_flat_tree_shadow_root_ancestor(element.dom_node())
while let current_part_shadow_root = part_shadow_root:
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, current_part_shadow_root):
css_style_computer_add_rules_to_run(&captures, &rule_cache.part_rules, current_part_shadow_root)
part_shadow_root = css_style_computer_first_flat_tree_shadow_root_ancestor(current_part_shadow_root.dom_node())
if let rule_cache = css_style_computer_rule_cache_for_cascade_origin(this, cascade_origin, qualified_layer_name, none):
css_style_computer_add_rules_to_run(&captures, &rule_cache.part_rules, none)
var matching_rules: ak.Vector[CssStyleComputerScopedMatchingRule]
ak.vector_ensure_capacity(&matching_rules, ak.vector_size(&captures.rules_to_run))
for rule_to_run in ak.vector_span_const(&captures.rules_to_run):
# NOTE: When matching an element that is itself a shadow host against a rule from
# outside its own shadow root, we must not use the element as the shadow host
# for traversal (which would confine traversal to the element itself).
# Instead, use the rule's shadow root's host, so that combinators can traverse
# up to the enclosing shadow host (e.g. for `:host(...) .descendant` selectors).
let rule = rule_to_run.rule
let rule_root = rule_to_run.shadow_root
var shadow_host_to_use = shadow_host
if dom_element_is_shadow_host(element) and rule_root != dom_element_shadow_root(element):
shadow_host_to_use = none
if let rule_shadow_root = rule_root:
shadow_host_to_use = dom_document_fragment_host(rule_shadow_root.dom_document_fragment())
let selector = rule.selector
var context = SelectorEngineMatchContext(
style_sheet_for_rule = rule.sheet else trap("VERIFY: the matching rule has a style sheet"),
subject = element,
rule_shadow_root = rule_root,
collect_per_element_selector_involvement_metadata = true,
has_result_cache = this.m_has_result_cache,
)
defer css_pseudo_class_bitmap_or_assign(attempted_pseudo_class_matches, context.attempted_pseudo_class_matches)
if css_selector_is_slotted(selector):
if css_style_computer_assigned_slot(element) == none or subject_is_reslotted_slot:
continue
# We're collecting rules for element, which is assigned to a slot.
# For ::slotted() matching, slot should be used as a subject instead of element,
# while element itself is saved in matching context, so selector engine could
# switch back to it when matching inside ::slotted() argument.
# For nested slots, find the slot that lives in the same shadow root as the rule.
var matching_slot: HtmlSlotElement*? = none
var slot = css_style_computer_assigned_slot(element)
while let current_slot = slot:
if as_if_dom_shadow_root(tree_node_root(current_slot.dom_node())) == rule_root:
matching_slot = current_slot
break
slot = css_style_computer_assigned_slot(current_slot.dom_element())
let found_slot = matching_slot else continue
context.slotted_element = element
context.subject = found_slot.dom_element()
# The slot lives inside a shadow tree. Derive the shadow host from the
# slot's containing shadow root so that combinators like
# `:host ::slotted(...)` can traverse from the slot to the shadow host.
var slot_shadow_host: DomElement*? = none
if let slot_shadow_root = as_if_dom_shadow_root(tree_node_root(found_slot.dom_node())):
slot_shadow_host = dom_document_fragment_host(slot_shadow_root.dom_document_fragment())
let slotted_subject = DomAbstractElement(m_element = found_slot.dom_element(), m_pseudo_element = css_data.PseudoElement.slotted, m_inheritance_override = none)
if not selector_engine_matches(selector, slotted_subject, slot_shadow_host, &context):
continue
elif not selector_engine_matches(selector, abstract_element, shadow_host_to_use, &context):
continue
ak.vector_append_t(&matching_rules, rule_to_run)
return matching_rules
## sort_matching_rules' comparator.
func css_matching_rule_less_than(context: void*?, a: const CssStyleComputerScopedMatchingRule*, b: const CssStyleComputerScopedMatchingRule*) -> bool:
let a_rule = a.rule
let b_rule = b.rule
if a_rule.specificity == b_rule.specificity:
if a_rule.style_sheet_index == b_rule.style_sheet_index:
return a_rule.rule_index < b_rule.rule_index
return a_rule.style_sheet_index < b_rule.style_sheet_index
return a_rule.specificity < b_rule.specificity
## Ported from Libraries/LibWeb/CSS/StyleComputer.cpp:425 Web::CSS::sort_matching_rules.
func css_sort_matching_rules(matching_rules: ak.Vector[CssStyleComputerScopedMatchingRule]*):
ak.quick_sort_t_collection_t_less_than(ak.vector_span(matching_rules), ak.Function2[const CssStyleComputerScopedMatchingRule*, const CssStyleComputerScopedMatchingRule*, bool](call = css_matching_rule_less_than, context = none))