Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / css / style_scope_1.lucb

#==============================================================================================
#
#   style_scope_1 - CSS::StyleScope: the rule caches of a document or shadow root
#
#   DESCRIPTION:
#       Port of LibWeb/CSS/StyleScope.cpp (lines 1-420) and StyleScope.h's inline members:
#       visiting the caches, StyleCache creation, building the rule cache (the user-agent,
#       user and author style sheets bucketed into RuleCaches per cascade layer, the
#       pseudo-class rule caches and the @keyframes sets), the user-agent style sheets and the
#       selector insights.
#
#       A StyleScope is embedded in its Document or ShadowRoot; a StyleCache is ref-counted in
#       C++ and a managed blob here (DESIGN.md §3.3), as are the per-layer RuleCaches
#       (NonnullOwnPtr) and the pseudo-class RuleCaches (OwnPtr). The lambdas are private
#       functions with capture structs (DESIGN.md §2.7).
#
#       Copyright (c) 2018-2025, Andreas Kling <andreas@ladybird.org>
#       Copyright (c) 2022-2025, Aliaksandr Kalenik <kalenik.aliaksandr@gmail.com>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Visiting and StyleCache =================================================================

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:30 Web::CSS::RuleCaches::visit_edges.
pub func css_rule_caches_visit_edges(this: CssRuleCaches*, visitor: gc.CellVisitor*):
    css_rule_cache_visit_edges(&this.main, visitor)
    for it in ak.hash_map_begin(&this.by_layer):
        css_rule_cache_visit_edges(it.value, visitor)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:38 Web::CSS::StyleCache::create.
pub func css_style_cache_create() -> CssStyleCache*:
    let style_cache = new CssStyleCache else trap("out of memory")
    ak.vector_append_t(&style_cache.qualified_layer_names_in_order, ak.FlyString())
    return style_cache

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:45 Web::CSS::StyleCache::create_for_style_scope.
pub func css_style_cache_create_for_style_scope(style_scope: CssStyleScope*) -> CssStyleCache*:
    let style_cache = css_style_cache_create()
    css_style_scope_populate_rule_cache(style_scope, style_cache)
    return style_cache

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:52 Web::CSS::StyleCache::visit_edges.
pub func css_style_cache_visit_edges(this: CssStyleCache*, visitor: gc.CellVisitor*):
    for cache in this.pseudo_class_rule_cache:
        if let rule_cache = cache:
            css_rule_cache_visit_edges(rule_cache, visitor)
    css_rule_caches_visit_edges(&this.author_rule_cache, visitor)
    css_rule_caches_visit_edges(&this.user_rule_cache, visitor)
    css_rule_caches_visit_edges(&this.user_agent_rule_cache, visitor)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:63 Web::CSS::StyleScope::visit_edges.
pub func css_style_scope_visit_edges(this: CssStyleScope*, visitor: gc.CellVisitor*):
    gc.cell_visitor_visit_t_2(visitor, this.m_node)
    gc.cell_visitor_visit_t(visitor, this.m_user_style_sheet)
    if let rule_cache = this.m_rule_cache:
        css_style_cache_visit_edges(rule_cache, visitor)
    # visitor.visit(m_pending_has_invalidations): the keys are the cells.
    for it in ak.ordered_hash_map_begin_const(&this.m_pending_has_invalidations):
        gc.cell_visitor_visit_t_2(visitor, it.key)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:72 Web::CSS::MatchingRule::visit_edges.
pub func css_matching_rule_visit_edges(this: CssMatchingRule*, visitor: gc.CellVisitor*):
    gc.cell_visitor_visit_t(visitor, this.rule)
    gc.cell_visitor_visit_t(visitor, this.sheet)

## RuleCache::visit_edges' `visit_vector` lambda.
func css_rule_cache_visit_vector(vector: ak.Vector[CssMatchingRule]*, visitor: gc.CellVisitor*):
    let rules = ak.vector_span(vector)
    for rule in &rules:
        css_matching_rule_visit_edges(rule, visitor)

## RuleCache::visit_edges' `visit_map` lambda.
func css_rule_cache_visit_map[KT: ak.Traits[ak.FlyString]](map: ak.HashMap[ak.FlyString, ak.Vector[CssMatchingRule], KT]*, visitor: gc.CellVisitor*):
    for it in ak.hash_map_begin(map):
        css_rule_cache_visit_vector(&it.value, visitor)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:78 Web::CSS::RuleCache::visit_edges.
pub func css_rule_cache_visit_edges(this: CssRuleCache*, visitor: gc.CellVisitor*):
    css_rule_cache_visit_map(&this.rules_by_id, visitor)
    css_rule_cache_visit_map(&this.rules_by_class, visitor)
    css_rule_cache_visit_map(&this.rules_by_tag_name, visitor)
    css_rule_cache_visit_map(&this.rules_by_attribute_name, visitor)
    for i in 0..<this.rules_by_pseudo_element.length:
        css_rule_cache_visit_vector(&this.rules_by_pseudo_element[i], visitor)
    css_rule_cache_visit_vector(&this.root_rules, visitor)
    css_rule_cache_visit_vector(&this.slotted_rules, visitor)
    css_rule_cache_visit_vector(&this.part_rules, visitor)
    css_rule_cache_visit_vector(&this.other_rules, visitor)

# mark: StyleScope.h ============================================================================

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:103 Web::CSS::StyleScope::StyleScope.
pub func css_style_scope_construct(this: CssStyleScope*, node: DomNode*):
    this.m_node = node
    # bool m_needs_counter_style_cache_update : 1 { true };
    this.m_needs_counter_style_cache_update = true
    this.m_is_doing_counter_style_cache_update = false

## Ported from Libraries/LibWeb/CSS/StyleScope.h:113 Web::CSS::StyleScope::node.
pub func css_style_scope_node(this: const CssStyleScope*) -> DomNode*:
    return this.m_node

## Ported from Libraries/LibWeb/CSS/StyleScope.h:116 Web::CSS::StyleScope::author_rule_cache.
pub func css_style_scope_author_rule_cache(this: const CssStyleScope*) -> const CssRuleCaches*:
    let rule_cache = this.m_rule_cache else trap("VERIFY: the style scope has a rule cache")
    return &rule_cache.author_rule_cache

## Ported from Libraries/LibWeb/CSS/StyleScope.h:117 Web::CSS::StyleScope::user_rule_cache.
pub func css_style_scope_user_rule_cache(this: const CssStyleScope*) -> const CssRuleCaches*:
    let rule_cache = this.m_rule_cache else trap("VERIFY: the style scope has a rule cache")
    return &rule_cache.user_rule_cache

## Ported from Libraries/LibWeb/CSS/StyleScope.h:118 Web::CSS::StyleScope::user_agent_rule_cache.
pub func css_style_scope_user_agent_rule_cache(this: const CssStyleScope*) -> const CssRuleCaches*:
    let rule_cache = this.m_rule_cache else trap("VERIFY: the style scope has a rule cache")
    return &rule_cache.user_agent_rule_cache

## Ported from Libraries/LibWeb/CSS/StyleScope.h:120 Web::CSS::StyleScope::has_valid_rule_cache.
pub func css_style_scope_has_valid_rule_cache(this: const CssStyleScope*) -> bool:
    return this.m_rule_cache != none

# mark: Building the rule cache =================================================================

## The captures of build_rule_cache's for_each_active_css_style_sheet lambda.
struct CssStyleScopeBuildRuleCacheSheets:
    var constructed_style_sheet: CssCssStyleSheet*?
    var saw_more_than_one_style_sheet: bool

## build_rule_cache's for_each_active_css_style_sheet lambda.
func css_style_scope_build_rule_cache_sheet(context: void*?, style_sheet: CssCssStyleSheet*):
    let captures = (CssStyleScopeBuildRuleCacheSheets*)(context else trap("no captures"))
    if captures.constructed_style_sheet != none:
        captures.saw_more_than_one_style_sheet = true
        return
    captures.constructed_style_sheet = style_sheet

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:108 Web::CSS::StyleScope::build_rule_cache.
pub func css_style_scope_build_rule_cache(this: CssStyleScope*):
    if let shadow_root = as_if_dom_shadow_root(this.m_node):
        var captures = CssStyleScopeBuildRuleCacheSheets(constructed_style_sheet = none, saw_more_than_one_style_sheet = false)
        dom_shadow_root_for_each_active_css_style_sheet(shadow_root, ak.Function1[CssCssStyleSheet*, unit](call = css_style_scope_build_rule_cache_sheet, context = &captures))

        if let constructed_style_sheet = captures.constructed_style_sheet:
            if not captures.saw_more_than_one_style_sheet and css_css_style_sheet_constructed(constructed_style_sheet) and page_user_style(dom_document_page(css_style_scope_document(this))) == none:
                this.m_rule_cache = css_css_style_sheet_shared_single_constructed_sheet_style_cache(constructed_style_sheet, this)
                return

    let style_cache = css_style_cache_create()
    this.m_rule_cache = style_cache
    css_style_scope_populate_rule_cache(this, style_cache)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:131 Web::CSS::StyleScope::populate_rule_cache.
pub func css_style_scope_populate_rule_cache(this: CssStyleScope*, style_cache: CssStyleCache*):
    css_style_scope_build_user_style_sheet_if_needed(this)

    css_style_scope_build_qualified_layer_names_cache(this, style_cache)

    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.hover] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.active] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.focus] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.focus_within] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.focus_visible] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.has] = new CssRuleCache else trap("out of memory")
    style_cache.pseudo_class_rule_cache[(usize)css_data.PseudoClass.target] = new CssRuleCache else trap("out of memory")

    css_style_scope_make_rule_cache_for_cascade_origin(this, CssCascadeOrigin.author, style_cache)
    css_style_scope_make_rule_cache_for_cascade_origin(this, CssCascadeOrigin.user, style_cache)
    css_style_scope_make_rule_cache_for_cascade_origin(this, CssCascadeOrigin.user_agent, style_cache)

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:150 Web::CSS::StyleScope::invalidate_rule_cache.
pub func css_style_scope_invalidate_rule_cache(this: CssStyleScope*):
    css_style_scope_invalidate_counter_style_cache(this)
    this.m_rule_cache = none

    # NOTE: We could be smarter about keeping the user rule cache, and style sheet.
    #       Currently we are re-parsing the user style sheet every time we build the caches,
    #       as it may have changed.
    this.m_user_style_sheet = none

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:161 Web::CSS::StyleScope::build_user_style_sheet_if_needed.
pub func css_style_scope_build_user_style_sheet_if_needed(this: CssStyleScope*):
    if this.m_user_style_sheet != none:
        return

    if let user_style_source = page_user_style(dom_document_page(css_style_scope_document(this))):
        var params: CssParsingParams = ---
        css_parsing_params_construct_dom_document(&params, css_style_scope_document(this))
        this.m_user_style_sheet = parse_css_stylesheet(params, ak.string_bytes_as_string_view(&user_style_source))

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:170 Web::CSS::StyleScope::build_rule_cache_if_needed.
pub func css_style_scope_build_rule_cache_if_needed(this: const CssStyleScope*):
    if css_style_scope_has_valid_rule_cache(this):
        return
    css_style_scope_build_rule_cache((CssStyleScope*)this)

# mark: The user-agent style sheets =============================================================

## `static GC::Root<CSSStyleSheet> sheet` of default_stylesheet().
var css_default_stylesheet_sheet: gc.Root[CssCssStyleSheet]

## `static GC::Root<CSSStyleSheet> sheet` of quirks_mode_stylesheet().
var css_quirks_mode_stylesheet_sheet: gc.Root[CssCssStyleSheet]

## `static GC::Root<CSSStyleSheet> sheet` of mathml_stylesheet().
var css_mathml_stylesheet_sheet: gc.Root[CssCssStyleSheet]

## `static GC::Root<CSSStyleSheet> sheet` of svg_stylesheet().
var css_svg_stylesheet_sheet: gc.Root[CssCssStyleSheet]

## The user-agent style sheets forgotten as their VM is destroyed (vm_destroy): they are cells of
## the internal CSS realm, and C++'s statics live as long as the process's one VM.
func css_forget_user_agent_stylesheets():
    gc.root_release(&css_default_stylesheet_sheet)
    gc.root_release(&css_quirks_mode_stylesheet_sheet)
    gc.root_release(&css_mathml_stylesheet_sheet)
    gc.root_release(&css_svg_stylesheet_sheet)

## `parse_css_stylesheet(CSS::Parser::ParsingParams(internal_css_realm(), Parser::IsUAStyleSheet::Yes), source)`.
func css_parse_user_agent_stylesheet(source: str) -> CssCssStyleSheet*:
    var params: CssParsingParams = ---
    css_parsing_params_construct_realm_css_is_ua_style_sheet(&params, internal_css_realm(), CssIsUaStyleSheet.yes)
    return parse_css_stylesheet(params, ak.sv(source))

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:177 Web::CSS::default_stylesheet.
func css_default_stylesheet() -> CssCssStyleSheet*:
    if gc.root_is_null(&css_default_stylesheet_sheet):
        css_default_stylesheet_sheet = gc.root_create(css_parse_user_agent_stylesheet(css_default_stylesheet_source))
    return gc.root_cell(&css_default_stylesheet_sheet) else trap("VERIFY: the default style sheet")

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:187 Web::CSS::quirks_mode_stylesheet.
func css_quirks_mode_stylesheet() -> CssCssStyleSheet*:
    if gc.root_is_null(&css_quirks_mode_stylesheet_sheet):
        css_quirks_mode_stylesheet_sheet = gc.root_create(css_parse_user_agent_stylesheet(css_quirks_mode_stylesheet_source))
    return gc.root_cell(&css_quirks_mode_stylesheet_sheet) else trap("VERIFY: the quirks mode style sheet")

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:197 Web::CSS::mathml_stylesheet.
func css_mathml_stylesheet() -> CssCssStyleSheet*:
    if gc.root_is_null(&css_mathml_stylesheet_sheet):
        css_mathml_stylesheet_sheet = gc.root_create(css_parse_user_agent_stylesheet(css_mathml_stylesheet_source))
    return gc.root_cell(&css_mathml_stylesheet_sheet) else trap("VERIFY: the MathML style sheet")

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:207 Web::CSS::svg_stylesheet.
func css_svg_stylesheet() -> CssCssStyleSheet*:
    if gc.root_is_null(&css_svg_stylesheet_sheet):
        css_svg_stylesheet_sheet = gc.root_create(css_parse_user_agent_stylesheet(css_svg_stylesheet_source))
    return gc.root_cell(&css_svg_stylesheet_sheet) else trap("VERIFY: the SVG style sheet")

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:217 Web::CSS::StyleScope::for_each_stylesheet.
pub func css_style_scope_for_each_stylesheet(this: const CssStyleScope*, cascade_origin: CssCascadeOrigin, callback: ak.Function1[CssCssStyleSheet*, unit]):
    if cascade_origin == CssCascadeOrigin.user_agent:
        ak.function1_call(&callback, css_default_stylesheet())
        if dom_document_in_quirks_mode(css_style_scope_document(this)):
            ak.function1_call(&callback, css_quirks_mode_stylesheet())
        ak.function1_call(&callback, css_mathml_stylesheet())
        ak.function1_call(&callback, css_svg_stylesheet())
    if cascade_origin == CssCascadeOrigin.user:
        let style_scope = (CssStyleScope*)this
        css_style_scope_build_user_style_sheet_if_needed(style_scope)
        if let user_style_sheet = style_scope.m_user_style_sheet:
            ak.function1_call(&callback, user_style_sheet)
    if cascade_origin == CssCascadeOrigin.author:
        css_style_scope_for_each_active_css_style_sheet(this, callback)

# mark: make_rule_cache_for_cascade_origin ======================================================

## The captures of make_rule_cache_for_cascade_origin's for_each_stylesheet lambda.
struct CssStyleScopeMakeRuleCacheForCascadeOrigin:
    var cascade_origin: CssCascadeOrigin
    var style_cache: CssStyleCache*
    var style_sheet_index: usize

## The captures of the lambda over a sheet's effective style-producing rules.
struct CssStyleScopeMakeRuleCacheForCascadeOriginRule:
    var outer: CssStyleScopeMakeRuleCacheForCascadeOrigin*
    var rule_caches: CssRuleCaches*
    var sheet: CssCssStyleSheet*
    var rule_index: usize

## The captures of the lambda over a sheet's effective @keyframes rules.
struct CssStyleScopeMakeRuleCacheForCascadeOriginKeyframes:
    var rule_caches: CssRuleCaches*

## The captures of the keyframes lambda's for_each_property_expanding_shorthands callback.
struct CssStyleScopeMakeRuleCacheForCascadeOriginLonghand:
    var animated_properties: ak.HashTable[css_data.PropertyId, css_data.PropertyIdTraits]*
    var resolved_keyframe: AnimationsKeyframeEffectKeyFrameSetResolvedKeyFrame*

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:237 Web::CSS::StyleScope::make_rule_cache_for_cascade_origin.
pub func css_style_scope_make_rule_cache_for_cascade_origin(this: CssStyleScope*, cascade_origin: CssCascadeOrigin, style_cache: CssStyleCache*):
    var captures = CssStyleScopeMakeRuleCacheForCascadeOrigin(cascade_origin = cascade_origin, style_cache = style_cache, style_sheet_index = 0)
    css_style_scope_for_each_stylesheet(this, cascade_origin, ak.Function1[CssCssStyleSheet*, unit](call = css_style_scope_make_rule_cache_for_sheet, context = &captures))

## make_rule_cache_for_cascade_origin's for_each_stylesheet lambda.
func css_style_scope_make_rule_cache_for_sheet(context: void*?, sheet: CssCssStyleSheet*):
    let captures = (CssStyleScopeMakeRuleCacheForCascadeOrigin*)(context else trap("no captures"))
    let style_cache = captures.style_cache
    var rule_caches: CssRuleCaches* = ---
    match captures.cascade_origin:
        .author:
            rule_caches = &style_cache.author_rule_cache
        .user:
            rule_caches = &style_cache.user_rule_cache
        .user_agent:
            rule_caches = &style_cache.user_agent_rule_cache
        _:
            trap("VERIFY_NOT_REACHED")

    var rule_captures = CssStyleScopeMakeRuleCacheForCascadeOriginRule(outer = captures, rule_caches = rule_caches, sheet = sheet, rule_index = 0)
    css_css_style_sheet_for_each_effective_style_producing_rule(sheet, ak.Function1[CssRule*, unit](call = css_style_scope_make_rule_cache_for_rule, context = &rule_captures))

    # Loosely based on https://drafts.csswg.org/css-animations-2/#keyframe-processing
    var keyframes_captures = CssStyleScopeMakeRuleCacheForCascadeOriginKeyframes(rule_caches = rule_caches)
    css_css_style_sheet_for_each_effective_keyframes_at_rule(sheet, ak.Function1[CssKeyframesRule*, unit](call = css_style_scope_make_rule_cache_for_keyframes, context = &keyframes_captures))
    captures.style_sheet_index += 1

## A style-producing rule's absolutized selectors: a CSSStyleRule's, or a CSSNestedDeclarations' parent style rule's.
func css_style_scope_absolutized_selectors_of(rule: CssRule*) -> ak.Vector[CssSelector*]:
    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")

## make_rule_cache_for_cascade_origin's lambda over the sheet's effective style-producing rules.
func css_style_scope_make_rule_cache_for_rule(context: void*?, rule: CssRule*):
    let captures = (CssStyleScopeMakeRuleCacheForCascadeOriginRule*)(context else trap("no captures"))
    let style_cache = captures.outer.style_cache
    let absolutized_selectors = css_style_scope_absolutized_selectors_of(rule)

    for selector in ak.vector_span_const(&absolutized_selectors):
        css_style_invalidation_data_build_invalidation_sets_for_selector(&style_cache.style_invalidation_data, selector)

    for selector in ak.vector_span_const(&absolutized_selectors):
        let target_pseudo_element = css_selector_target_pseudo_element(selector)
        let matching_rule = CssMatchingRule(
            rule = rule,
            sheet = captures.sheet,
            default_namespace = css_css_style_sheet_default_namespace(captures.sheet),
            selector = selector,
            style_sheet_index = captures.outer.style_sheet_index,
            rule_index = captures.rule_index,
            specificity = css_selector_specificity(selector),
            cascade_origin = captures.outer.cascade_origin,
            contains_pseudo_element = target_pseudo_element != none,
            slotted = css_selector_is_slotted(selector),
            contains_part_pseudo_element = css_selector_has_part_pseudo_element(selector),
        )

        let qualified_layer_name = css_matching_rule_qualified_layer_name(&matching_rule)
        var rule_cache: CssRuleCache* = &captures.rule_caches.main
        if not ak.fly_string_is_empty(&qualified_layer_name):
            if let existing = ak.hash_map_get_k(&captures.rule_caches.by_layer, qualified_layer_name):
                rule_cache = *existing
            else:
                let layer_rule_cache = new CssRuleCache else trap("out of memory")
                _ = ak.hash_map_set(&captures.rule_caches.by_layer, qualified_layer_name, layer_rule_cache)
                rule_cache = layer_rule_cache

        css_style_scope_collect_selector_insights(selector, &style_cache.selector_insights)

        var contains_root_pseudo_class = false
        let compound_selectors = css_selector_compound_selectors(selector)
        let last_compound_selector = ak.vector_last_const(&compound_selectors)
        for simple_selector in ak.vector_span_const(&last_compound_selector.simple_selectors):
            if not contains_root_pseudo_class:
                if simple_selector.type_ == CssSelectorSimpleSelectorType.pseudo_class and css_selector_simple_selector_pseudo_class(&simple_selector).type_ == css_data.PseudoClass.root:
                    contains_root_pseudo_class = true

        for i in 0..<(usize)css_data.PseudoClass.count:
            let pseudo_class = (css_data.PseudoClass)i
            # If we're not building a rule cache for this pseudo class, just ignore it.
            let pseudo_class_rule_cache = style_cache.pseudo_class_rule_cache[i] else continue
            if css_selector_contains_pseudo_class(selector, pseudo_class):
                # For pseudo class rule caches we intentionally pass no pseudo-element, because we don't want to bucket pseudo class rules by pseudo-element type.
                css_rule_cache_add_rule(pseudo_class_rule_cache, &matching_rule, none, contains_root_pseudo_class)

        var pseudo_element_type: css_data.PseudoElement? = none
        if let pseudo_element = target_pseudo_element:
            pseudo_element_type = css_selector_pseudo_element_selector_type(&pseudo_element)
        css_rule_cache_add_rule(rule_cache, &matching_rule, pseudo_element_type, contains_root_pseudo_class)
    captures.rule_index += 1

## The keyframes lambda's for_each_property_expanding_shorthands callback.
func css_style_scope_make_rule_cache_for_keyframes_longhand(context: void*?, shorthand_id: css_data.PropertyId, shorthand_value: CssStyleValue*):
    let captures = (CssStyleScopeMakeRuleCacheForCascadeOriginLonghand*)(context else trap("no captures"))
    _ = ak.hash_table_set(captures.animated_properties, shorthand_id)
    _ = ak.hash_map_set(&captures.resolved_keyframe.properties, shorthand_id, AnimationsKeyframeEffectKeyFrameSetUseInitialOrCssStyleValue.css_style_value(shorthand_value))

## make_rule_cache_for_cascade_origin's lambda over the sheet's effective @keyframes rules.
func css_style_scope_make_rule_cache_for_keyframes(context: void*?, rule: CssKeyframesRule*):
    let captures = (CssStyleScopeMakeRuleCacheForCascadeOriginKeyframes*)(context else trap("no captures"))
    let keyframe_set = new AnimationsKeyframeEffectKeyFrameSet else trap("out of memory")
    var animated_properties: ak.HashTable[css_data.PropertyId, css_data.PropertyIdTraits]

    # Forwards pass, resolve all the user-specified keyframe properties.
    let keyframe_rules = css_keyframes_rule_css_rules(rule)
    for keyframe_rule in ak.vector_span(&keyframe_rules.m_rules):
        let keyframe = as_css_keyframe_rule(keyframe_rule)
        var resolved_keyframe = animations_keyframe_effect_key_frame_set_resolved_key_frame_new()

        let keyframe_key = css_keyframe_rule_key(keyframe)
        let key = (u64)(css_percentage_value(&keyframe_key) * animations_keyframe_effect_animation_key_frame_key_scale_factor)
        let keyframe_style = css_keyframe_rule_style(keyframe)
        let keyframe_properties = css_style_properties_properties(keyframe_style)
        for it in ak.vector_span_const(&keyframe_properties):
            if it.property_id == css_data.PropertyId.animation_timing_function:
                # animation-timing-function is a list property, but inside @keyframes only
                # a single value is meaningful.
                var easing_value = it.value
                if css_style_value_is_value_list(easing_value):
                    let list = css_style_value_as_value_list(easing_value)
                    if css_style_value_list_size(list) > 0:
                        easing_value = css_style_value_list_value_at(list, 0, false)
                    else:
                        continue
                if css_style_value_is_easing(easing_value) or css_style_value_is_keyword(easing_value):
                    resolved_keyframe.easing = EmptyOrCssEasingFunctionOrCssStyleValue.css_easing_function(css_easing_function_from_style_value(easing_value))
                else:
                    resolved_keyframe.easing = EmptyOrCssEasingFunctionOrCssStyleValue.css_style_value(easing_value)
                continue
            if it.property_id == css_data.PropertyId.animation_composition:
                let composition_str = css_style_value_to_string(it.value, css_syntax.SerializationMode.normal)
                var composition = css_data.AnimationComposition.replace
                if ak.string_eq_string_view(&composition_str, ak.sv("add")):
                    composition = css_data.AnimationComposition.add
                elif ak.string_eq_string_view(&composition_str, ak.sv("accumulate")):
                    composition = css_data.AnimationComposition.accumulate
                resolved_keyframe.composite = animations_css_animation_composition_to_bindings_composite_operation_or_auto(composition)
                continue
            if not css_data.is_animatable_property(it.property_id):
                continue

            # Unresolved properties will be resolved in collect_animation_into()
            var longhand_captures = CssStyleScopeMakeRuleCacheForCascadeOriginLonghand(animated_properties = &animated_properties, resolved_keyframe = &resolved_keyframe)
            css_style_computer_for_each_property_expanding_shorthands(it.property_id, it.value, ak.Function2[css_data.PropertyId, CssStyleValue*, unit](call = css_style_scope_make_rule_cache_for_keyframes_longhand, context = &longhand_captures))

        if let existing_keyframe = ak.red_black_tree_find(&keyframe_set.keyframes_by_key, key):
            for property in ak.hash_map_begin(&resolved_keyframe.properties):
                _ = ak.hash_map_set(&existing_keyframe.properties, property.key, property.value)
            if resolved_keyframe.composite != BindCompositeOperationOrAuto.auto:
                existing_keyframe.composite = resolved_keyframe.composite
            let easing_is_empty = match resolved_keyframe.easing:
                .empty => true
                _ => false
            if not easing_is_empty:
                existing_keyframe.easing = resolved_keyframe.easing
        else:
            ak.red_black_tree_insert(&keyframe_set.keyframes_by_key, key, resolved_keyframe)

    animations_keyframe_effect_generate_initial_and_final_frames(keyframe_set, &animated_properties)

    if css_libweb_css_debug:
        let name = css_keyframes_rule_name(rule)
        ak.dbgln(f"Resolved keyframe set '{(str)ak.fly_string_bytes(&name)}' into {ak.base_red_black_tree_size(&keyframe_set.keyframes_by_key.base)} keyframes:")
        var it = ak.red_black_tree_begin(&keyframe_set.keyframes_by_key)
        while not ak.red_black_tree_iterator_is_end(&it):
            let keyframe = ak.red_black_tree_iterator_deref(&it)
            ak.dbgln(f"    - keyframe {ak.red_black_tree_iterator_key(&it)}: {ak.hash_map_size(&keyframe.properties)} properties")
            _ = ak.red_black_tree_iterator_inc(&it)

    _ = ak.hash_map_set(&captures.rule_caches.main.rules_by_animation_keyframes, css_keyframes_rule_name(rule), keyframe_set)

# mark: Selector insights =======================================================================

## Ported from Libraries/LibWeb/CSS/StyleScope.cpp:391 Web::CSS::StyleScope::collect_selector_insights.
pub func css_style_scope_collect_selector_insights(selector: const CssSelector*, insights: CssSelectorInsights*):
    let compound_selectors = css_selector_compound_selectors(selector)
    for compound_selector in ak.vector_span_const(&compound_selectors):
        for simple_selector in ak.vector_span_const(&compound_selector.simple_selectors):
            if simple_selector.type_ == CssSelectorSimpleSelectorType.pseudo_class:
                let pseudo_class = css_selector_simple_selector_pseudo_class(&simple_selector)
                if pseudo_class.type_ == css_data.PseudoClass.has:
                    insights.has_has_selectors = true
                    for argument_selector in ak.vector_span_const(&pseudo_class.argument_selector_list):
                        let relative_compound_selectors = css_selector_compound_selectors(argument_selector)
                        for relative_compound_selector in ak.vector_span_const(&relative_compound_selectors):
                            if relative_compound_selector.combinator == CssSelectorCombinator.next_sibling or relative_compound_selector.combinator == CssSelectorCombinator.subsequent_sibling:
                                insights.has_has_selectors_with_relative_selector_that_has_sibling_combinator = true
                                break
                for argument_selector in ak.vector_span_const(&pseudo_class.argument_selector_list):
                    css_style_scope_collect_selector_insights(argument_selector, insights)
            elif simple_selector.type_ == CssSelectorSimpleSelectorType.pseudo_element:
                # Pseudo-elements like ::slotted(...) carry a compound selector argument whose contents need the
                # same insight collection pass.
                let pseudo_element = css_selector_simple_selector_pseudo_element(&simple_selector)
                if css_selector_pseudo_element_selector_type(&pseudo_element) == css_data.PseudoElement.slotted:
                    css_style_scope_collect_selector_insights(css_selector_pseudo_element_selector_compound_selector(&pseudo_element), insights)